Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
|
---|---|---|---|---|---|
1,202,075 | I would like to update a table in mySql with data from another table.
I have two tables "people" and "business". The people table is linked to the business table by a column called "business\_id".
The necessary table structure, primary key is starred (Table: columns):
People: \*business\_id, \*sort\_order, email
Business: \*business\_id, email
I would like to update the business table email column with the email from the people table, something like this (I know I am missing something here):
```
UPDATE business b SET email = (SELECT email from People p where p.business_id = b.business_id AND sort_order = '1') WHERE b.email = '';
```
Does this make sense? Is it possible? | 2009/07/29 | [
"https://Stackoverflow.com/questions/1202075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54259/"
] | ```
UPDATE business b, people p
SET b.email = p.email
WHERE b.business_id = p.business_id
AND p.sort_order = '1'
AND b.email = ''
``` | Note, if sort\_order is an INT, then don't use '1' - use 1:
```
UPDATE business b
JOIN People p
ON p.business_id = b.business_id
AND p.sort_order = '1'
SET b.email = p.email
WHERE b.email = '';
``` |
1,202,075 | I would like to update a table in mySql with data from another table.
I have two tables "people" and "business". The people table is linked to the business table by a column called "business\_id".
The necessary table structure, primary key is starred (Table: columns):
People: \*business\_id, \*sort\_order, email
Business: \*business\_id, email
I would like to update the business table email column with the email from the people table, something like this (I know I am missing something here):
```
UPDATE business b SET email = (SELECT email from People p where p.business_id = b.business_id AND sort_order = '1') WHERE b.email = '';
```
Does this make sense? Is it possible? | 2009/07/29 | [
"https://Stackoverflow.com/questions/1202075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54259/"
] | ```
UPDATE business b, people p
SET b.email = p.email
WHERE b.business_id = p.business_id
AND p.sort_order = '1'
AND b.email = ''
``` | Try this, it works fine for me.
```
Update table a, table b
Set a.importantField = b.importantField,
a.importantField2 = b.importantField2
where a.matchedfield = b.matchedfield;
``` |
1,202,075 | I would like to update a table in mySql with data from another table.
I have two tables "people" and "business". The people table is linked to the business table by a column called "business\_id".
The necessary table structure, primary key is starred (Table: columns):
People: \*business\_id, \*sort\_order, email
Business: \*business\_id, email
I would like to update the business table email column with the email from the people table, something like this (I know I am missing something here):
```
UPDATE business b SET email = (SELECT email from People p where p.business_id = b.business_id AND sort_order = '1') WHERE b.email = '';
```
Does this make sense? Is it possible? | 2009/07/29 | [
"https://Stackoverflow.com/questions/1202075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54259/"
] | Note, if sort\_order is an INT, then don't use '1' - use 1:
```
UPDATE business b
JOIN People p
ON p.business_id = b.business_id
AND p.sort_order = '1'
SET b.email = p.email
WHERE b.email = '';
``` | Try this, it works fine for me.
```
Update table a, table b
Set a.importantField = b.importantField,
a.importantField2 = b.importantField2
where a.matchedfield = b.matchedfield;
``` |
40,407,955 | I have component that renders jsx like this
```
<section>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
</section>
```
I want this behavior, when I click the button in the first div, the input in the first div will show. Similarly, I click the button in the third div the input in third div will show.
How you do that in react? | 2016/11/03 | [
"https://Stackoverflow.com/questions/40407955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455340/"
] | If it were me I would make a new component out of:
show input
Lets call it `<InputToggler/>`
and then it would have a state of inputHidden for its own input and use classes to determine if it should show or not and the button would have an onclick handler to toggle the state of hidden or shown. Here is a pen showing exactly that
<http://codepen.io/finalfreq/pen/VKPXoN>
```
class InputToggler extends React.Component {
constructor() {
super();
this.state = {
inputHidden: true
}
}
toggleInput = () => {
this.setState({
inputHidden: !this.state.inputHidden
})
};
render() {
const inputClass = this.state.inputHidden ? 'hide' : '';
const buttonLabel = this.state.inputHidden ? 'show input' : 'hide input'
return (
<span>
<input type="text" className={inputClass} />
<button onClick={this.toggleInput} id={this.props.item.uniqueID}>
{buttonLabel}
</button>
</span>
)
}
}
``` | This is the concept not the exact code.
Each button should have onClick with callback to a function ex. toggleShow
```
<button id={item.uniqueID} onClick={this.toggleShow.bind(this)}>show input</button>
```
toggleShow do something like:
```
toggleShow(e){
var item = e.target.id;
this.setState({inputClassName1: "hide"})
```
at the same time the input field classname should refer to the state
Note that I omitted the fact that you have multiple objects, you may want to handle their references in arrays. |
35,917,100 | I am developing an Android app. In my app I need to work with tabs. But when I add tabs to TabLayout in code, it is throwing error. What is wrong with my code?
This is my tablayout XML in custom action bar:
```
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:background="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/action_bar_padding_top"
android:paddingBottom="@dimen/action_bar_padding_bottom"
android:paddingLeft="@dimen/action_bar_padding_left"
android:paddingRight="@dimen/action_bar_padding_right">
<ImageButton
android:id="@+id/open_left_drawer_icon"
android:background="@drawable/nav_open"
android:layout_width="@dimen/nav_icon_width"
android:layout_height="@dimen/nav_icon_height" />
<TextView
android:layout_centerHorizontal="true"
android:text="@string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/main_logo_text_size"/>
<ImageButton
android:layout_alignParentRight="true"
android:background="@drawable/wishlist_icon"
android:layout_width="@dimen/nav_icon_width"
android:layout_height="@dimen/nav_icon_height" />
</RelativeLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/main_tab_layout"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize" />
</LinearLayout> </LinearLayout>
```
How I set up tabs to tablayout in activity:
```
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout)findViewById(R.id.main_tab_layout);
setupTabs();
}
private void setupTabs() {
tabLayout.addTab(tabLayout.newTab().setTag(1).setText("TRENDY/HOT"));
tabLayout.addTab(tabLayout.newTab().setTag(2).setText("MEN"));
tabLayout.addTab(tabLayout.newTab().setTag(3).setText("WOMEN"));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
break;
case 2:
break;
default:
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
break;
case 2:
break;
default:
break;
}
}
});
}
}
```
This is the error in logacat when I run the app:
```
03-10 12:52:12.610 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion W/dalvikvm: VFY: unable to resolve virtual method 496: Landroid/content/res/TypedArray;.getType (I)I
03-10 12:52:12.610 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
03-10 12:52:12.618 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed 143K, 10% free 2617K/2892K, paused 3ms, total 4ms
03-10 12:52:12.670 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed 21K, 10% free 2870K/3168K, paused 1ms, total 2ms
03-10 12:52:12.706 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed 98K, 12% free 2992K/3392K, paused 3ms, total 3ms
03-10 12:52:12.710 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion I/dalvikvm-heap: Grow heap (frag case) to 4.121MB for 1127532-byte allocation
03-10 12:52:12.718 7428-7430/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_CONCURRENT freed <1K, 9% free 4093K/4496K, paused 2ms+1ms, total 7ms
03-10 12:52:12.722 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed <1K, 9% free 4094K/4496K, paused 2ms, total 2ms
03-10 12:52:12.726 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion I/dalvikvm-heap: Grow heap (frag case) to 6.541MB for 2536932-byte allocation
03-10 12:52:12.734 7428-7430/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_CONCURRENT freed 0K, 6% free 6571K/6976K, paused 1ms+1ms, total 4ms
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/AndroidRuntime: Shutting down VM
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa61d4908)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: FATAL EXCEPTION: main
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blog.waiyanhein.mmfashion.mmfashion/com.blog.waiyanhein.mmfashion.mmfashion.MainActivity}: java.lang.NullPointerException
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5041)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: Caused by: java.lang.NullPointerException
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.mmfashion.MainActivity.setupTabs(MainActivity.java:395)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.mmfashion.MainActivity.onCreate(MainActivity.java:98)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5104)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5041)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
03-10 12:52:12.778 396-407/system_process W/ActivityManager: Force finishing activity com.blog.waiyanhein.mmfashion.mmfashion/.MainActivity
03-10 12:52:12.898 396-407/system_process D/dalvikvm: GC_FOR_ALLOC freed 175K, 35% free 6244K/9560K, paused 16ms, total 16ms
03-10 12:52:12.898 396-407/system_process I/dalvikvm-heap: Grow heap (frag case) to 7.042MB for 856092-byte allocation
03-10 12:52:12.910 396-411/system_process D/dalvikvm: GC_FOR_ALLOC freed 4K, 32% free 7075K/10400K, paused 12ms, total 12ms
03-10 12:52:12.938 396-399/system_process D/dalvikvm: GC_CONCURRENT freed 7K, 31% free 7191K/10400K, paused 9ms+1ms, total 28ms
03-10 12:52:12.938 396-412/system_process D/dalvikvm: WAIT_FOR_CONCURRENT_GC blocked 4ms
```
Why cannot set tabs to TabLayout? But when I remove calling setUpTabs function in onCreate, app is running fine. | 2016/03/10 | [
"https://Stackoverflow.com/questions/35917100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4675736/"
] | Your id of TabLayout in your xml is `@+id/tab_layout"` but you're finding the view with id `main_tab_layout` in your Activity.
Line `tabLayout = (TabLayout)findViewById(R.id.main_tab_layout);`
It should be `tabLayout = (TabLayout)findViewById(R.id.tab_layout);` | I believe that you are referencing the wrong tablayout.
You define android:id="@+id/tab\_layout" in your xml but you are looking for tabLayout = (TabLayout)findViewById(R.id.main\_tab\_layout);.
Try changing findViewById(R.id.main\_tab\_layout) to findViewById(R.id.tab\_layout).
If this doesn't work could you include the rest of the XML? |
26,455,839 | I just came across this code:
```
array_filter(array_map('intval', $array));
```
It seems to return all entries of $array converted to int where the number is > 0.
However, I can't see on the manual page that this is defined. It is supposed to return the array value if the callback function evaluates to true. But there isn't any callback function defined here.
Confusing is also that the callback function is optional on [the manual page](http://php.net/manual/en/function.array-filter.php). | 2014/10/19 | [
"https://Stackoverflow.com/questions/26455839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123594/"
] | Removes empty or equivalent values from array:
```
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => '',
5 => 0
);
print_r(array_filter($entry));
```
**Result**
```
Array
(
[0] => foo
[2] => -1
)
```
See the [original documentation](http://php.net/manual/en/function.array-filter.php#example-6190) from the manual:
**Example #2 array\_filter() without callback** | If you read just a little further on the page to which you linked, you find, "If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed." |
329,336 | In my quest to better my experience in my windows 7 environment, I have installed cygwin and have started using mintty as my command line interface tool. This has been nice and takes me back to my more productive days in working in a unix environment.
There is one annoying thing however, that I can't seem to get working correctly. Batch files (i.e. \*.bat) will not auto complete on the command line, nor will they show up properly colored when ls --color is used. I've tracked this down (I think) to the fact that the bat files are showing up as rw-r--r--. I can do something like ./run\_my\_batch\_file.bat from the command line and the batch file will properly run, but I have to type the full filename or else auto complete will not pick it up.
I did try running 'chmod 750' (as well as various other file modes) to change the batch file to sport the 'x' bit, but their mode bits did not change. I'm pretty sure that I can attribute this to the fact that I am mounting my local drives with the 'noacl' option. Here is the relevant line from my fstab:
```
none /cygdrive cygdrive binary,posix=0,user,noacl 0 0
```
I put the 'noacl' in because without it, the file mode bits seems all screwed up. Here is an example listing without the 'noacl' parameter.
```
-r-x------+ 1 Administrators Domain Users 209K Jul 18 16:46 some.dll
-rwx------+ 1 Administrators Domain Users 867K Aug 22 11:21 binary_filea
-rwx------+ 1 Administrators Domain Users 736K Aug 28 18:02 binary_fileb
-rwx------+ 1 Administrators Domain Users 736K Aug 28 17:43 binary_filec
-rwx------+ 1 Administrators Domain Users 14K Jan 21 2010 cache_00.bak
-r-x------+ 1 Administrators Domain Users 354K Jun 6 22:42 cdb.exe
-rwx------+ 1 Administrators Domain Users 22 Mar 14 08:05 cleanup_scratch_folder.bat
drwx------+ 1 Administrators Domain Users 0 Mar 3 14:59 code
-rwx------+ 1 Administrators Domain Users 1.8K Aug 12 14:34 config.txt
-rwx------+ 1 Administrators Domain Users 52 Aug 28 19:05 console_history
-rwx------+ 1 Administrators Domain Users 3.8M Aug 23 09:46 copy_files.bat
```
(note that the directory listing above is from my /cygdrive/d drive - which is a local NTFS filesystem). That seemed pretty messed up so I went with the 'noacl' mount option to get me accurate file modes for the files in my directories.
One last note - I do have the full bash completion package installed. I briefly looked to see if I could modify one of the completion packages to get at least part of what I want (which is batch file auto completion), but I didn't find anything that would be relevant there.
So my questions can I properly change the batch file file modes to include 'x' so that I can get proper bash command line completion on them (as well as get proper directory coloring on them because they are executable files). Auto-complete is more important FWIW.
Thanks. | 2011/08/29 | [
"https://superuser.com/questions/329336",
"https://superuser.com",
"https://superuser.com/users/27663/"
] | I'm not sure of the answer to your question, but here are a few things that might help:
* Check that the `PATHEXT` environment variable includes `.BAT`.
* Read about the `noacl` option [here](http://www.cygwin.com/cygwin-ug-net/using.html). It seems that you might do better to remove `noacl`, and spend some time getting the real permissions right.
* Ask on the [cygwin mailing list](http://cygwin.com/lists.html#cygwin). There are many experts there who can almost certainly answer your question. | For those who uses `noacl` options (the only sane option to live outside of Cygwin) add single colon `:` as a first line of your batch file.
Official docs says:
>
> Files ending in certain extensions (.exe, .com, .lnk) are assumed
> to be executable. Files whose first two characters
> are "#!", "MZ", or ":\n" are also considered to be executable.
>
>
> |
63,595,089 | I'm trying to set chrome as default browser for launching jupyter notebook. For this i'm following the usual steps-
1. In anaconda prompt, i fired- `jupyter notebook --generate-config`
,a config file 'jupyter\_notebook\_config.py' is created.
2. Opened the file in notepad & change the line `# c.NotebookApp.browser = ''` to `c.NotebookApp.browser = u'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'`
3. Saved the file & run the file, got an error, PF the Screenshot-
[error](https://i.stack.imgur.com/ey2MB.png)
Traceback (most recent call last):
File "jupyter\_notebook\_config.py", line 99, in
c.NotebookApp.browser = u'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
NameError: name 'c' is not defined
Can anyone please let me know what is object c here, which class it invokes? | 2020/08/26 | [
"https://Stackoverflow.com/questions/63595089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13994287/"
] | In windows 10 - Goto file explorer - browse to C:\Users\your user name\AppData\Roaming\jupyter\runtime. Locate the nbserver-####-open.html files. Right click anyone of them. Select Properties (at bottom). With popup window, choose OPEN WITH: change button (at top) and select browser of your choice. | Why are you running `python jupyter_notebook_config.py`?
You are supposed to run `jupyter notebook` in the console. and *jupyter* should ideally read off the `config`, and you should get something like :
```
The Jupyter Notebook is running at:
[I 03:33:00.085 NotebookApp] http://localhost:8888/?token=...
``` |
52,220,105 | I want to format pagination in laravel like this:
```
api/posts?from=1&to=10
```
I tried:
```
$posts = new LengthAwarePaginator(Post::all(), 100, 10);
return $posts->toArray();
```
Which didn’t work at all :( Please help | 2018/09/07 | [
"https://Stackoverflow.com/questions/52220105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9764412/"
] | Try this
```
$x = array_search ('english', $request->all());
``` | use
```
$x = array_keys ($request->all(),'english');
```
returns all the keys having value english
if given only the array returns all the keys. The search field is included as a second parameter to get keys for the given search value and there is a optional third parameter strict which may be either true or false, if set strict validation occurstrue |
69,254,790 | I have a small issue with my application that I spotted when testing it. I have a `println` statement that should run to inform the user they have entered an invalid **product code**.
I have a **for-loop** that will run through an Array List of objects where an if statement will match each item in said Array List to a local variable named **searchTerm**.
The issue is that if the **searchTerm** does not match the item[0] with in the ArrayList then, the else statement will run more than once, thus executing the `println` statement multiple times.
```
static void searchProduct() {
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
for (int i = 0; i < report.size(); i++) {
if (report.get(i).code.equals(searchTerm)) {
System.out.println("****************************************************************************"
+ "\nPRODUCT SEARCH RESULTS"
+ "\n****************************************************************************");
System.out.println("PRODUCT CODE >> " + report.get(i).code);
System.out.println("PRODUCT NAME >> " + report.get(i).name);
System.out.println("PRODUCT CATERGORY >> " + report.get(i).category);
System.out.println("PRODUCT WARRANTY >> " + report.get(i).warranty);
System.out.println("PRODUCT PRICE >> " + report.get(i).price);
System.out.println("PRODUCT LEVEL >> " + report.get(i).stock);
System.out.println("PRODUCT SUPPLIER >> " + report.get(i).supplier);
System.out.println("****************************************************************************");
}
else {
// System.out.println("The product cannot be located. Invalid Product");
}
}
System.out.println("Enter (1) to launch menu or any other key to exit");
String opt2 = in.nextLine();
if (opt2.equals("1")) {
mainMenu.Menu();
}
else { System.exit(0); }
}
``` | 2021/09/20 | [
"https://Stackoverflow.com/questions/69254790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16740107/"
] | Separate out the printing from the looping:
Loop through the list until you find the item:
```
Report r = null;
for (int i = 0; i < report.size(); ++i) {
if (report.get(i).code.equals(searchTerm)) {
r = report.get(i);
break;
}
}
// or
for (Report rep : report) {
if (rep.code.equals(searchTerm)) {
r = rep;
break;
}
}
// or
Report r = report.stream().filter(rep -> rep.code.equals(searchTerm)).findFirst().orElse(null);
```
Now, `r` is only non-null if you found something, so, after the loop:
```
if (r != null) {
// Print stuff.
} else {
// Print message saying you didn't find it.
}
``` | Use a boolean flag to detect if the product is found:
```
boolean found = false;
for (int i = 0; i < report.size(); i++) {
if (report.get(i).code.equals(searchTerm)) {
System.out.println("****************************************************************************"
+ "\nPRODUCT SEARCH RESULTS"
+ "\n****************************************************************************");
System.out.println("PRODUCT CODE >> " + report.get(i).code);
System.out.println("PRODUCT NAME >> " + report.get(i).name);
System.out.println("PRODUCT CATERGORY >> " + report.get(i).category);
System.out.println("PRODUCT WARRANTY >> " + report.get(i).warranty);
System.out.println("PRODUCT PRICE >> " + report.get(i).price);
System.out.println("PRODUCT LEVEL >> " + report.get(i).stock);
System.out.println("PRODUCT SUPPLIER >> " + report.get(i).supplier);
System.out.println("****************************************************************************");
found= true;
}
}
//end of the loop
if(!found) System.out.println("The product cannot be located. Invalid Product");
``` |
69,254,790 | I have a small issue with my application that I spotted when testing it. I have a `println` statement that should run to inform the user they have entered an invalid **product code**.
I have a **for-loop** that will run through an Array List of objects where an if statement will match each item in said Array List to a local variable named **searchTerm**.
The issue is that if the **searchTerm** does not match the item[0] with in the ArrayList then, the else statement will run more than once, thus executing the `println` statement multiple times.
```
static void searchProduct() {
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
for (int i = 0; i < report.size(); i++) {
if (report.get(i).code.equals(searchTerm)) {
System.out.println("****************************************************************************"
+ "\nPRODUCT SEARCH RESULTS"
+ "\n****************************************************************************");
System.out.println("PRODUCT CODE >> " + report.get(i).code);
System.out.println("PRODUCT NAME >> " + report.get(i).name);
System.out.println("PRODUCT CATERGORY >> " + report.get(i).category);
System.out.println("PRODUCT WARRANTY >> " + report.get(i).warranty);
System.out.println("PRODUCT PRICE >> " + report.get(i).price);
System.out.println("PRODUCT LEVEL >> " + report.get(i).stock);
System.out.println("PRODUCT SUPPLIER >> " + report.get(i).supplier);
System.out.println("****************************************************************************");
}
else {
// System.out.println("The product cannot be located. Invalid Product");
}
}
System.out.println("Enter (1) to launch menu or any other key to exit");
String opt2 = in.nextLine();
if (opt2.equals("1")) {
mainMenu.Menu();
}
else { System.exit(0); }
}
``` | 2021/09/20 | [
"https://Stackoverflow.com/questions/69254790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16740107/"
] | Use a boolean flag to detect if the product is found:
```
boolean found = false;
for (int i = 0; i < report.size(); i++) {
if (report.get(i).code.equals(searchTerm)) {
System.out.println("****************************************************************************"
+ "\nPRODUCT SEARCH RESULTS"
+ "\n****************************************************************************");
System.out.println("PRODUCT CODE >> " + report.get(i).code);
System.out.println("PRODUCT NAME >> " + report.get(i).name);
System.out.println("PRODUCT CATERGORY >> " + report.get(i).category);
System.out.println("PRODUCT WARRANTY >> " + report.get(i).warranty);
System.out.println("PRODUCT PRICE >> " + report.get(i).price);
System.out.println("PRODUCT LEVEL >> " + report.get(i).stock);
System.out.println("PRODUCT SUPPLIER >> " + report.get(i).supplier);
System.out.println("****************************************************************************");
found= true;
}
}
//end of the loop
if(!found) System.out.println("The product cannot be located. Invalid Product");
``` | Switch the data structure used for searching the items in 'report' from a List to HashMap to avoid having to loop through all of them:
```
HashMap<String, Integer> quickSearchMapping;
quickSearchMapping = new HashMap<>();
for(int i=0 ; i<report.size ; i++ ){
quickSearchMapping.put(report.get(i).code, i);
}
while(TRUE){
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
if quickSearchMapping.containsKey(searchTerm){
Report the_report = report.get(quickSearchMapping.get(searchTerm));
//print to user stuff in the_report
break; //break if you wish to
} else {
System.out.println("Code entered didn't match any product.");
}
}
``` |
69,254,790 | I have a small issue with my application that I spotted when testing it. I have a `println` statement that should run to inform the user they have entered an invalid **product code**.
I have a **for-loop** that will run through an Array List of objects where an if statement will match each item in said Array List to a local variable named **searchTerm**.
The issue is that if the **searchTerm** does not match the item[0] with in the ArrayList then, the else statement will run more than once, thus executing the `println` statement multiple times.
```
static void searchProduct() {
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
for (int i = 0; i < report.size(); i++) {
if (report.get(i).code.equals(searchTerm)) {
System.out.println("****************************************************************************"
+ "\nPRODUCT SEARCH RESULTS"
+ "\n****************************************************************************");
System.out.println("PRODUCT CODE >> " + report.get(i).code);
System.out.println("PRODUCT NAME >> " + report.get(i).name);
System.out.println("PRODUCT CATERGORY >> " + report.get(i).category);
System.out.println("PRODUCT WARRANTY >> " + report.get(i).warranty);
System.out.println("PRODUCT PRICE >> " + report.get(i).price);
System.out.println("PRODUCT LEVEL >> " + report.get(i).stock);
System.out.println("PRODUCT SUPPLIER >> " + report.get(i).supplier);
System.out.println("****************************************************************************");
}
else {
// System.out.println("The product cannot be located. Invalid Product");
}
}
System.out.println("Enter (1) to launch menu or any other key to exit");
String opt2 = in.nextLine();
if (opt2.equals("1")) {
mainMenu.Menu();
}
else { System.exit(0); }
}
``` | 2021/09/20 | [
"https://Stackoverflow.com/questions/69254790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16740107/"
] | Separate out the printing from the looping:
Loop through the list until you find the item:
```
Report r = null;
for (int i = 0; i < report.size(); ++i) {
if (report.get(i).code.equals(searchTerm)) {
r = report.get(i);
break;
}
}
// or
for (Report rep : report) {
if (rep.code.equals(searchTerm)) {
r = rep;
break;
}
}
// or
Report r = report.stream().filter(rep -> rep.code.equals(searchTerm)).findFirst().orElse(null);
```
Now, `r` is only non-null if you found something, so, after the loop:
```
if (r != null) {
// Print stuff.
} else {
// Print message saying you didn't find it.
}
``` | Switch the data structure used for searching the items in 'report' from a List to HashMap to avoid having to loop through all of them:
```
HashMap<String, Integer> quickSearchMapping;
quickSearchMapping = new HashMap<>();
for(int i=0 ; i<report.size ; i++ ){
quickSearchMapping.put(report.get(i).code, i);
}
while(TRUE){
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
if quickSearchMapping.containsKey(searchTerm){
Report the_report = report.get(quickSearchMapping.get(searchTerm));
//print to user stuff in the_report
break; //break if you wish to
} else {
System.out.println("Code entered didn't match any product.");
}
}
``` |
47,061,829 | I'm trying to get image format plugins working on Android.
My plan is to build this [APNG](https://github.com/Skycoder42/qapng) image format plugin, which closely follows the style of the official Qt extra [image format plugins](http://doc.qt.io/qt-5/qtimageformats-index.html). The answer to my problem will be the same for these too.
On desktop (windows) it works. So long as you put the plugin DLL into a `imageformats` subdirectory like this:
```
myapp/<all my binaries>
imageformats/qapng.dll
```
But on Android, it's another story;
First idea was to put `libqapng.so` into `libs` so that `qtcreator` bundles it up with all the others as part of an APK build. It goes in, but is not loaded by Qt at runtime.
So i look into how the existing qt image formats work;
turns out, rather than being in a subdirectory, they are named according to this pattern;
`libplugins_imageformats_libqapng.so`
So i rename `libqapng.so` to the above and put that into `libs`. Nice try, but it didn't work.
After a lot of head scratching, i discover there's a secret *resource* array that connects the logical location of plugins to the physical file names;
This lives in;
`res/values/libs.xml`
and looks like this:
```
<array name="bundled_in_lib">
...
<item>libplugins_imageformats_libqgif.so:plugins/imageformats/libqgif.so</item>
<item>libplugins_imageformats_libqicns.so:plugins/imageformats/libqicns.so</item>
<item>libplugins_imageformats_libqico.so:plugins/imageformats/libqico.so</item>
<item>libplugins_imageformats_libqjpeg.so:plugins/imageformats/libqjpeg.so</item>
<item>libplugins_imageformats_libqsvg.so:plugins/imageformats/libqsvg.so</item>
<item>libplugins_imageformats_libqtga.so:plugins/imageformats/libqtga.so</item>
<item>libplugins_imageformats_libqtiff.so:plugins/imageformats/libqtiff.so</item>
<item>libplugins_imageformats_libqwbmp.so:plugins/imageformats/libqwbmp.so</item>
<item>libplugins_imageformats_libqwebp.so:plugins/imageformats/libqwebp.so</item>
....
```
So, i just need to get my new plugin into that list.
Sure enough, if i **HACK** it in, it works! but how to add my plugin to this list properly as part of the build?
[this](http://doc.qt.io/qt-5/deployment-android.html) page on Qt Android deployment mentions a thing called `bundled_in_lib`, which is indeed what i need. But it unfortunately does not explain how to change this or to add to it.
I'm thinking there might be a secret magic spell i can add to my `qmake` `.pro` file to affect this `bundled_in_lib` resource.
How to do it? or is there a better way that I've not yet seen. There doesn't seem to be much about explaining these details for Android.
On a final note, an alternative might be to manually load the plugin in `main.cpp`. I've tried this and it doesn't work. Perhaps, they need to be loaded by the Qt image format plugin loader rather than just *loaded* at all. Maybe there's a way to do this. not sure?
using Qt5.9.1
Thanks for any help. | 2017/11/01 | [
"https://Stackoverflow.com/questions/47061829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1964167/"
] | Following @Felix answer, `ANDROID_EXTRA_PLUGINS` is correct, but how it works is a bit strange.
Following a discussion on the lack of doc for this feature [here](https://bugreports.qt.io/browse/QTBUG-60022), and some trial and error, i found that;
`ANDROID_EXTRA_PLUGINS` must specify a *directory*, not a file. So you point to a plugins directory of your own. Things below this directory (including subdirectories) get mangled as in my original question and explained below.
So, for my plugin `libqapng.so`, i have:
`ANDROID_EXTRA_PLUGINS += <some path>/plugins`
and my android plugin building .pro puts the output in;
`<some path again>/plugins/imageformats/libqapng.so`
The `.so` lib, then winds up mangled in (eg. for arm);
`android-build/libs/armeabi-v7a/libplugins_imageformats_libqapng.so`
and the resources get the entry;
`android-build/res/values/libs.xml`
```
<array name="bundled_in_lib">
...
<item>libplugins_imageformats_libqapng.so:plugins/imageformats/libqapng.so</item>
</array>
```
as required.
Thanks to @Felix for almost the answer, but i thought I'd write up the extra details here for the benefit of others. | The answer is on the same site, a little lower on the page: [Android-specific qmake Variables](https://doc.qt.io/qt-5/deployment-android.html#android-specific-qmake-variables)
The one you are looking for is most likely `ANDROID_EXTRA_PLUGINS`. There is no usage example, so you will have to try out in wich format to add the plugin here.
My suggestions would be:
```
ANDROID_EXTRA_PLUGINS += imageformats/qapng
```
or
```
ANDROID_EXTRA_PLUGINS += plugins/imageformats/libqapng.so
```
... something like that. This should take care of all the renaming stuff etc. as well.
EDIT:
Its also very possible you need to enter the absolute path, i.e.
```
ANDROID_EXTRA_PLUGINS += $$[QT_INSTALL_PLUGINS]/imageformats/libqapng.so
```
or in whichever path you keep the plugin |
421,335 | So here's the question:
***We want to design a circuit that determines if a four-bit number is less than 10 and is also even.***
***a. (10 points) Write an expression of M such that M=1 if the four-bit number X (x3 x2 x1 x0) is less than 10
and is also even.***
Is this asking for the answer in POS form since it is using "M" instead of "m"? | 2019/02/09 | [
"https://electronics.stackexchange.com/questions/421335",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/212333/"
] | They probably want the simplest form. | Yes. The conventional representation for the POS form is M(.). Now, since the last bit for the even numbers is 0, it is enough to have 3 bits will all numbers from 0 to 4. So, we just need a mod 5 counter to generate all these numbers and the last bit of the four bits (LSB) being grounded always. |
48,333,458 | I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
```
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
<a href="">Read More . .</a>
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
```
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
```
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
``` | 2018/01/19 | [
"https://Stackoverflow.com/questions/48333458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7942721/"
] | You can use nested for loops to loop through all arguments. `argc` will tell you number of arguments, while `argv` contains the array of arrays. I also used `strlen()` function from `strings` library. It will tell you how long a string is. This way you can check for any number of arguments. Your *if* statement can also be changed to just 2, either `argc` is less than 2 or more than.
```
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return 1;
} else {
int i, x;
int ch = 0;
for (i=1; i<argc; i++) {
for (x = 0; x < strlen(argv[i]); x++) {
ch = argv[i][x];
if (ch == 'A' || ch == 'a' || ch == 'e')
printf('Vowel\n');
}
}
}
}
```
Python Equivalent for the nested loop
```
for i in range (0, argc):
for x in range(0, len(argv[i])):
ch = argv[i][x];
if ch in ('A', 'a', 'e'):
print('Vowel')
``` | While you can use multiple conditional expressions to test if the current character is a vowel, it is often beneficial to create a constant string containing all possible members of a set to test against (vowels here) and loop over your string of vowels to determine if the current character is a match.
Instead of looping, you can simply use your constant string as the string to test against in a call to `strchr` to determine if the current character is a member of the set.
The following simply uses a loop and a pointer to iterate over each character in each argument, and in like manner to iterate over each character in our constant string `char *vowels = "aeiouAEIOU";` to determine if the current character is a vowel (handling both lower and uppercase forms).
```
#include <stdio.h>
int main (int argc, char *argv[]) {
int i, nvowels = 0;
char *vowels = "aeiouAEIOU";
if (argc < 2) {
fprintf (stderr, "ERROR: You need at least one argument.\n");
return 1;
}
for (i = 1; i < argc; i++) { /* loop over each argument */
char *p = argv[i]; /* pointer to 1st char in argv[i] */
int vowelsinarg = 0; /* vowels per argument (optional) */
while (*p) { /* loop over each char in arg */
char *v = vowels; /* pointer to 1st char in vowels */
while (*v) { /* loop over each char in vowels */
if (*v == *p) { /* if char is vowel */
vowelsinarg++; /* increment number */
break; /* bail */
}
v++; /* increment pointer to vowels */
}
p++; /* increment pointer to arg */
}
printf ("argv[%2d] : %-16s (%d vowels)\n", i, argv[i], vowelsinarg);
nvowels += vowelsinarg; /* update total number of vowels */
}
printf ("\n Total: %d vowles\n", nvowels);
return 0;
}
```
**Example Use/Output**
```
$ ./bin/argvowelcnt My dog has FLEAS.
argv[ 1] : My (0 vowels)
argv[ 2] : dog (1 vowels)
argv[ 3] : has (1 vowels)
argv[ 4] : FLEAS. (2 vowels)
Total: 4 vowles
```
If you decided to use the `strchar` function from `string.h` to check if the current char was in your set of `vowels`, your inner loop over each character would be reduced to:
```
while (*p) { /* loop over each char in arg */
if (strchr (vowels, *p)) /* check if char is in vowels */
vowelsinarg++; /* increment number */
p++; /* increment pointer to arg */
}
```
Look things over and let me know if you have further questions. |
48,333,458 | I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
```
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
<a href="">Read More . .</a>
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
```
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
```
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
``` | 2018/01/19 | [
"https://Stackoverflow.com/questions/48333458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7942721/"
] | >
> `I was hoping someone could use the context of this question to help me understand pointers better....`
>
>
>
In context of your program:
```
int main(int argc, char *argv[])
```
First, understand what is `argc` and `argv` here.
**`argc`(argument count):** is the number of arguments passed into the program from the command line, including the name of the program.
**`argv`(argument vector):** An array of character pointers pointing to the string arguments passed.
A couple of points about `argv`:
* The string pointed to by `argv[0]` represents the program name.
* `argv[argc]` is a null pointer.
For better understanding, let's consider an example:
Say you are passing some command line arguments to a program -
```
# test have a nice day
```
`test` is the name of the executable file and `have`, `a`, `nice` and `day` are arguments passed to it and in this case, the argument count (`argc`) will be `5`.
The in-memory view of the argument vector (`argv`) will be something like this:
```
argv --
+----+ +-+-+-+-+--+ |
argv[0]| |--->|t|e|s|t|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+-+--+ |
argv[1]| |--->|h|a|v|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+--+ |
argv[2]| |--->|a|\0| > Null terminated char array (string)
| | +-+--+ |
+----+ +-+-+-+-+--+ |
argv[3]| |--->|n|i|c|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+--+ |
argv[4]| |--->|d|a|y|\0| |
| | +-+-+-+--+ |
+----+ --
argv[5]|NULL|
| |
+----+
```
A point to note about string (null-terminated character array) that it decays into pointer which is assigned to the type `char*`.
Since `argv` (argument vector) is an array of pointers pointing to string arguments passed. So,
```
argv+0 --> will give address of first element of array.
argv+1 --> will give address of second element of array.
...
...
and so on.
```
We can also get the address of the first element of the array like this - `&argv[0]`.
That means:
```
argv+0 and &argv[0] are same.
```
Similarly,
```
argv+1 and &argv[1] are same.
argv+2 and &argv[2] are same.
...
...
and so on.
```
When you dereference them, you will get the string they are pointing to:
```
*(argv+0) --> "test"
*(argv+1) --> "have"
....
....
and so on.
```
Similarly,
```
*(&argv[0]) --> "test"
```
`*(&argv[0])` can also written as `argv[0]`.
which means:
```
*(argv+0) can also written as argv[0].
```
So,
```
*(argv+0) and argv[0] are same
*(argv+1) and argv[1] are same
...
...
and so on.
```
When printing them:
```
printf ("%s", argv[0]); //---> print "test"
printf ("%s", *(argv+0)); //---> print "test"
printf ("%s", argv[3]); //---> print "nice"
printf ("%s", *(argv+3)); //---> print "nice"
```
And since the last element of argument vector is `NULL`, when we access - `argv[argc]` we get `NULL`.
To access characters of a string:
```
argv[1] is a string --> "have"
argv[1][0] represents first character of string --> 'h'
As we have already seen:
argv[1] is same as *(argv+1)
So,
argv[1][0] is same as *(*(argv+1)+0)
```
To access the second character of string "have", you can use:
```
argv[1][1] --> 'a'
or,
*(*(argv+1)+1) --> 'a'
```
I hope this will help you out in understanding pointers better in context of your question.
To identify the vowels in arguments passed to program, you can do:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return -1;
}
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++) {
/* Explaination:
* Initialization -
* char **pargv = argv+1; --> pargv pointer pointing second element of argv
* The first element of argument vector is program name
* Condition -
* *pargv != argv[argc]; --> *pargv iterate to argv array
* argv[argc] represents NULL
* So, the condition is *pargv != NULL
* This condition (*pargv != argv[argc]) is for your understanding
* If using only *pragv is also okay
* Loop iterator increment -
* pargv++
*/
printf ("Vowels in string \"%s\" : ", *pargv);
for (char *ptr = *pargv; *ptr != '\0'; ptr++) {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u'
|| *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U') {
printf ("%c ", *ptr);
}
}
printf ("\n");
}
return 0;
}
```
Output:
```
#./a.out have a nice day
Vowels in string "have" : a e
Vowels in string "a" : a
Vowels in string "nice" : i e
Vowels in string "day" : a
``` | You can use nested for loops to loop through all arguments. `argc` will tell you number of arguments, while `argv` contains the array of arrays. I also used `strlen()` function from `strings` library. It will tell you how long a string is. This way you can check for any number of arguments. Your *if* statement can also be changed to just 2, either `argc` is less than 2 or more than.
```
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return 1;
} else {
int i, x;
int ch = 0;
for (i=1; i<argc; i++) {
for (x = 0; x < strlen(argv[i]); x++) {
ch = argv[i][x];
if (ch == 'A' || ch == 'a' || ch == 'e')
printf('Vowel\n');
}
}
}
}
```
Python Equivalent for the nested loop
```
for i in range (0, argc):
for x in range(0, len(argv[i])):
ch = argv[i][x];
if ch in ('A', 'a', 'e'):
print('Vowel')
``` |
48,333,458 | I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
```
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
<a href="">Read More . .</a>
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
```
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
```
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
``` | 2018/01/19 | [
"https://Stackoverflow.com/questions/48333458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7942721/"
] | You can use nested for loops to loop through all arguments. `argc` will tell you number of arguments, while `argv` contains the array of arrays. I also used `strlen()` function from `strings` library. It will tell you how long a string is. This way you can check for any number of arguments. Your *if* statement can also be changed to just 2, either `argc` is less than 2 or more than.
```
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return 1;
} else {
int i, x;
int ch = 0;
for (i=1; i<argc; i++) {
for (x = 0; x < strlen(argv[i]); x++) {
ch = argv[i][x];
if (ch == 'A' || ch == 'a' || ch == 'e')
printf('Vowel\n');
}
}
}
}
```
Python Equivalent for the nested loop
```
for i in range (0, argc):
for x in range(0, len(argv[i])):
ch = argv[i][x];
if ch in ('A', 'a', 'e'):
print('Vowel')
``` | If anyone else is coming to this from *Learn C The Hard Way* the answers above using pointers are getting a bit far ahead of us as we won't be covering pointers until chapter 15. However you can do this piece of extra credit with what we've learned so far. I won't spoil the fun but you can use a for loop for the arguments with a nested for loop for the letters in those words; getting a letter from each word then is as simple as `argv[j][i]` where j is the jth arg passed and i the ith letter in j. No having to import header files or use pointers. I have to say I did come back to H.S's answer when I did come to pointers in chapter 15. |
48,333,458 | I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
```
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
<a href="">Read More . .</a>
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
```
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
```
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
``` | 2018/01/19 | [
"https://Stackoverflow.com/questions/48333458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7942721/"
] | >
> `I was hoping someone could use the context of this question to help me understand pointers better....`
>
>
>
In context of your program:
```
int main(int argc, char *argv[])
```
First, understand what is `argc` and `argv` here.
**`argc`(argument count):** is the number of arguments passed into the program from the command line, including the name of the program.
**`argv`(argument vector):** An array of character pointers pointing to the string arguments passed.
A couple of points about `argv`:
* The string pointed to by `argv[0]` represents the program name.
* `argv[argc]` is a null pointer.
For better understanding, let's consider an example:
Say you are passing some command line arguments to a program -
```
# test have a nice day
```
`test` is the name of the executable file and `have`, `a`, `nice` and `day` are arguments passed to it and in this case, the argument count (`argc`) will be `5`.
The in-memory view of the argument vector (`argv`) will be something like this:
```
argv --
+----+ +-+-+-+-+--+ |
argv[0]| |--->|t|e|s|t|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+-+--+ |
argv[1]| |--->|h|a|v|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+--+ |
argv[2]| |--->|a|\0| > Null terminated char array (string)
| | +-+--+ |
+----+ +-+-+-+-+--+ |
argv[3]| |--->|n|i|c|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+--+ |
argv[4]| |--->|d|a|y|\0| |
| | +-+-+-+--+ |
+----+ --
argv[5]|NULL|
| |
+----+
```
A point to note about string (null-terminated character array) that it decays into pointer which is assigned to the type `char*`.
Since `argv` (argument vector) is an array of pointers pointing to string arguments passed. So,
```
argv+0 --> will give address of first element of array.
argv+1 --> will give address of second element of array.
...
...
and so on.
```
We can also get the address of the first element of the array like this - `&argv[0]`.
That means:
```
argv+0 and &argv[0] are same.
```
Similarly,
```
argv+1 and &argv[1] are same.
argv+2 and &argv[2] are same.
...
...
and so on.
```
When you dereference them, you will get the string they are pointing to:
```
*(argv+0) --> "test"
*(argv+1) --> "have"
....
....
and so on.
```
Similarly,
```
*(&argv[0]) --> "test"
```
`*(&argv[0])` can also written as `argv[0]`.
which means:
```
*(argv+0) can also written as argv[0].
```
So,
```
*(argv+0) and argv[0] are same
*(argv+1) and argv[1] are same
...
...
and so on.
```
When printing them:
```
printf ("%s", argv[0]); //---> print "test"
printf ("%s", *(argv+0)); //---> print "test"
printf ("%s", argv[3]); //---> print "nice"
printf ("%s", *(argv+3)); //---> print "nice"
```
And since the last element of argument vector is `NULL`, when we access - `argv[argc]` we get `NULL`.
To access characters of a string:
```
argv[1] is a string --> "have"
argv[1][0] represents first character of string --> 'h'
As we have already seen:
argv[1] is same as *(argv+1)
So,
argv[1][0] is same as *(*(argv+1)+0)
```
To access the second character of string "have", you can use:
```
argv[1][1] --> 'a'
or,
*(*(argv+1)+1) --> 'a'
```
I hope this will help you out in understanding pointers better in context of your question.
To identify the vowels in arguments passed to program, you can do:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return -1;
}
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++) {
/* Explaination:
* Initialization -
* char **pargv = argv+1; --> pargv pointer pointing second element of argv
* The first element of argument vector is program name
* Condition -
* *pargv != argv[argc]; --> *pargv iterate to argv array
* argv[argc] represents NULL
* So, the condition is *pargv != NULL
* This condition (*pargv != argv[argc]) is for your understanding
* If using only *pragv is also okay
* Loop iterator increment -
* pargv++
*/
printf ("Vowels in string \"%s\" : ", *pargv);
for (char *ptr = *pargv; *ptr != '\0'; ptr++) {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u'
|| *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U') {
printf ("%c ", *ptr);
}
}
printf ("\n");
}
return 0;
}
```
Output:
```
#./a.out have a nice day
Vowels in string "have" : a e
Vowels in string "a" : a
Vowels in string "nice" : i e
Vowels in string "day" : a
``` | While you can use multiple conditional expressions to test if the current character is a vowel, it is often beneficial to create a constant string containing all possible members of a set to test against (vowels here) and loop over your string of vowels to determine if the current character is a match.
Instead of looping, you can simply use your constant string as the string to test against in a call to `strchr` to determine if the current character is a member of the set.
The following simply uses a loop and a pointer to iterate over each character in each argument, and in like manner to iterate over each character in our constant string `char *vowels = "aeiouAEIOU";` to determine if the current character is a vowel (handling both lower and uppercase forms).
```
#include <stdio.h>
int main (int argc, char *argv[]) {
int i, nvowels = 0;
char *vowels = "aeiouAEIOU";
if (argc < 2) {
fprintf (stderr, "ERROR: You need at least one argument.\n");
return 1;
}
for (i = 1; i < argc; i++) { /* loop over each argument */
char *p = argv[i]; /* pointer to 1st char in argv[i] */
int vowelsinarg = 0; /* vowels per argument (optional) */
while (*p) { /* loop over each char in arg */
char *v = vowels; /* pointer to 1st char in vowels */
while (*v) { /* loop over each char in vowels */
if (*v == *p) { /* if char is vowel */
vowelsinarg++; /* increment number */
break; /* bail */
}
v++; /* increment pointer to vowels */
}
p++; /* increment pointer to arg */
}
printf ("argv[%2d] : %-16s (%d vowels)\n", i, argv[i], vowelsinarg);
nvowels += vowelsinarg; /* update total number of vowels */
}
printf ("\n Total: %d vowles\n", nvowels);
return 0;
}
```
**Example Use/Output**
```
$ ./bin/argvowelcnt My dog has FLEAS.
argv[ 1] : My (0 vowels)
argv[ 2] : dog (1 vowels)
argv[ 3] : has (1 vowels)
argv[ 4] : FLEAS. (2 vowels)
Total: 4 vowles
```
If you decided to use the `strchar` function from `string.h` to check if the current char was in your set of `vowels`, your inner loop over each character would be reduced to:
```
while (*p) { /* loop over each char in arg */
if (strchr (vowels, *p)) /* check if char is in vowels */
vowelsinarg++; /* increment number */
p++; /* increment pointer to arg */
}
```
Look things over and let me know if you have further questions. |
48,333,458 | I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
```
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
<a href="">Read More . .</a>
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
```
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
```
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
``` | 2018/01/19 | [
"https://Stackoverflow.com/questions/48333458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7942721/"
] | While you can use multiple conditional expressions to test if the current character is a vowel, it is often beneficial to create a constant string containing all possible members of a set to test against (vowels here) and loop over your string of vowels to determine if the current character is a match.
Instead of looping, you can simply use your constant string as the string to test against in a call to `strchr` to determine if the current character is a member of the set.
The following simply uses a loop and a pointer to iterate over each character in each argument, and in like manner to iterate over each character in our constant string `char *vowels = "aeiouAEIOU";` to determine if the current character is a vowel (handling both lower and uppercase forms).
```
#include <stdio.h>
int main (int argc, char *argv[]) {
int i, nvowels = 0;
char *vowels = "aeiouAEIOU";
if (argc < 2) {
fprintf (stderr, "ERROR: You need at least one argument.\n");
return 1;
}
for (i = 1; i < argc; i++) { /* loop over each argument */
char *p = argv[i]; /* pointer to 1st char in argv[i] */
int vowelsinarg = 0; /* vowels per argument (optional) */
while (*p) { /* loop over each char in arg */
char *v = vowels; /* pointer to 1st char in vowels */
while (*v) { /* loop over each char in vowels */
if (*v == *p) { /* if char is vowel */
vowelsinarg++; /* increment number */
break; /* bail */
}
v++; /* increment pointer to vowels */
}
p++; /* increment pointer to arg */
}
printf ("argv[%2d] : %-16s (%d vowels)\n", i, argv[i], vowelsinarg);
nvowels += vowelsinarg; /* update total number of vowels */
}
printf ("\n Total: %d vowles\n", nvowels);
return 0;
}
```
**Example Use/Output**
```
$ ./bin/argvowelcnt My dog has FLEAS.
argv[ 1] : My (0 vowels)
argv[ 2] : dog (1 vowels)
argv[ 3] : has (1 vowels)
argv[ 4] : FLEAS. (2 vowels)
Total: 4 vowles
```
If you decided to use the `strchar` function from `string.h` to check if the current char was in your set of `vowels`, your inner loop over each character would be reduced to:
```
while (*p) { /* loop over each char in arg */
if (strchr (vowels, *p)) /* check if char is in vowels */
vowelsinarg++; /* increment number */
p++; /* increment pointer to arg */
}
```
Look things over and let me know if you have further questions. | If anyone else is coming to this from *Learn C The Hard Way* the answers above using pointers are getting a bit far ahead of us as we won't be covering pointers until chapter 15. However you can do this piece of extra credit with what we've learned so far. I won't spoil the fun but you can use a for loop for the arguments with a nested for loop for the letters in those words; getting a letter from each word then is as simple as `argv[j][i]` where j is the jth arg passed and i the ith letter in j. No having to import header files or use pointers. I have to say I did come back to H.S's answer when I did come to pointers in chapter 15. |
48,333,458 | I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
```
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
<a href="">Read More . .</a>
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
```
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
```
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
``` | 2018/01/19 | [
"https://Stackoverflow.com/questions/48333458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7942721/"
] | >
> `I was hoping someone could use the context of this question to help me understand pointers better....`
>
>
>
In context of your program:
```
int main(int argc, char *argv[])
```
First, understand what is `argc` and `argv` here.
**`argc`(argument count):** is the number of arguments passed into the program from the command line, including the name of the program.
**`argv`(argument vector):** An array of character pointers pointing to the string arguments passed.
A couple of points about `argv`:
* The string pointed to by `argv[0]` represents the program name.
* `argv[argc]` is a null pointer.
For better understanding, let's consider an example:
Say you are passing some command line arguments to a program -
```
# test have a nice day
```
`test` is the name of the executable file and `have`, `a`, `nice` and `day` are arguments passed to it and in this case, the argument count (`argc`) will be `5`.
The in-memory view of the argument vector (`argv`) will be something like this:
```
argv --
+----+ +-+-+-+-+--+ |
argv[0]| |--->|t|e|s|t|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+-+--+ |
argv[1]| |--->|h|a|v|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+--+ |
argv[2]| |--->|a|\0| > Null terminated char array (string)
| | +-+--+ |
+----+ +-+-+-+-+--+ |
argv[3]| |--->|n|i|c|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+--+ |
argv[4]| |--->|d|a|y|\0| |
| | +-+-+-+--+ |
+----+ --
argv[5]|NULL|
| |
+----+
```
A point to note about string (null-terminated character array) that it decays into pointer which is assigned to the type `char*`.
Since `argv` (argument vector) is an array of pointers pointing to string arguments passed. So,
```
argv+0 --> will give address of first element of array.
argv+1 --> will give address of second element of array.
...
...
and so on.
```
We can also get the address of the first element of the array like this - `&argv[0]`.
That means:
```
argv+0 and &argv[0] are same.
```
Similarly,
```
argv+1 and &argv[1] are same.
argv+2 and &argv[2] are same.
...
...
and so on.
```
When you dereference them, you will get the string they are pointing to:
```
*(argv+0) --> "test"
*(argv+1) --> "have"
....
....
and so on.
```
Similarly,
```
*(&argv[0]) --> "test"
```
`*(&argv[0])` can also written as `argv[0]`.
which means:
```
*(argv+0) can also written as argv[0].
```
So,
```
*(argv+0) and argv[0] are same
*(argv+1) and argv[1] are same
...
...
and so on.
```
When printing them:
```
printf ("%s", argv[0]); //---> print "test"
printf ("%s", *(argv+0)); //---> print "test"
printf ("%s", argv[3]); //---> print "nice"
printf ("%s", *(argv+3)); //---> print "nice"
```
And since the last element of argument vector is `NULL`, when we access - `argv[argc]` we get `NULL`.
To access characters of a string:
```
argv[1] is a string --> "have"
argv[1][0] represents first character of string --> 'h'
As we have already seen:
argv[1] is same as *(argv+1)
So,
argv[1][0] is same as *(*(argv+1)+0)
```
To access the second character of string "have", you can use:
```
argv[1][1] --> 'a'
or,
*(*(argv+1)+1) --> 'a'
```
I hope this will help you out in understanding pointers better in context of your question.
To identify the vowels in arguments passed to program, you can do:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return -1;
}
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++) {
/* Explaination:
* Initialization -
* char **pargv = argv+1; --> pargv pointer pointing second element of argv
* The first element of argument vector is program name
* Condition -
* *pargv != argv[argc]; --> *pargv iterate to argv array
* argv[argc] represents NULL
* So, the condition is *pargv != NULL
* This condition (*pargv != argv[argc]) is for your understanding
* If using only *pragv is also okay
* Loop iterator increment -
* pargv++
*/
printf ("Vowels in string \"%s\" : ", *pargv);
for (char *ptr = *pargv; *ptr != '\0'; ptr++) {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u'
|| *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U') {
printf ("%c ", *ptr);
}
}
printf ("\n");
}
return 0;
}
```
Output:
```
#./a.out have a nice day
Vowels in string "have" : a e
Vowels in string "a" : a
Vowels in string "nice" : i e
Vowels in string "day" : a
``` | If anyone else is coming to this from *Learn C The Hard Way* the answers above using pointers are getting a bit far ahead of us as we won't be covering pointers until chapter 15. However you can do this piece of extra credit with what we've learned so far. I won't spoil the fun but you can use a for loop for the arguments with a nested for loop for the letters in those words; getting a letter from each word then is as simple as `argv[j][i]` where j is the jth arg passed and i the ith letter in j. No having to import header files or use pointers. I have to say I did come back to H.S's answer when I did come to pointers in chapter 15. |
3,574 | I am getting the error -
`'System.QueryException: sObject type 'CollaborationGroup' is not supported.'`
When running the following code as part of a managed package by scheduled apex:
>
> List groups = [select id, name, description from
> collaborationGroup];
>
>
>
What's strange is that the code works if I run it in the developer console but not when it runs from scheduled apex (setup as part of a post install script).
I've got 'with sharing on' so could it be down to the installer user profile? It works in some installed instances but not others but can't see a reason e.g. SFDC edition, profile, chatter settings, etc...
I do know that Chatter has to be enabled but that is the case anyway in the partnerforce dev orgs.
What am I missing here? | 2012/10/22 | [
"https://salesforce.stackexchange.com/questions/3574",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/783/"
] | Your code must be run in a `without sharing` context in order for it to have access to the `CollaborationGroup` SObject. I'm guessing that your Utility class which contains the query is *not* explicitly declared as `without sharing`, so you can do one of two things:
1. Move all of your code into your actual PostInstall Script Apex class (the one that implements `InstallHandler`).
2. If possible, change the signature of your Utility class to be `without sharing`.
3. Extract out the particular logic that executes this query into a separate Utility class that is declared as `without sharing`. | It looks like your querying for `Group`, as in a [user group](http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_group.htm) instead of a `Collaboration Group` *which is the API name for a [Chatter group](http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_collaborationgroup.htm)*
```
List<CollaborationGroup> chatterGroups = [SELECT Id FROM CollaborationGroup];
```
vs.
```
List<Group> groups = [SELECT Id FROM Group];
```
Try explicitly querying for `CollaborationGroup` to get the type correct |
5,018,340 | I have this little piece of code, and I'm trying to convert a JSON string to a map.
```
String json = "[{'code':':)','img':'<img src=/faccine/sorriso.gif>'}]";
ObjectMapper mapper = new ObjectMapper();
Map<String,String> userData = mapper.readValue(json,new TypeReference<HashMap<String,String>>() { });
```
But it returns the following error:
```
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token
at [Source: java.io.StringReader@1b1756a4; line: 1, column: 1]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:198)
at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:151)
at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:25)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2131)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1402)
at CodeSnippet_19.run(CodeSnippet_19.java:13)
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1.eval(ScrapbookMain1.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain.evalLoop(ScrapbookMain.java:54)
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain.main(ScrapbookMain.java:35)
```
What am I doing wrong? | 2011/02/16 | [
"https://Stackoverflow.com/questions/5018340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613631/"
] | From what I remember Jackson is used to convert json to java classes - it is probably expecting the first object is reads to be a map, like
```
String json = "{'code':':)','img':'<img src=/faccine/sorriso.gif>'}";
``` | Right: you're asking Jackson to map a JSON Array into an object; there is no obvious way to do that. So, tofarr's answer is correct.
But if you wanted a List or an array, you could achieved it easily by:
```
List<?> list = mapper.readValue(json, List.class);
```
Or with full type reference; optional in this case because you just want Lists, Maps and Strings. |
57,698,746 | I am trying to do a migration in django 2.2.4 in python 3.7.
First I try to make do makemigations:
```
python3 manage.py makemigrations
```
I get:
```
Migrations for 'main':
main/migrations/0001_initial.py
- Create model TutorialCategory
- Create model TutorialSeries
- Create model Tutorial
```
But then I try the second step:
```
python3 manage.py migrate
```
I get:
```
Operations to perform:
Apply all migrations: admin, auth, contenttypes, main, sessions
Running migrations:
No migrations to apply.
```
Even though a migration should happen.
I tried deleting my migrations folder and then remaking it (with the empty `__init__.py` file inside) but it still doesn't work.
(Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) | 2019/08/28 | [
"https://Stackoverflow.com/questions/57698746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8802333/"
] | Somehow your migrations are virtually or faked applied in the database, Truncating **django\_migrations** table should work.
1. Delete all the migrations files:
find . -path "*/migrations/*.py" -not -name "**init**.py" -delete
find . -path "*/migrations/*.pyc" -delete
2. Truncate table:
truncate django\_migrations
3. makemigrations, migrate. | I faced the same problem in django 2.2, The following worked for me...
1. delete the migrations folder resided inside the app folder
2. delete the pycache folder too
3. restart the server [if your server is on and you are working from another cli]
4. `python manage.py makemigrations <app_name> zero`
5. `python manage.py makemigrations <app_name>` [explicit app\_name is important]
6. `python manage.py migrate` |
57,698,746 | I am trying to do a migration in django 2.2.4 in python 3.7.
First I try to make do makemigations:
```
python3 manage.py makemigrations
```
I get:
```
Migrations for 'main':
main/migrations/0001_initial.py
- Create model TutorialCategory
- Create model TutorialSeries
- Create model Tutorial
```
But then I try the second step:
```
python3 manage.py migrate
```
I get:
```
Operations to perform:
Apply all migrations: admin, auth, contenttypes, main, sessions
Running migrations:
No migrations to apply.
```
Even though a migration should happen.
I tried deleting my migrations folder and then remaking it (with the empty `__init__.py` file inside) but it still doesn't work.
(Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) | 2019/08/28 | [
"https://Stackoverflow.com/questions/57698746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8802333/"
] | Somehow your migrations are virtually or faked applied in the database, Truncating **django\_migrations** table should work.
1. Delete all the migrations files:
find . -path "*/migrations/*.py" -not -name "**init**.py" -delete
find . -path "*/migrations/*.pyc" -delete
2. Truncate table:
truncate django\_migrations
3. makemigrations, migrate. | 1. w/in the app directory I deleted the `pycache` and `migrations` folders,
2. from `django.migrations` tables I deleted all rows like this for PostgreSQL
```
DELETE FROM public.django_migrations
WHERE public.django_migrations.app = 'target_app_name';
```
3. To delete any app tables already created for the tables to be created from scratch. |
57,698,746 | I am trying to do a migration in django 2.2.4 in python 3.7.
First I try to make do makemigations:
```
python3 manage.py makemigrations
```
I get:
```
Migrations for 'main':
main/migrations/0001_initial.py
- Create model TutorialCategory
- Create model TutorialSeries
- Create model Tutorial
```
But then I try the second step:
```
python3 manage.py migrate
```
I get:
```
Operations to perform:
Apply all migrations: admin, auth, contenttypes, main, sessions
Running migrations:
No migrations to apply.
```
Even though a migration should happen.
I tried deleting my migrations folder and then remaking it (with the empty `__init__.py` file inside) but it still doesn't work.
(Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) | 2019/08/28 | [
"https://Stackoverflow.com/questions/57698746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8802333/"
] | Somehow your migrations are virtually or faked applied in the database, Truncating **django\_migrations** table should work.
1. Delete all the migrations files:
find . -path "*/migrations/*.py" -not -name "**init**.py" -delete
find . -path "*/migrations/*.pyc" -delete
2. Truncate table:
truncate django\_migrations
3. makemigrations, migrate. | Mine didn't migrate cause there was already a record in the django\_migrations table with the same name, so I just removed it and then migrate worked. |
57,698,746 | I am trying to do a migration in django 2.2.4 in python 3.7.
First I try to make do makemigations:
```
python3 manage.py makemigrations
```
I get:
```
Migrations for 'main':
main/migrations/0001_initial.py
- Create model TutorialCategory
- Create model TutorialSeries
- Create model Tutorial
```
But then I try the second step:
```
python3 manage.py migrate
```
I get:
```
Operations to perform:
Apply all migrations: admin, auth, contenttypes, main, sessions
Running migrations:
No migrations to apply.
```
Even though a migration should happen.
I tried deleting my migrations folder and then remaking it (with the empty `__init__.py` file inside) but it still doesn't work.
(Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) | 2019/08/28 | [
"https://Stackoverflow.com/questions/57698746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8802333/"
] | I faced the same problem in django 2.2, The following worked for me...
1. delete the migrations folder resided inside the app folder
2. delete the pycache folder too
3. restart the server [if your server is on and you are working from another cli]
4. `python manage.py makemigrations <app_name> zero`
5. `python manage.py makemigrations <app_name>` [explicit app\_name is important]
6. `python manage.py migrate` | 1. w/in the app directory I deleted the `pycache` and `migrations` folders,
2. from `django.migrations` tables I deleted all rows like this for PostgreSQL
```
DELETE FROM public.django_migrations
WHERE public.django_migrations.app = 'target_app_name';
```
3. To delete any app tables already created for the tables to be created from scratch. |
57,698,746 | I am trying to do a migration in django 2.2.4 in python 3.7.
First I try to make do makemigations:
```
python3 manage.py makemigrations
```
I get:
```
Migrations for 'main':
main/migrations/0001_initial.py
- Create model TutorialCategory
- Create model TutorialSeries
- Create model Tutorial
```
But then I try the second step:
```
python3 manage.py migrate
```
I get:
```
Operations to perform:
Apply all migrations: admin, auth, contenttypes, main, sessions
Running migrations:
No migrations to apply.
```
Even though a migration should happen.
I tried deleting my migrations folder and then remaking it (with the empty `__init__.py` file inside) but it still doesn't work.
(Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) | 2019/08/28 | [
"https://Stackoverflow.com/questions/57698746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8802333/"
] | I faced the same problem in django 2.2, The following worked for me...
1. delete the migrations folder resided inside the app folder
2. delete the pycache folder too
3. restart the server [if your server is on and you are working from another cli]
4. `python manage.py makemigrations <app_name> zero`
5. `python manage.py makemigrations <app_name>` [explicit app\_name is important]
6. `python manage.py migrate` | Mine didn't migrate cause there was already a record in the django\_migrations table with the same name, so I just removed it and then migrate worked. |
46,377,827 | Let us assume In PHP
```
$i = 016;
echo $i / 2;
```
The output is returning `7`.! why..? | 2017/09/23 | [
"https://Stackoverflow.com/questions/46377827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6382509/"
] | Appending 0 to the front of a number in PHP is making it octal.
16 in octal is equivalent to 14 in decimal.
So , 14/2 = 7 is the answer. | The leading `0` will cause `016` to be interpreted as written in base `8`, thus in base `10` it will actually be `14`.
So `14/2 = 7` |
2,825,220 | I currently have a JS function that allows me to load partial content from another page into the current page using jQuery.load()
However I noticed when using this that I get a duplicate ID in the DOM (when inspecting with FireBug)
This function is used in conjuction with a Flash Building viewe so it does not contain any code to retrieve the URL from the anchor tag.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
The code above works just fine in retrieving the content, however it just bugs me that when inspecting with firebug I get something like this.
```
<div id="apartmentInfo">
<div id="apartmentInfo">
<!-- Remote HTML here..... -->
</div>
</div>
```
Can anyone please suggest anything on how to remove the duplicate div?
Thanks,
Warren | 2010/05/13 | [
"https://Stackoverflow.com/questions/2825220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69795/"
] | If it's just that ID that is causing you an annoyance, you could either change that id, or remove the duplicate when the document is loaded:
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).attr('id', 'somethingElse'); //change the id
// OR
$(this).children().unwrap(); // remove the second apartmentId from the DOM completely.
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
If it's multiple ID's, the only solution I can think of is to prefix all the ID's within the remote page with something, or load the remote page in an IFRAME.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).find('*[id]').andSelf().attr('id', function (index, previous) {
return 'a-random-prefix-' + previous;
});
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` | a way around it maybe
```
function displayApartment(apartmentID) {
var parent = $("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
parent.children(':first').unwrap();
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` |
2,825,220 | I currently have a JS function that allows me to load partial content from another page into the current page using jQuery.load()
However I noticed when using this that I get a duplicate ID in the DOM (when inspecting with FireBug)
This function is used in conjuction with a Flash Building viewe so it does not contain any code to retrieve the URL from the anchor tag.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
The code above works just fine in retrieving the content, however it just bugs me that when inspecting with firebug I get something like this.
```
<div id="apartmentInfo">
<div id="apartmentInfo">
<!-- Remote HTML here..... -->
</div>
</div>
```
Can anyone please suggest anything on how to remove the duplicate div?
Thanks,
Warren | 2010/05/13 | [
"https://Stackoverflow.com/questions/2825220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69795/"
] | If it's just that ID that is causing you an annoyance, you could either change that id, or remove the duplicate when the document is loaded:
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).attr('id', 'somethingElse'); //change the id
// OR
$(this).children().unwrap(); // remove the second apartmentId from the DOM completely.
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
If it's multiple ID's, the only solution I can think of is to prefix all the ID's within the remote page with something, or load the remote page in an IFRAME.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).find('*[id]').andSelf().attr('id', function (index, previous) {
return 'a-random-prefix-' + previous;
});
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` | Simply Use This:
```
#apartmentInfo > *
```
Full Code:
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo > *", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` |
2,825,220 | I currently have a JS function that allows me to load partial content from another page into the current page using jQuery.load()
However I noticed when using this that I get a duplicate ID in the DOM (when inspecting with FireBug)
This function is used in conjuction with a Flash Building viewe so it does not contain any code to retrieve the URL from the anchor tag.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
The code above works just fine in retrieving the content, however it just bugs me that when inspecting with firebug I get something like this.
```
<div id="apartmentInfo">
<div id="apartmentInfo">
<!-- Remote HTML here..... -->
</div>
</div>
```
Can anyone please suggest anything on how to remove the duplicate div?
Thanks,
Warren | 2010/05/13 | [
"https://Stackoverflow.com/questions/2825220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69795/"
] | If it's just that ID that is causing you an annoyance, you could either change that id, or remove the duplicate when the document is loaded:
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).attr('id', 'somethingElse'); //change the id
// OR
$(this).children().unwrap(); // remove the second apartmentId from the DOM completely.
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
If it's multiple ID's, the only solution I can think of is to prefix all the ID's within the remote page with something, or load the remote page in an IFRAME.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).find('*[id]').andSelf().attr('id', function (index, previous) {
return 'a-random-prefix-' + previous;
});
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` | I came here thanks to *the Google* looking for what I believe OP was really looking for; a way to have **all** of the **contents** of `$(selector).load('my.html #apartmentInfo')` without the surrounding div.
E.g.:
```
<div id='apartmentInfo' data-from="main page">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
```
...rather than the default behavior of `$('#apartmentInfo').load('my.html #apartmentInfo')` which results in:
```
<div id='apartmentInfo' data-from="main page">
<div id='apartmentInfo' data-from="my.html">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
</div>
```
The use of `.unwrap()` above comes close, but results in this:
```
<div id='apartmentInfo' data-from="my.html">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
```
...which is a problem if you have any attributes set on the `data-from="main page"` div that are not also set on the `data-from="my.html"` div as they are lost.
The code below retains the `data-from="main page"` div while stripping the `data-from="my.html"` div post `.load`:
```
var $apartmentInfo = $('#apartmentInfo'),
$tempApartmentInfo = $apartmentInfo.clone()
;
$tempApartmentInfo.contents().remove();
$tempApartmentInfo.load('my.html #apartmentInfo', function (response, status, xhr) {
$tempApartmentInfo.children().each(function () {
$apartmentInfo.append($(this).contents());
});
});
```
This code avoids all issues with duplicate IDs as described by OP (but the *contents* of the remote `#apartmentInfo` may have duplicate IDs) as the `data-from="my.html"` div is never loaded into the DOM thanks to the use of the detached `$tempApartmentInfo`.
Or... here it is again as a jQuery plugin named `loadContents`:
```
//# .load the specified content while stripping the outer-most container
jQuery.fn.loadContents = function (url, data, complete) {
var $target = $(this),
$tempTarget = $target.clone()
;
//# Clear out the $tempTarget so we are left with only the base element
$tempTarget.contents().remove();
//# Pass the call off to .load to do the heavy lifting
$tempTarget.load(url, data, function (response, status, xhr) {
//# Traverse the .children, .appending the .load'ed .contents of each child back into the $target as we go
$tempTarget.children().each(function () {
$target.append($(this).contents());
});
//# If the passed complete is a function, call it now
if (Object.prototype.toString.call(complete) == '[object Function]') { complete(response, status, xhr); }
});
};
```
NOTE: This plugin **always** strips the outer-most element in the loaded content. Also note that unlike jQuery's native `.load` this plugin does not remove and current content within the `$target`, but rather `.append`s the `.load`ed content onto the `$target`. |
2,825,220 | I currently have a JS function that allows me to load partial content from another page into the current page using jQuery.load()
However I noticed when using this that I get a duplicate ID in the DOM (when inspecting with FireBug)
This function is used in conjuction with a Flash Building viewe so it does not contain any code to retrieve the URL from the anchor tag.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
The code above works just fine in retrieving the content, however it just bugs me that when inspecting with firebug I get something like this.
```
<div id="apartmentInfo">
<div id="apartmentInfo">
<!-- Remote HTML here..... -->
</div>
</div>
```
Can anyone please suggest anything on how to remove the duplicate div?
Thanks,
Warren | 2010/05/13 | [
"https://Stackoverflow.com/questions/2825220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69795/"
] | a way around it maybe
```
function displayApartment(apartmentID) {
var parent = $("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
parent.children(':first').unwrap();
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` | Simply Use This:
```
#apartmentInfo > *
```
Full Code:
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo > *", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` |
2,825,220 | I currently have a JS function that allows me to load partial content from another page into the current page using jQuery.load()
However I noticed when using this that I get a duplicate ID in the DOM (when inspecting with FireBug)
This function is used in conjuction with a Flash Building viewe so it does not contain any code to retrieve the URL from the anchor tag.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
The code above works just fine in retrieving the content, however it just bugs me that when inspecting with firebug I get something like this.
```
<div id="apartmentInfo">
<div id="apartmentInfo">
<!-- Remote HTML here..... -->
</div>
</div>
```
Can anyone please suggest anything on how to remove the duplicate div?
Thanks,
Warren | 2010/05/13 | [
"https://Stackoverflow.com/questions/2825220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69795/"
] | a way around it maybe
```
function displayApartment(apartmentID) {
var parent = $("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
parent.children(':first').unwrap();
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` | I came here thanks to *the Google* looking for what I believe OP was really looking for; a way to have **all** of the **contents** of `$(selector).load('my.html #apartmentInfo')` without the surrounding div.
E.g.:
```
<div id='apartmentInfo' data-from="main page">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
```
...rather than the default behavior of `$('#apartmentInfo').load('my.html #apartmentInfo')` which results in:
```
<div id='apartmentInfo' data-from="main page">
<div id='apartmentInfo' data-from="my.html">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
</div>
```
The use of `.unwrap()` above comes close, but results in this:
```
<div id='apartmentInfo' data-from="my.html">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
```
...which is a problem if you have any attributes set on the `data-from="main page"` div that are not also set on the `data-from="my.html"` div as they are lost.
The code below retains the `data-from="main page"` div while stripping the `data-from="my.html"` div post `.load`:
```
var $apartmentInfo = $('#apartmentInfo'),
$tempApartmentInfo = $apartmentInfo.clone()
;
$tempApartmentInfo.contents().remove();
$tempApartmentInfo.load('my.html #apartmentInfo', function (response, status, xhr) {
$tempApartmentInfo.children().each(function () {
$apartmentInfo.append($(this).contents());
});
});
```
This code avoids all issues with duplicate IDs as described by OP (but the *contents* of the remote `#apartmentInfo` may have duplicate IDs) as the `data-from="my.html"` div is never loaded into the DOM thanks to the use of the detached `$tempApartmentInfo`.
Or... here it is again as a jQuery plugin named `loadContents`:
```
//# .load the specified content while stripping the outer-most container
jQuery.fn.loadContents = function (url, data, complete) {
var $target = $(this),
$tempTarget = $target.clone()
;
//# Clear out the $tempTarget so we are left with only the base element
$tempTarget.contents().remove();
//# Pass the call off to .load to do the heavy lifting
$tempTarget.load(url, data, function (response, status, xhr) {
//# Traverse the .children, .appending the .load'ed .contents of each child back into the $target as we go
$tempTarget.children().each(function () {
$target.append($(this).contents());
});
//# If the passed complete is a function, call it now
if (Object.prototype.toString.call(complete) == '[object Function]') { complete(response, status, xhr); }
});
};
```
NOTE: This plugin **always** strips the outer-most element in the loaded content. Also note that unlike jQuery's native `.load` this plugin does not remove and current content within the `$target`, but rather `.append`s the `.load`ed content onto the `$target`. |
114,864 | I am trying to get Emacs (24.3.1), Org-mode (8.0.3, from ELPA) and BibTeX (from TeX Live 2012) to work together.
I have followed the instructions under the **Bibliography** section in <http://orgmode.org/worg/org-tutorials/org-latex-export.html> but after exporting the document to LaTeX, compiling to PDF, and opening the result (with key sequence `C-c C-e l o` in the latest Org mode) I see a question mark instead of a citation (i.e., **[?]**) which means that the reference was not resolved by LaTeX. In fact, checking the `Org PDF LaTeX Output` buffer, I see the following warning:
```
LaTeX Warning: Citation `Tappert77' on page 3 undefined on input line 43.
No file org-bib-test.bbl.
[3] (.//org-bib-test.aux)
LaTeX Warning: There were undefined references.
```
It looked to me that probably Org-mode was looking for a `.bib` file with the same base name as the `.org` file but renaming the `.bib` file and updating the `\bibliography` line did not solve the problem.
Here are two minimal `.org` and `.bib` files that together can be used to reproduce the behavior described above:
**`org-bib-test.org`**
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
The following, using `#+LATEX_HEADER`, gives the same result:
**`org-bib-test.org`**
```
#+LATEX_HEADER: \bibliographystyle{plain}
#+LATEX_HEADER: \bibliography{org-bib-test-refs}
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
```
**`org-bib-test-refs.bib`**
```
@incollection {Tappert77,
AUTHOR = {Tappert, Fred D.},
TITLE = {The parabolic approximation method},
BOOKTITLE = {Wave propagation and underwater acoustics ({W}orkshop,
{M}ystic, {C}onn., 1974)},
PAGES = {224--287. Lecture Notes in Phys., Vol. 70},
PUBLISHER = {Springer},
ADDRESS = {Berlin},
YEAR = {1977},
MRCLASS = {76.41 (86.41)},
}
```
Currently I am using the following **ugly** hack to get the references resolved: I generate the `.bbl` file from the `.bib` file (using a minimal `.tex` file) and then I `\include` the resulting `.bbl` file directly in my `.org` file. This is rather cumbersome and of course requires that I regenerate the `.bbl` file every time I make a change to the `.bib` file. Although this process can be automated in Emacs by writing a lisp function to encapsulate these actions, I'd rather solve the problem than streamline a hack.
**Edit**
I have checked the `.tex` file generated by Org mode. It *does* have the following necessary lines exported in it:
```
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
``` | 2013/05/18 | [
"https://tex.stackexchange.com/questions/114864",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/11886/"
] | @G.JayKerns has a perfectly good solution in the comments, but since this question has been a while without an answer, I'll fill it in. The important elisp variable is `org-latex-pdf-process`, which can work with a number of settings. I have mine set up as something like:
```lisp
(setq org-latex-pdf-process (list
"latexmk -pdflatex='lualatex -shell-escape -interaction nonstopmode' -pdf -f %f"))
```
That's a simplification since I set the actual variable dynamically based on some other orgmode macro lines, but the basic idea should work.
You can use explicit multiple iterations or a build process like `latexmk` or `rubber` within `org-latex-pdf-process`. Use what you would at the command line and check the log in the `*Org PDF LaTeX Output*` buffer if you get errors.
The org-mode file should look like this:
`org-bib-test.org`
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
Put your bibtex in the file `org-bib-test-refs.bib` and run `C-c C-e l o` and you should be good. | This answer from
[Problems with .bbl in org-mode](https://tex.stackexchange.com/questions/32348/problems-with-bbl-in-org-mode)
```lisp
(setq org-latex-to-pdf-process (list "latexmk -pdf %f"))
```
worked for me |
114,864 | I am trying to get Emacs (24.3.1), Org-mode (8.0.3, from ELPA) and BibTeX (from TeX Live 2012) to work together.
I have followed the instructions under the **Bibliography** section in <http://orgmode.org/worg/org-tutorials/org-latex-export.html> but after exporting the document to LaTeX, compiling to PDF, and opening the result (with key sequence `C-c C-e l o` in the latest Org mode) I see a question mark instead of a citation (i.e., **[?]**) which means that the reference was not resolved by LaTeX. In fact, checking the `Org PDF LaTeX Output` buffer, I see the following warning:
```
LaTeX Warning: Citation `Tappert77' on page 3 undefined on input line 43.
No file org-bib-test.bbl.
[3] (.//org-bib-test.aux)
LaTeX Warning: There were undefined references.
```
It looked to me that probably Org-mode was looking for a `.bib` file with the same base name as the `.org` file but renaming the `.bib` file and updating the `\bibliography` line did not solve the problem.
Here are two minimal `.org` and `.bib` files that together can be used to reproduce the behavior described above:
**`org-bib-test.org`**
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
The following, using `#+LATEX_HEADER`, gives the same result:
**`org-bib-test.org`**
```
#+LATEX_HEADER: \bibliographystyle{plain}
#+LATEX_HEADER: \bibliography{org-bib-test-refs}
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
```
**`org-bib-test-refs.bib`**
```
@incollection {Tappert77,
AUTHOR = {Tappert, Fred D.},
TITLE = {The parabolic approximation method},
BOOKTITLE = {Wave propagation and underwater acoustics ({W}orkshop,
{M}ystic, {C}onn., 1974)},
PAGES = {224--287. Lecture Notes in Phys., Vol. 70},
PUBLISHER = {Springer},
ADDRESS = {Berlin},
YEAR = {1977},
MRCLASS = {76.41 (86.41)},
}
```
Currently I am using the following **ugly** hack to get the references resolved: I generate the `.bbl` file from the `.bib` file (using a minimal `.tex` file) and then I `\include` the resulting `.bbl` file directly in my `.org` file. This is rather cumbersome and of course requires that I regenerate the `.bbl` file every time I make a change to the `.bib` file. Although this process can be automated in Emacs by writing a lisp function to encapsulate these actions, I'd rather solve the problem than streamline a hack.
**Edit**
I have checked the `.tex` file generated by Org mode. It *does* have the following necessary lines exported in it:
```
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
``` | 2013/05/18 | [
"https://tex.stackexchange.com/questions/114864",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/11886/"
] | @G.JayKerns has a perfectly good solution in the comments, but since this question has been a while without an answer, I'll fill it in. The important elisp variable is `org-latex-pdf-process`, which can work with a number of settings. I have mine set up as something like:
```lisp
(setq org-latex-pdf-process (list
"latexmk -pdflatex='lualatex -shell-escape -interaction nonstopmode' -pdf -f %f"))
```
That's a simplification since I set the actual variable dynamically based on some other orgmode macro lines, but the basic idea should work.
You can use explicit multiple iterations or a build process like `latexmk` or `rubber` within `org-latex-pdf-process`. Use what you would at the command line and check the log in the `*Org PDF LaTeX Output*` buffer if you get errors.
The org-mode file should look like this:
`org-bib-test.org`
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
Put your bibtex in the file `org-bib-test-refs.bib` and run `C-c C-e l o` and you should be good. | From the documentation for `org-latex-pdf-process` in org-mode version 8.2.5h (February 10, 2014):
>
> By default, Org uses 3 runs of `pdflatex` to do the processing.
> If you have texi2dvi on your system and if that does not cause
> the infamous egrep/locale bug:
>
>
> <http://lists.gnu.org/archive/html/bug-texinfo/2010-03/msg00031.html>
>
>
> then `texi2dvi` is the superior choice as it automates the LaTeX
> build process by calling the "correct" combinations of
> auxiliary programs. Org does offer `texi2dvi` as one of the
> customize options. Alternatively, `rubber` and `latexmk` also
> provide similar functionality. The latter supports `biber' out
> of the box.
>
>
>
The customization buffer offers a value menu that includes `texi2dvi`, so it can easily be set through that interface. If you prefer to set the value in your .emacs, you can use the following:
```
(setq org-latex-pdf-process (quote ("texi2dvi -p -b -V %f")))
``` |
114,864 | I am trying to get Emacs (24.3.1), Org-mode (8.0.3, from ELPA) and BibTeX (from TeX Live 2012) to work together.
I have followed the instructions under the **Bibliography** section in <http://orgmode.org/worg/org-tutorials/org-latex-export.html> but after exporting the document to LaTeX, compiling to PDF, and opening the result (with key sequence `C-c C-e l o` in the latest Org mode) I see a question mark instead of a citation (i.e., **[?]**) which means that the reference was not resolved by LaTeX. In fact, checking the `Org PDF LaTeX Output` buffer, I see the following warning:
```
LaTeX Warning: Citation `Tappert77' on page 3 undefined on input line 43.
No file org-bib-test.bbl.
[3] (.//org-bib-test.aux)
LaTeX Warning: There were undefined references.
```
It looked to me that probably Org-mode was looking for a `.bib` file with the same base name as the `.org` file but renaming the `.bib` file and updating the `\bibliography` line did not solve the problem.
Here are two minimal `.org` and `.bib` files that together can be used to reproduce the behavior described above:
**`org-bib-test.org`**
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
The following, using `#+LATEX_HEADER`, gives the same result:
**`org-bib-test.org`**
```
#+LATEX_HEADER: \bibliographystyle{plain}
#+LATEX_HEADER: \bibliography{org-bib-test-refs}
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
```
**`org-bib-test-refs.bib`**
```
@incollection {Tappert77,
AUTHOR = {Tappert, Fred D.},
TITLE = {The parabolic approximation method},
BOOKTITLE = {Wave propagation and underwater acoustics ({W}orkshop,
{M}ystic, {C}onn., 1974)},
PAGES = {224--287. Lecture Notes in Phys., Vol. 70},
PUBLISHER = {Springer},
ADDRESS = {Berlin},
YEAR = {1977},
MRCLASS = {76.41 (86.41)},
}
```
Currently I am using the following **ugly** hack to get the references resolved: I generate the `.bbl` file from the `.bib` file (using a minimal `.tex` file) and then I `\include` the resulting `.bbl` file directly in my `.org` file. This is rather cumbersome and of course requires that I regenerate the `.bbl` file every time I make a change to the `.bib` file. Although this process can be automated in Emacs by writing a lisp function to encapsulate these actions, I'd rather solve the problem than streamline a hack.
**Edit**
I have checked the `.tex` file generated by Org mode. It *does* have the following necessary lines exported in it:
```
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
``` | 2013/05/18 | [
"https://tex.stackexchange.com/questions/114864",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/11886/"
] | @G.JayKerns has a perfectly good solution in the comments, but since this question has been a while without an answer, I'll fill it in. The important elisp variable is `org-latex-pdf-process`, which can work with a number of settings. I have mine set up as something like:
```lisp
(setq org-latex-pdf-process (list
"latexmk -pdflatex='lualatex -shell-escape -interaction nonstopmode' -pdf -f %f"))
```
That's a simplification since I set the actual variable dynamically based on some other orgmode macro lines, but the basic idea should work.
You can use explicit multiple iterations or a build process like `latexmk` or `rubber` within `org-latex-pdf-process`. Use what you would at the command line and check the log in the `*Org PDF LaTeX Output*` buffer if you get errors.
The org-mode file should look like this:
`org-bib-test.org`
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
Put your bibtex in the file `org-bib-test-refs.bib` and run `C-c C-e l o` and you should be good. | Because bibtex usually uses `\cite{some_reference}` there is a conflict involving reftex in org-mode where the usual bib{some\_reference} is used. To get round this I define a my-org2pdf-export, which works for me using emacs-24 and org 8.3. I then an org file using reftex to call references and then use M-x my-org2pdf-export RET when I want to export to a pdf file.
```
;;; Begin "my-org2pdf-export"
;;;
;;; Define bib2cite
(defun my-bib2cite ()
"change bib to cite"
(interactive)
(let ((case-fold-search t)) ; or nil
(goto-char (point-min))
(while (search-forward "bib:" nil t)
(replace-match "cite:" t t))))
;;;
;;; Define cite2bib
(defun my-cite2bib ()
"change cite to bib"
(interactive)
(let ((case-fold-search t)) ; or nil
(goto-char (point-min))
(while (search-forward "cite:" nil t)
(replace-match "bib:" t t))))
;;;
;;; Change bib: to cite: in .org file
;;; Then call org-export-dispatch and
;;; then change cite: back to bib:
;;; to leave original .org file unchanged.
(defun my-export-org ()
"export settings"
(interactive)
(my-bib2cite) ;; Change bib: to cite:
(org-export-dispatch) ;; Call the dispatcher
(my-cite2bib) ;; Change cite: back to bib:
(save-buffer);; Save file again
) ;; End bracket
;;; End "my-org2pdf-export".
``` |
114,864 | I am trying to get Emacs (24.3.1), Org-mode (8.0.3, from ELPA) and BibTeX (from TeX Live 2012) to work together.
I have followed the instructions under the **Bibliography** section in <http://orgmode.org/worg/org-tutorials/org-latex-export.html> but after exporting the document to LaTeX, compiling to PDF, and opening the result (with key sequence `C-c C-e l o` in the latest Org mode) I see a question mark instead of a citation (i.e., **[?]**) which means that the reference was not resolved by LaTeX. In fact, checking the `Org PDF LaTeX Output` buffer, I see the following warning:
```
LaTeX Warning: Citation `Tappert77' on page 3 undefined on input line 43.
No file org-bib-test.bbl.
[3] (.//org-bib-test.aux)
LaTeX Warning: There were undefined references.
```
It looked to me that probably Org-mode was looking for a `.bib` file with the same base name as the `.org` file but renaming the `.bib` file and updating the `\bibliography` line did not solve the problem.
Here are two minimal `.org` and `.bib` files that together can be used to reproduce the behavior described above:
**`org-bib-test.org`**
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
The following, using `#+LATEX_HEADER`, gives the same result:
**`org-bib-test.org`**
```
#+LATEX_HEADER: \bibliographystyle{plain}
#+LATEX_HEADER: \bibliography{org-bib-test-refs}
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
```
**`org-bib-test-refs.bib`**
```
@incollection {Tappert77,
AUTHOR = {Tappert, Fred D.},
TITLE = {The parabolic approximation method},
BOOKTITLE = {Wave propagation and underwater acoustics ({W}orkshop,
{M}ystic, {C}onn., 1974)},
PAGES = {224--287. Lecture Notes in Phys., Vol. 70},
PUBLISHER = {Springer},
ADDRESS = {Berlin},
YEAR = {1977},
MRCLASS = {76.41 (86.41)},
}
```
Currently I am using the following **ugly** hack to get the references resolved: I generate the `.bbl` file from the `.bib` file (using a minimal `.tex` file) and then I `\include` the resulting `.bbl` file directly in my `.org` file. This is rather cumbersome and of course requires that I regenerate the `.bbl` file every time I make a change to the `.bib` file. Although this process can be automated in Emacs by writing a lisp function to encapsulate these actions, I'd rather solve the problem than streamline a hack.
**Edit**
I have checked the `.tex` file generated by Org mode. It *does* have the following necessary lines exported in it:
```
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
``` | 2013/05/18 | [
"https://tex.stackexchange.com/questions/114864",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/11886/"
] | This answer from
[Problems with .bbl in org-mode](https://tex.stackexchange.com/questions/32348/problems-with-bbl-in-org-mode)
```lisp
(setq org-latex-to-pdf-process (list "latexmk -pdf %f"))
```
worked for me | Because bibtex usually uses `\cite{some_reference}` there is a conflict involving reftex in org-mode where the usual bib{some\_reference} is used. To get round this I define a my-org2pdf-export, which works for me using emacs-24 and org 8.3. I then an org file using reftex to call references and then use M-x my-org2pdf-export RET when I want to export to a pdf file.
```
;;; Begin "my-org2pdf-export"
;;;
;;; Define bib2cite
(defun my-bib2cite ()
"change bib to cite"
(interactive)
(let ((case-fold-search t)) ; or nil
(goto-char (point-min))
(while (search-forward "bib:" nil t)
(replace-match "cite:" t t))))
;;;
;;; Define cite2bib
(defun my-cite2bib ()
"change cite to bib"
(interactive)
(let ((case-fold-search t)) ; or nil
(goto-char (point-min))
(while (search-forward "cite:" nil t)
(replace-match "bib:" t t))))
;;;
;;; Change bib: to cite: in .org file
;;; Then call org-export-dispatch and
;;; then change cite: back to bib:
;;; to leave original .org file unchanged.
(defun my-export-org ()
"export settings"
(interactive)
(my-bib2cite) ;; Change bib: to cite:
(org-export-dispatch) ;; Call the dispatcher
(my-cite2bib) ;; Change cite: back to bib:
(save-buffer);; Save file again
) ;; End bracket
;;; End "my-org2pdf-export".
``` |
114,864 | I am trying to get Emacs (24.3.1), Org-mode (8.0.3, from ELPA) and BibTeX (from TeX Live 2012) to work together.
I have followed the instructions under the **Bibliography** section in <http://orgmode.org/worg/org-tutorials/org-latex-export.html> but after exporting the document to LaTeX, compiling to PDF, and opening the result (with key sequence `C-c C-e l o` in the latest Org mode) I see a question mark instead of a citation (i.e., **[?]**) which means that the reference was not resolved by LaTeX. In fact, checking the `Org PDF LaTeX Output` buffer, I see the following warning:
```
LaTeX Warning: Citation `Tappert77' on page 3 undefined on input line 43.
No file org-bib-test.bbl.
[3] (.//org-bib-test.aux)
LaTeX Warning: There were undefined references.
```
It looked to me that probably Org-mode was looking for a `.bib` file with the same base name as the `.org` file but renaming the `.bib` file and updating the `\bibliography` line did not solve the problem.
Here are two minimal `.org` and `.bib` files that together can be used to reproduce the behavior described above:
**`org-bib-test.org`**
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
The following, using `#+LATEX_HEADER`, gives the same result:
**`org-bib-test.org`**
```
#+LATEX_HEADER: \bibliographystyle{plain}
#+LATEX_HEADER: \bibliography{org-bib-test-refs}
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
```
**`org-bib-test-refs.bib`**
```
@incollection {Tappert77,
AUTHOR = {Tappert, Fred D.},
TITLE = {The parabolic approximation method},
BOOKTITLE = {Wave propagation and underwater acoustics ({W}orkshop,
{M}ystic, {C}onn., 1974)},
PAGES = {224--287. Lecture Notes in Phys., Vol. 70},
PUBLISHER = {Springer},
ADDRESS = {Berlin},
YEAR = {1977},
MRCLASS = {76.41 (86.41)},
}
```
Currently I am using the following **ugly** hack to get the references resolved: I generate the `.bbl` file from the `.bib` file (using a minimal `.tex` file) and then I `\include` the resulting `.bbl` file directly in my `.org` file. This is rather cumbersome and of course requires that I regenerate the `.bbl` file every time I make a change to the `.bib` file. Although this process can be automated in Emacs by writing a lisp function to encapsulate these actions, I'd rather solve the problem than streamline a hack.
**Edit**
I have checked the `.tex` file generated by Org mode. It *does* have the following necessary lines exported in it:
```
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
``` | 2013/05/18 | [
"https://tex.stackexchange.com/questions/114864",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/11886/"
] | From the documentation for `org-latex-pdf-process` in org-mode version 8.2.5h (February 10, 2014):
>
> By default, Org uses 3 runs of `pdflatex` to do the processing.
> If you have texi2dvi on your system and if that does not cause
> the infamous egrep/locale bug:
>
>
> <http://lists.gnu.org/archive/html/bug-texinfo/2010-03/msg00031.html>
>
>
> then `texi2dvi` is the superior choice as it automates the LaTeX
> build process by calling the "correct" combinations of
> auxiliary programs. Org does offer `texi2dvi` as one of the
> customize options. Alternatively, `rubber` and `latexmk` also
> provide similar functionality. The latter supports `biber' out
> of the box.
>
>
>
The customization buffer offers a value menu that includes `texi2dvi`, so it can easily be set through that interface. If you prefer to set the value in your .emacs, you can use the following:
```
(setq org-latex-pdf-process (quote ("texi2dvi -p -b -V %f")))
``` | Because bibtex usually uses `\cite{some_reference}` there is a conflict involving reftex in org-mode where the usual bib{some\_reference} is used. To get round this I define a my-org2pdf-export, which works for me using emacs-24 and org 8.3. I then an org file using reftex to call references and then use M-x my-org2pdf-export RET when I want to export to a pdf file.
```
;;; Begin "my-org2pdf-export"
;;;
;;; Define bib2cite
(defun my-bib2cite ()
"change bib to cite"
(interactive)
(let ((case-fold-search t)) ; or nil
(goto-char (point-min))
(while (search-forward "bib:" nil t)
(replace-match "cite:" t t))))
;;;
;;; Define cite2bib
(defun my-cite2bib ()
"change cite to bib"
(interactive)
(let ((case-fold-search t)) ; or nil
(goto-char (point-min))
(while (search-forward "cite:" nil t)
(replace-match "bib:" t t))))
;;;
;;; Change bib: to cite: in .org file
;;; Then call org-export-dispatch and
;;; then change cite: back to bib:
;;; to leave original .org file unchanged.
(defun my-export-org ()
"export settings"
(interactive)
(my-bib2cite) ;; Change bib: to cite:
(org-export-dispatch) ;; Call the dispatcher
(my-cite2bib) ;; Change cite: back to bib:
(save-buffer);; Save file again
) ;; End bracket
;;; End "my-org2pdf-export".
``` |
4,082 | I think that [this question](https://math.stackexchange.com/questions/3704/integral-representation-of-infinite-series) deserves to be reopened. Hopefully now that we have more meta members, enough others will agree. Please vote to reopen if you agree.
**Edit** $\ $ The question is now reopened. Thanks to everyone who helped. Apologies for not being clearer from the start as to why I thought it deserved reopening.
Perhaps now the question will come to the attention of others who can say more about some of the powerful techniques here that deserve to be more widely known. | 2012/05/01 | [
"https://math.meta.stackexchange.com/questions/4082",
"https://math.meta.stackexchange.com",
"https://math.meta.stackexchange.com/users/242/"
] | I cast the final reopen vote. While at face value I think it made a close-worthy question according to the word of the FAQ and rules and such, I personally have a higher bar for my close votes:
* If the question has proven amenable to a valuable and original contribution from some member of the community as an answer, it deserves to remain open.
* If the question is feasibly salvageable by the original poster, he or she should be given ample time and opportunity to attempt to do so as best they can with help from the community.
But why reopen *now*? Well, why not - what does timing have to do with anything? The past doesn't become less interesting mathematically or useful for our community by virtue of being in the past.
Ultimately I think closures serve as models to our question-askers and our close-voters about what kinds of questions are discouraged. It is a difficult situation to be in to have a question nagging at you incessantly, but at the same time not understand the mathematical context well enough to be able to ask a question properly about it, or even know if your thoughts correspond at all to a "real" question. (Been there, done that.) I want users to feel free to at least *try* and find out if something fruitful can be said about what they're exploring, as best as our community can manage, as well as balance with closing the incorrigible ones, and to that end I devised the above two bullet points. | I'm posting here my idea of editing this question so that it's not bumped unnecessarily. In addition to what's below, I would add the `big-list` tag. I would ask those who think that this version is still beyond repair to downvote this answer. I would ask those who think that this version is fine to upvote. Those who think this is not OK but can still be corrected I would ask to leave comments and refrain from voting if possible. Of course the invitation to leave comments is not restricted to the last group.
---
Let's take a look at the following integrals :
1) $\displaystyle \int\limits\_{0}^{1} \frac{\log{x}}{1+x} \ dx = -\frac{\pi^{2}}{12} = -2 \sum\limits\_{n=1}^{\infty} \frac{1}{n^2}= \zeta(2)$
2) For $c<1$ $\displaystyle \int\limits\_{0}^{\frac{\pi}{2}} \arcsin(c \cos{x}) \ dx = \frac{c}{1^2} + \frac{c}{3^2} + \frac{c}{5^2} + \cdots $
3) [Summing the series $(-1)^k \frac{(2k)!!}{(2k+1)!!} a^{2k+1}$](https://math.stackexchange.com/questions/3502/summing-the-series-1k-frac2k2k1-a2k1)
Infinite series can often be summed (and perhaps otherwise usefully manipulated) by noticing that they are equal to certain integrals. I would like to know if there are any general methods or doing so which prove useful in a mathematician's work. If so what are they?
**Notes:**
$(1)$ Examples of such methods from books and from personal experience will be equally welcomed.
$(2)$ Examples of such methods with various scopes of applicability will be welcomed.
$(3)$ Examples of less tangible, heuristic methods which work will be welcomed. |
339,291 | After opening the emoji keyboard with `Ctrl + Cmd + Space`, selecting an emoji and finally hitting enter, the emoji keyboard closes but nothing is inserted at my cursor.
[![enter image description here](https://i.stack.imgur.com/S8hL5.png)](https://i.stack.imgur.com/S8hL5.png)
A restart seems to fix this, but after some time the keyboard breaks again and I need to restart again.
Does anyone have an idea why this is happening?
This is on macOS High Sierra v10.13.6 (17G2307)
Thank you. | 2018/10/11 | [
"https://apple.stackexchange.com/questions/339291",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/43263/"
] | Lets assume you are not confusing Google and Chrome.
Google application passwords are stored in your KeyChain, for things like Gmail, Calendar, Google drive ect..
Chrome passwords are stored on your HD at
`~/Library/Application Support/Google/Chrome/Default/databases` in special format. (SQL)
However Chrome is a browser and its passwords for diverse websites is not stored in the KeyChain. | All of your Chrome passwords are encrypted by Chrome and stored in an SQLite database file under Chrome's Local App Data. It is not stored via Keychain.
If you would like to know more about the technical details, refer [this](https://superuser.com/questions/146742/how-does-google-chrome-store-passwords) answer. |
339,291 | After opening the emoji keyboard with `Ctrl + Cmd + Space`, selecting an emoji and finally hitting enter, the emoji keyboard closes but nothing is inserted at my cursor.
[![enter image description here](https://i.stack.imgur.com/S8hL5.png)](https://i.stack.imgur.com/S8hL5.png)
A restart seems to fix this, but after some time the keyboard breaks again and I need to restart again.
Does anyone have an idea why this is happening?
This is on macOS High Sierra v10.13.6 (17G2307)
Thank you. | 2018/10/11 | [
"https://apple.stackexchange.com/questions/339291",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/43263/"
] | Lets assume you are not confusing Google and Chrome.
Google application passwords are stored in your KeyChain, for things like Gmail, Calendar, Google drive ect..
Chrome passwords are stored on your HD at
`~/Library/Application Support/Google/Chrome/Default/databases` in special format. (SQL)
However Chrome is a browser and its passwords for diverse websites is not stored in the KeyChain. | I don't think this is the case any longer. I'm using Chrome Version 76.0.3809.132. When I start Chrome and get the question to 'Allow Always', 'Deny', or 'Allow' access to the keychain, I Deny its use of the keychain. In Chrome, I have 'Offer to save passwords' and 'Auto Sign-in' on and it never asks me to save passwords and I cannot do it manually (using the key icon to the right of the address bar) as the key icon never shows. I exited Chrome and re-started, this time Allowing Chrome to use the keychain and now it asks me to save passwords and the key icon displays. Also, I do not have a /Library/Application Support/Google/Chrome/Default/databases file nor a /Library/Application Support/Google/Chrome/Default directory. |
33,099,133 | When I am run my application in android studio error. I am new in android developing.
My Logtag is here:
```
Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:assembleDebug]
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
> Could not find com.android.support:recyclerview-v7:.
Searched in the following locations:
https://jcenter.bintray.com/com/android/support/recyclerview-v7//recyclerview-v7-.pom
https://jcenter.bintray.com/com/android/support/recyclerview-v7//recyclerview-v7-.jar
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.pom
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.jar
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.pom
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.jar
Required by:
ShoppingMazza:app:unspecified
Information:BUILD FAILED
Information:Total time: 4.964 secs
Information:1 error
Information:0 warnings
Information:See complete output in console
```
My `build.gradle`:
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.catalyst.android.shoppingmazza"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.android.support:recyclerview-v7:'
}
``` | 2015/10/13 | [
"https://Stackoverflow.com/questions/33099133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5064636/"
] | **Error:**
>
> Error:A problem occurred configuring project ':app'. Could not
> resolve all dependencies for configuration ':app:\_debugCompile'.
>
> Could not find com.android.support:recyclerview-v7:.
>
>
>
From error i can say you'll have to add the following gradle dependency :
```
compile 'com.android.support:recyclerview-v7:+'
```
**EDIT:**
>
> Error:Execution failed for task ':app:dexDebug'. >
> com.android.ide.common.process.ProcessException:
> org.gradle.process.internal.ExecException: Process 'command
> 'C:\Program Files\Java\jdk1.8.0\_51\bin\java.exe'' finished with
> non-zero exit value 1
>
>
>
For this error i think you are compiling `JAR` library twice. You are using
```
compile fileTree(dir: 'libs', include: ['*.jar'])
```
in `build.gradle` file so it will compile all library that has jar extension on libs folder, so You can remove this lines:
```
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
```
If issue still exists then issue is quite possibly due to exceeding the 65K methods dex limit imposed by Android. This problem can be solved either by cleaning the project, and removing some unused libraries and methods from dependencies in `build.gradle`, OR by adding `multidex` support.
```
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
``` | Did you forget the version? In your gradle config you should have something like this:
```
compile 'com.android.support:recyclerview-v7:23.0.1'
``` |
33,099,133 | When I am run my application in android studio error. I am new in android developing.
My Logtag is here:
```
Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:assembleDebug]
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
> Could not find com.android.support:recyclerview-v7:.
Searched in the following locations:
https://jcenter.bintray.com/com/android/support/recyclerview-v7//recyclerview-v7-.pom
https://jcenter.bintray.com/com/android/support/recyclerview-v7//recyclerview-v7-.jar
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.pom
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.jar
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.pom
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.jar
Required by:
ShoppingMazza:app:unspecified
Information:BUILD FAILED
Information:Total time: 4.964 secs
Information:1 error
Information:0 warnings
Information:See complete output in console
```
My `build.gradle`:
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.catalyst.android.shoppingmazza"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.android.support:recyclerview-v7:'
}
``` | 2015/10/13 | [
"https://Stackoverflow.com/questions/33099133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5064636/"
] | **Error:**
>
> Error:A problem occurred configuring project ':app'. Could not
> resolve all dependencies for configuration ':app:\_debugCompile'.
>
> Could not find com.android.support:recyclerview-v7:.
>
>
>
From error i can say you'll have to add the following gradle dependency :
```
compile 'com.android.support:recyclerview-v7:+'
```
**EDIT:**
>
> Error:Execution failed for task ':app:dexDebug'. >
> com.android.ide.common.process.ProcessException:
> org.gradle.process.internal.ExecException: Process 'command
> 'C:\Program Files\Java\jdk1.8.0\_51\bin\java.exe'' finished with
> non-zero exit value 1
>
>
>
For this error i think you are compiling `JAR` library twice. You are using
```
compile fileTree(dir: 'libs', include: ['*.jar'])
```
in `build.gradle` file so it will compile all library that has jar extension on libs folder, so You can remove this lines:
```
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
```
If issue still exists then issue is quite possibly due to exceeding the 65K methods dex limit imposed by Android. This problem can be solved either by cleaning the project, and removing some unused libraries and methods from dependencies in `build.gradle`, OR by adding `multidex` support.
```
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
``` | In my case, I deleted `caches` folder inside `.gradle` folder and then I added `compile`. It worked for me! |
68,682,825 | I am using last version of ActiveMQ Artemis.
My use case is pretty simple. The broker sends a lot of messages to consumer - a single queue. I have 2 consumers per queue. Consumers are set to use default prefetch size of messages (1000).
Is there a way to monitor how many messages are pre-fetch and processed from each consumer? | 2021/08/06 | [
"https://Stackoverflow.com/questions/68682825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4173038/"
] | There are several ways you can go about "shuffling" an array. I chose the Fisher-Yates method in an experimental "war" card game.
<https://github.com/scottm85/war/blob/master/src/Game/Deck.js#L80>
```
shuffle()
{
/* Use a Fisher-Yates shuffle...If provides a much more reliable shuffle than using variations of a sort method https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */
let cards = this.cards;
for (let i = cards.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cards[i], cards[j]] = [cards[j], cards[i]];
}
this.cards = cards;
console.log("----------------- Deck Shuffled -----------------");
}
```
<https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle>
Granted my provided example is slightly different than your needs as I was doing this in react, had a Deck array built out, and wasn't using JS for direct DOM manipulation. In theory though, you could modify this to work with your method. Something like this:
```
function shuffleCards
{
let cards = document.querySelectorAll('.card');
let cardsArray = Array.from(cards);
for (let i = cardsArray.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cardsArray[i], cardsArray[j]] = [cardsArray[j], cardsArray[i]];
cards[i].remove();
}
cardsArray.forEach(t => document.body.appendChild(t));
}
``` | You can use `sort` and `Math.random()` methods like this:
```js
function shuffleCards() {
var parent = document.getElementById("parent");
let cards = document.querySelectorAll('.card');
let cardsArray = Array.from(cards);
//console.log(cardsArray)
cardsArray.sort(() => Math.random() - 0.5);
//console.log(cardsArray)
cardsArray.forEach(t => parent.appendChild(t));
// reorder the nodes of the nodelist (cards)
}
```
```html
<h3> Click on card to Shuffle at the same postion</h3>
<div id="parent">
<div class="card" data-card="1" onclick="shuffleCards(this)">
card 1
<img src="img/cards/1.png" alt="">
<img class="back" src="img/cards/back.png" alt="">
</div>
<div class="card" data-card="7" onclick="shuffleCards(this)">
card 2
<img src="img/cards/7.png" alt="">
<img class="back" src="img/cards/back.png" alt="">
</div>
<div class="card" data-card="1" onclick="shuffleCards(this)">
card 3
<img src="img/cards/1.png" alt="">
<img class="back" src="img/cards/back.png" alt="">
</div>
</div>
``` |
68,682,825 | I am using last version of ActiveMQ Artemis.
My use case is pretty simple. The broker sends a lot of messages to consumer - a single queue. I have 2 consumers per queue. Consumers are set to use default prefetch size of messages (1000).
Is there a way to monitor how many messages are pre-fetch and processed from each consumer? | 2021/08/06 | [
"https://Stackoverflow.com/questions/68682825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4173038/"
] | There are several ways you can go about "shuffling" an array. I chose the Fisher-Yates method in an experimental "war" card game.
<https://github.com/scottm85/war/blob/master/src/Game/Deck.js#L80>
```
shuffle()
{
/* Use a Fisher-Yates shuffle...If provides a much more reliable shuffle than using variations of a sort method https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */
let cards = this.cards;
for (let i = cards.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cards[i], cards[j]] = [cards[j], cards[i]];
}
this.cards = cards;
console.log("----------------- Deck Shuffled -----------------");
}
```
<https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle>
Granted my provided example is slightly different than your needs as I was doing this in react, had a Deck array built out, and wasn't using JS for direct DOM manipulation. In theory though, you could modify this to work with your method. Something like this:
```
function shuffleCards
{
let cards = document.querySelectorAll('.card');
let cardsArray = Array.from(cards);
for (let i = cardsArray.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cardsArray[i], cardsArray[j]] = [cardsArray[j], cardsArray[i]];
cards[i].remove();
}
cardsArray.forEach(t => document.body.appendChild(t));
}
``` | Others have provided algorithms for the randomization portion, but here is how you can handle the detaching and reattaching portion. [`removeChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild) will get you the node detached from the DOM and [`appendChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) will allow you to add it. Just be careful with attaching and detaching. Events can get a bit messy especially if you end up cloning the node somewhere down the line rather than just attaching it again.
```js
(function shuffleCards() {
let container = document.querySelector('#container');
let cards = container.querySelectorAll('.card');
[...cards].map(
node => container.removeChild(node)
).sort(
() => Math.random() - 0.5 // shamelessly stolen from Alireza Ahmadi
).forEach(
node => container.appendChild(node)
);
})()
```
```html
<div id="container">
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 1
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
Card 2
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 3
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 4
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 5
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 6
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 7
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 8
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 9
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
Card 10
</div>
</div>
``` |
68,682,825 | I am using last version of ActiveMQ Artemis.
My use case is pretty simple. The broker sends a lot of messages to consumer - a single queue. I have 2 consumers per queue. Consumers are set to use default prefetch size of messages (1000).
Is there a way to monitor how many messages are pre-fetch and processed from each consumer? | 2021/08/06 | [
"https://Stackoverflow.com/questions/68682825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4173038/"
] | There are several ways you can go about "shuffling" an array. I chose the Fisher-Yates method in an experimental "war" card game.
<https://github.com/scottm85/war/blob/master/src/Game/Deck.js#L80>
```
shuffle()
{
/* Use a Fisher-Yates shuffle...If provides a much more reliable shuffle than using variations of a sort method https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */
let cards = this.cards;
for (let i = cards.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cards[i], cards[j]] = [cards[j], cards[i]];
}
this.cards = cards;
console.log("----------------- Deck Shuffled -----------------");
}
```
<https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle>
Granted my provided example is slightly different than your needs as I was doing this in react, had a Deck array built out, and wasn't using JS for direct DOM manipulation. In theory though, you could modify this to work with your method. Something like this:
```
function shuffleCards
{
let cards = document.querySelectorAll('.card');
let cardsArray = Array.from(cards);
for (let i = cardsArray.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cardsArray[i], cardsArray[j]] = [cardsArray[j], cardsArray[i]];
cards[i].remove();
}
cardsArray.forEach(t => document.body.appendChild(t));
}
``` | The following approach is agnostic to where the queried nodes need to be removed from, and after shuffling, have to be inserted into again.
Thus one does not need to know anything about the DOM structure except for the element query.
Basically ...
1. Use only reliable/proven shuffle functions like [`_.shuffle`](https://underscorejs.org/#shuffle).
2. Create an array from the queried node list.
3. Map it with node items in a way that each (child) node gets removed from the DOM but preserves not only its own reference but also the reference of its parent node.
4. Shuffle the mapped array.
5. Iterate the shuffled items in a way where from each item one can restore the former parent-node child-node relationship ...
```js
function shuffleArray(arr) {
let idx;
let count = arr.length;
while (--count) {
idx = Math.floor(Math.random() * (count + 1));
[arr[idx], arr[count]] = [arr[count], arr[idx]];
}
return arr;
}
function shuffleCards() {
const removedNodeDataList = Array
.from(document.querySelectorAll('.card'))
.map(elmNode => ({
parentNode: elmNode.parentNode,
elementNode: elmNode.parentNode.removeChild(elmNode),
}));
shuffleArray(removedNodeDataList)
.forEach(({ parentNode, elementNode }) =>
parentNode.appendChild(elementNode)
);
}
function init() {
document
.querySelector('button')
.addEventListener('click', shuffleCards);
}
init();
```
```css
img { background-color: #eee; }
button { display: block; margin: 0 0 10px 0; }
```
```html
<button>Shuffle Cards</button>
<div class="card" data-card="1">
<img src="https://picsum.photos/140/50?grayscale" alt="">
<img class="back" src="https://picsum.photos/120/50?grayscale" alt="">
</div>
<div class="card" data-card="2">
<img src="https://picsum.photos/100/50?grayscale" alt="">
<img class="back" src="https://picsum.photos/160/50?grayscale" alt="">
</div>
<div class="card" data-card="3">
<img src="https://picsum.photos/180/50?grayscale" alt="">
<img class="back" src="https://picsum.photos/80/50?grayscale" alt="">
</div>
``` |
25,906,182 | I am using Eclipse Indigo (version 3.7) for my Plug in development. I have created a plug-in and added Jersey archive jars in my Build Path . When i try to debug or run the application I am getting......
```
org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.NoClassDefFoundError: com/sun/jersey/api/client/Client)
at org.eclipse.swt.SWT.error(SWT.java:4282)
at org.eclipse.swt.SWT.error(SWT.java:4197)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.block(ModalContext.java:173)
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:388)
at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:1029)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage.connect(JiraConnectionPage.java:256)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage.access$0(JiraConnectionPage.java:249)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage$1.widgetSelected(JiraConnectionPage.java:142)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:240)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4165)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3754)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at com.cts.adpart.ui.configuration.pages.management.ManagementConfigurationBlock.showAddConfigurationWizard(ManagementConfigurationBlock.java:171)
at com.cts.adpart.ui.configuration.pages.management.ManagementConfigurationBlock.access$1(ManagementConfigurationBlock.java:153)
at com.cts.adpart.ui.configuration.pages.management.ManagementConfigurationBlock$2.linkActivated(ManagementConfigurationBlock.java:133)
at org.eclipse.ui.forms.widgets.AbstractHyperlink.handleActivate(AbstractHyperlink.java:233)
at org.eclipse.ui.forms.widgets.AbstractHyperlink.handleMouseUp(AbstractHyperlink.java:327)
at org.eclipse.ui.forms.widgets.AbstractHyperlink.access$2(AbstractHyperlink.java:311)
at org.eclipse.ui.forms.widgets.AbstractHyperlink$4.handleEvent(AbstractHyperlink.java:125)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4165)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3754)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at com.cts.adpart.standalone.Application.start(Application.java:94)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)
Caused by: java.lang.NoClassDefFoundError: com/sun/jersey/api/client/Client
at com.cts.adpart.testmanagement.jira.api.JiraConnection.connect(JiraConnection.java:34)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage$3$1.run(JiraConnectionPage.java:268)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
... 47 more
Caused by: java.lang.ClassNotFoundException: com.sun.jersey.api.client.Client
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:513)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:429)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:417)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 51 more
```
Exception . I have no idea on how to resolve this issue. Any suggestion ? | 2014/09/18 | [
"https://Stackoverflow.com/questions/25906182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926459/"
] | **EDIT**
I've just noticed (after adding my answer) an error in your constructor - it's name is `_construct` with single underscore. It should be with double underscore `__construct` so correct the name and make sure if error is still present and if it is, read the rest of the answer.
**Rest of the answer**
The first thing you need to run `View::share` before `View::make` otherwise you will get this error.
So if you use somewhere:
```
$wait = 'available';
View::share('wait', $wait);
return View::make('myview');
```
In your template you can simply use:
```
{{ $wait }}
```
and you will get output `available` for your variable and not any notice.
But you mentioned you put `View::share` in a constructor. Is it in your controller class or in parent class? If in parent, you should then execute it using `parent::__construct();` - you need to make sure that this constructor is launched at all, so you can even add `echo 'I'm running'; exit;` in this constructor to make sure it has been launched at all. | You can call it just by using the variable $wait ;-) |
77,767 | In a cavity, the standing wave will constructively interfere with itself, so its energy gets higher while the oscillator is still vibrating. Since the vibration time is not a constant value, and sometimes the wall of the cavity absorbs some of the wave energy, the energy of a standing EM wave is probabilistic and follows Maxwell-Boltzmann distribution. Am I correct in the statement above?
---
Actually I'm thinking about the black-body radiation. To calculate the energy density in a cavity which is heated up to $T$, we assume that the cavity is a cube, and only standing wave can exist in it(Why?). First we need to calculate how many kinds of standing waves(how many different wave vectors) for one frequency $f$. This can be done with some mathematical tricks. And then we have to determine the energy of each wave $\overline{E(f)}$. And my question is, actually, why does this overline come from? Why is it an average energy, instead of a constant value? | 2013/09/18 | [
"https://physics.stackexchange.com/questions/77767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/24610/"
] | Conservation of energy follows directly from Maxwell's equations, so if you convince yourself that energy isn't conserved when EM waves interfere, you've made a mistake, and you need to go back and figure out what your mistake was.
>
> In a cavity, the standing wave will constructively interfere with itself, [...]
>
>
>
Not true. If you work out the right-hand relationships for two EM plane waves traveling in opposite directions, you'll find that if the E fields are in phase, the B fields have opposite phases, and vice versa. | The constructive interference in a cavity doesn’t really make the energy higher. It is a way of seeing how a wave propagates in a confined space, the answer is there is a wave say going from left to right. At the same time there is another wave with the same frequency going from right to left. Those two waves constructively interfere with each other. Their total energy is set by excitation, so there is no increase of energy. The energy of a Resonance/oscillation never increases above its intial value set by excitation, unless excitation was done again which means extra energy was added to the system.
Resonance/oscillation occurs in cavity for particular frequencies that give rise to what is called resonance modes (for example TE111 is the lowest resonance mode in rectangular cavity). So the vibration time (the period of oscillation if that is what you meant) is constant.
If the walls are perfectly conducting, the resonance lasts for ever. If they are not perfect conductors, the energy of the oscillation (also called resonance mode) decreases until the resonance dies away.
I hope that was useful. |
77,767 | In a cavity, the standing wave will constructively interfere with itself, so its energy gets higher while the oscillator is still vibrating. Since the vibration time is not a constant value, and sometimes the wall of the cavity absorbs some of the wave energy, the energy of a standing EM wave is probabilistic and follows Maxwell-Boltzmann distribution. Am I correct in the statement above?
---
Actually I'm thinking about the black-body radiation. To calculate the energy density in a cavity which is heated up to $T$, we assume that the cavity is a cube, and only standing wave can exist in it(Why?). First we need to calculate how many kinds of standing waves(how many different wave vectors) for one frequency $f$. This can be done with some mathematical tricks. And then we have to determine the energy of each wave $\overline{E(f)}$. And my question is, actually, why does this overline come from? Why is it an average energy, instead of a constant value? | 2013/09/18 | [
"https://physics.stackexchange.com/questions/77767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/24610/"
] | In a standing wave of this type, energy swaps back and forth between E field (electric) and B field (magnetic) energy. The total energy remains constant, as noted by earlier commenters. This is very much like the case of an LC oscillator, oscillating at resonance. Of course we have to assume in all cases that the losses are negligible over the time course of our observation.
Maxwell Boltzmann does not come into this at all. Your train of thought mis-lead you in this case, if that's where it took you. | The constructive interference in a cavity doesn’t really make the energy higher. It is a way of seeing how a wave propagates in a confined space, the answer is there is a wave say going from left to right. At the same time there is another wave with the same frequency going from right to left. Those two waves constructively interfere with each other. Their total energy is set by excitation, so there is no increase of energy. The energy of a Resonance/oscillation never increases above its intial value set by excitation, unless excitation was done again which means extra energy was added to the system.
Resonance/oscillation occurs in cavity for particular frequencies that give rise to what is called resonance modes (for example TE111 is the lowest resonance mode in rectangular cavity). So the vibration time (the period of oscillation if that is what you meant) is constant.
If the walls are perfectly conducting, the resonance lasts for ever. If they are not perfect conductors, the energy of the oscillation (also called resonance mode) decreases until the resonance dies away.
I hope that was useful. |
7,660 | I've started Wing Chun few days before. Everything seems to be nice, but I've seen some videos on internet, they say that Wing Chun can't handle Boxers or Wrestlers.
What are the comparisons between Wing Chun and boxing/wrestling that would lead someone to make this claim? Are there weaknesses that can be exploited? | 2017/07/16 | [
"https://martialarts.stackexchange.com/questions/7660",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/-1/"
] | As always, you can't compare style A with style B and say either one is better. It's not because you're a boxer, you immediately win agains a wing chun practitioner. It all depends on how good both fighters are, how much experience they got fighting opponents of different styles, the competition's rules (eg. if you pit a judoka vs. a taekwondo, and rules state no throws or groundwork, chances are the taekwondo will win. If the rules state throws and groundwork are allowed, but kicks to the head aren't, the tables will turn), and even as much as how good/bad a day someone's been having and even sheer luck (Remember, one lucky hit can be all it takes)
Of course, each style has its strengths and weaknesses. Once you understand your system well enough (and your own body, for that matter), you can start playing with the strengths and the weaknesses. You can get creative with them. That's an important part of the experience part mentioned above.
But yeah, in short: You can't just compare style A with style B. A kid who did 3 weeks boxing classes won't win against Ip Man. A kid who did Wing Chun for 3 weeks won't win against Mohammed Ali. | I don't think that it makes too much sense to compare styles instead of individual athletes, but I will try to answer your question anyway.
There is no one answer to this as it is very hard to say how important the advantages and disadvantages of both styles are. Therefore I will give you some insight to the advantages/disadvantages and you can think about it yourself.
Wing Chun has good punches, which may be the fastest with the least amount of telegraphing, but they have less range and have a less power compared to the punch of a boxer (they are still powerful and hurt).
But the most important thing is the range. Wing Chun and Boxers have different ranges in which they work and feel comfortable. Also because of the range, they have different tactics to be in that range.
A boxer normally stays back, out of range, moving in to strike then moving back again.
A wing chun practioner will be much closer to their opponent and tries to stay close (this is one reason why "sticky hands" are important).
I assume that the fighter who can stay at his preferred range will win the fight. Wing chun focuses on sticking to the opponent, maintaining physical contact in some way. The sense of feeling is 6 times faster than the sense of seeing, which obviously gives a strong advantage to the wing chun fighter in their preferred range.
Some boxing schools start training in the wing chun range. If this is the case, the boxer has an advantage, because all boxers I know train a lot to get into their range.
An additional point I can imagine that a boxer could lose because he underestimates his opponent in general. On the other hand I see a good chance, that the wing chun practitioner gets knocked out by a hook, because I have seen a lot of wing chun people underestimating every round technique.
Wrestling and wing chun are even more difficult to compare, but I think it's about the same as with a boxer versus a wing chun guy. |
7,660 | I've started Wing Chun few days before. Everything seems to be nice, but I've seen some videos on internet, they say that Wing Chun can't handle Boxers or Wrestlers.
What are the comparisons between Wing Chun and boxing/wrestling that would lead someone to make this claim? Are there weaknesses that can be exploited? | 2017/07/16 | [
"https://martialarts.stackexchange.com/questions/7660",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/-1/"
] | As always, you can't compare style A with style B and say either one is better. It's not because you're a boxer, you immediately win agains a wing chun practitioner. It all depends on how good both fighters are, how much experience they got fighting opponents of different styles, the competition's rules (eg. if you pit a judoka vs. a taekwondo, and rules state no throws or groundwork, chances are the taekwondo will win. If the rules state throws and groundwork are allowed, but kicks to the head aren't, the tables will turn), and even as much as how good/bad a day someone's been having and even sheer luck (Remember, one lucky hit can be all it takes)
Of course, each style has its strengths and weaknesses. Once you understand your system well enough (and your own body, for that matter), you can start playing with the strengths and the weaknesses. You can get creative with them. That's an important part of the experience part mentioned above.
But yeah, in short: You can't just compare style A with style B. A kid who did 3 weeks boxing classes won't win against Ip Man. A kid who did Wing Chun for 3 weeks won't win against Mohammed Ali. | So there are some fundamental assumptions here that one must look at with "intent or goal".
**Goal:
To beat your opponent senseless?**
* If this is your goal then you will probably want a style that focuses aggression and subjugation of your opponent over anything else.
**Goal:
To protect oneself?**
* If this is the goal then any discipline which focuses on body mechanics as well as properly analyzing a situation and working to diffuse it works well.
**Goal:
To develop oneself through discipline and mastery of ones body?**
* If this is the goal then the ability to "beat someone" isn't really as important as the type of person you become through the exercise and mastery of the art. Boxing, Wrestling, Kung Fu, Tai Chi, Karate, etc... all have the ability to develop ones physical and mental techniques while disciplining and harnessing ones own inner self for personal growth.
P.S. Unless you are practicing just for a MMA full contact event, then any style has use, purpose, and value. The only caveat to add is if you are grappling it's hard to hit and if you are at a distance it's hard to grapple, so there is a body mechanics balance needed to be well rounded.
P.P.S. As far as ability to beat another opponent, this is largely circumspect on the individual's abilities and if one is better skilled and physically capable then they will likely win regardless of the style in question. |
7,660 | I've started Wing Chun few days before. Everything seems to be nice, but I've seen some videos on internet, they say that Wing Chun can't handle Boxers or Wrestlers.
What are the comparisons between Wing Chun and boxing/wrestling that would lead someone to make this claim? Are there weaknesses that can be exploited? | 2017/07/16 | [
"https://martialarts.stackexchange.com/questions/7660",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/-1/"
] | I don't think that it makes too much sense to compare styles instead of individual athletes, but I will try to answer your question anyway.
There is no one answer to this as it is very hard to say how important the advantages and disadvantages of both styles are. Therefore I will give you some insight to the advantages/disadvantages and you can think about it yourself.
Wing Chun has good punches, which may be the fastest with the least amount of telegraphing, but they have less range and have a less power compared to the punch of a boxer (they are still powerful and hurt).
But the most important thing is the range. Wing Chun and Boxers have different ranges in which they work and feel comfortable. Also because of the range, they have different tactics to be in that range.
A boxer normally stays back, out of range, moving in to strike then moving back again.
A wing chun practioner will be much closer to their opponent and tries to stay close (this is one reason why "sticky hands" are important).
I assume that the fighter who can stay at his preferred range will win the fight. Wing chun focuses on sticking to the opponent, maintaining physical contact in some way. The sense of feeling is 6 times faster than the sense of seeing, which obviously gives a strong advantage to the wing chun fighter in their preferred range.
Some boxing schools start training in the wing chun range. If this is the case, the boxer has an advantage, because all boxers I know train a lot to get into their range.
An additional point I can imagine that a boxer could lose because he underestimates his opponent in general. On the other hand I see a good chance, that the wing chun practitioner gets knocked out by a hook, because I have seen a lot of wing chun people underestimating every round technique.
Wrestling and wing chun are even more difficult to compare, but I think it's about the same as with a boxer versus a wing chun guy. | So there are some fundamental assumptions here that one must look at with "intent or goal".
**Goal:
To beat your opponent senseless?**
* If this is your goal then you will probably want a style that focuses aggression and subjugation of your opponent over anything else.
**Goal:
To protect oneself?**
* If this is the goal then any discipline which focuses on body mechanics as well as properly analyzing a situation and working to diffuse it works well.
**Goal:
To develop oneself through discipline and mastery of ones body?**
* If this is the goal then the ability to "beat someone" isn't really as important as the type of person you become through the exercise and mastery of the art. Boxing, Wrestling, Kung Fu, Tai Chi, Karate, etc... all have the ability to develop ones physical and mental techniques while disciplining and harnessing ones own inner self for personal growth.
P.S. Unless you are practicing just for a MMA full contact event, then any style has use, purpose, and value. The only caveat to add is if you are grappling it's hard to hit and if you are at a distance it's hard to grapple, so there is a body mechanics balance needed to be well rounded.
P.P.S. As far as ability to beat another opponent, this is largely circumspect on the individual's abilities and if one is better skilled and physically capable then they will likely win regardless of the style in question. |
7,660 | I've started Wing Chun few days before. Everything seems to be nice, but I've seen some videos on internet, they say that Wing Chun can't handle Boxers or Wrestlers.
What are the comparisons between Wing Chun and boxing/wrestling that would lead someone to make this claim? Are there weaknesses that can be exploited? | 2017/07/16 | [
"https://martialarts.stackexchange.com/questions/7660",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/-1/"
] | The great advantage of boxing and wrestling is that boxers and wrestlers practice actual fighting, with all other elements of their training - weights, bag work, jumping rope - in support of improving them as fighters. Even when practicing a constrained format a boxer's conditioning, strength and (most importantly) familiarity with hard contact will invariably see them roll over the top of more esoteric fighting methods. Regardless of the style, the single greatest determinant of effectiveness is hard, realistic sparring. If you want to learn how to fight, practice fighting. It's a no brainer | I don't think that it makes too much sense to compare styles instead of individual athletes, but I will try to answer your question anyway.
There is no one answer to this as it is very hard to say how important the advantages and disadvantages of both styles are. Therefore I will give you some insight to the advantages/disadvantages and you can think about it yourself.
Wing Chun has good punches, which may be the fastest with the least amount of telegraphing, but they have less range and have a less power compared to the punch of a boxer (they are still powerful and hurt).
But the most important thing is the range. Wing Chun and Boxers have different ranges in which they work and feel comfortable. Also because of the range, they have different tactics to be in that range.
A boxer normally stays back, out of range, moving in to strike then moving back again.
A wing chun practioner will be much closer to their opponent and tries to stay close (this is one reason why "sticky hands" are important).
I assume that the fighter who can stay at his preferred range will win the fight. Wing chun focuses on sticking to the opponent, maintaining physical contact in some way. The sense of feeling is 6 times faster than the sense of seeing, which obviously gives a strong advantage to the wing chun fighter in their preferred range.
Some boxing schools start training in the wing chun range. If this is the case, the boxer has an advantage, because all boxers I know train a lot to get into their range.
An additional point I can imagine that a boxer could lose because he underestimates his opponent in general. On the other hand I see a good chance, that the wing chun practitioner gets knocked out by a hook, because I have seen a lot of wing chun people underestimating every round technique.
Wrestling and wing chun are even more difficult to compare, but I think it's about the same as with a boxer versus a wing chun guy. |
7,660 | I've started Wing Chun few days before. Everything seems to be nice, but I've seen some videos on internet, they say that Wing Chun can't handle Boxers or Wrestlers.
What are the comparisons between Wing Chun and boxing/wrestling that would lead someone to make this claim? Are there weaknesses that can be exploited? | 2017/07/16 | [
"https://martialarts.stackexchange.com/questions/7660",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/-1/"
] | The great advantage of boxing and wrestling is that boxers and wrestlers practice actual fighting, with all other elements of their training - weights, bag work, jumping rope - in support of improving them as fighters. Even when practicing a constrained format a boxer's conditioning, strength and (most importantly) familiarity with hard contact will invariably see them roll over the top of more esoteric fighting methods. Regardless of the style, the single greatest determinant of effectiveness is hard, realistic sparring. If you want to learn how to fight, practice fighting. It's a no brainer | So there are some fundamental assumptions here that one must look at with "intent or goal".
**Goal:
To beat your opponent senseless?**
* If this is your goal then you will probably want a style that focuses aggression and subjugation of your opponent over anything else.
**Goal:
To protect oneself?**
* If this is the goal then any discipline which focuses on body mechanics as well as properly analyzing a situation and working to diffuse it works well.
**Goal:
To develop oneself through discipline and mastery of ones body?**
* If this is the goal then the ability to "beat someone" isn't really as important as the type of person you become through the exercise and mastery of the art. Boxing, Wrestling, Kung Fu, Tai Chi, Karate, etc... all have the ability to develop ones physical and mental techniques while disciplining and harnessing ones own inner self for personal growth.
P.S. Unless you are practicing just for a MMA full contact event, then any style has use, purpose, and value. The only caveat to add is if you are grappling it's hard to hit and if you are at a distance it's hard to grapple, so there is a body mechanics balance needed to be well rounded.
P.P.S. As far as ability to beat another opponent, this is largely circumspect on the individual's abilities and if one is better skilled and physically capable then they will likely win regardless of the style in question. |
12,011,559 | I have the following html that is bound to an object containing id and status. I want to translate status values into a specific color (hence the converter function convertStatus). I can see the converter work on the first binding, but if I change status in the binding list I do not see any UI update nor do I see convertStatus being subsequently called. My other issue is trying to bind the id property of the first span does not seem to work as expected (perhaps it is not possible to set this value via binding...)
HTML:
```
<span data-win-bind="id: id">person</span>
<span data-win-bind="textContent: status converter.convertStatus"></span>
```
Javascript (I have tried using to modify the status value):
>
> // persons === WinJS.Binding.List
>
> // updateStatus is a function that is called as a result of status changing in the system
>
>
>
```
function updateStatus(data) {
persons.forEach(function(value, index, array) {
if(value.id === data.id) {
value.status = data.status;
persons.notifyMutated(index);
}
}, this);
}
```
I have seen notifyMutated(index) work for values that are not using a converter.
**Updating with github project**
[Public repo for sample (not-working)](https://github.com/ShelbyZ/winjs-data-binding) - this is a really basic app that has a listview with a set of default data and a function that is executed when the item is clicked. The function attempts to randomize one of the bound fields of the item and call notifyMutated(...) on the list to trigger a visual updated. Even with defining the WinJS.Binding.List({ binding: true }); I do not see updates unless I force it via notifyReload(), which produces a reload-flicker on the listview element. | 2012/08/17 | [
"https://Stackoverflow.com/questions/12011559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665106/"
] | To answer your two questions:
1) Why can't I set id through binding?
This is deliberately prevented. The WinJS binding system uses the ID to track the element that it's binding to (to avoid leaking DOM elements through dangling bindings). As such, it has to be able to control the id for bound templates.
2) Why isn't the converter firing more than once?
The Binding.List will tell the listview about changes in the contents of the list (items added, removed, or moved around) but it's the responsibility of the individual items to notify the listview about changes in their contents.
You need to have a data object that's bindable. There are a couple of options:
* Call `WinJS.Binding.as` on the elements as you add them to the collection
* Turn on binding mode on the Binding.List
The latter is probably easier. Basically, when you create your Binding.List, do this:
```
var list = new WinJS.Binding.List({binding: true});
```
That way the List will call binding.as on everything in the list, and things should start updating. | I've found that if I doing the following, I will see updates to the UI post-binding:
```
var list = new WinJS.Binding.List({binding: true});
var item = WinJS.Binding.as({
firstName: "Billy",
lastName: "Bob"
});
list.push(item);
```
Later in the application, you can change some values like so:
```
item.firstName = "Bobby";
item.lastName = "Joe";
```
...and you will see the changes in the UI
Here's a link on MSDN for more information:
[MSDN - WinJS.Binding.as](http://msdn.microsoft.com/en-us/library/windows/apps/xaml/br229801.aspx) |
12,011,559 | I have the following html that is bound to an object containing id and status. I want to translate status values into a specific color (hence the converter function convertStatus). I can see the converter work on the first binding, but if I change status in the binding list I do not see any UI update nor do I see convertStatus being subsequently called. My other issue is trying to bind the id property of the first span does not seem to work as expected (perhaps it is not possible to set this value via binding...)
HTML:
```
<span data-win-bind="id: id">person</span>
<span data-win-bind="textContent: status converter.convertStatus"></span>
```
Javascript (I have tried using to modify the status value):
>
> // persons === WinJS.Binding.List
>
> // updateStatus is a function that is called as a result of status changing in the system
>
>
>
```
function updateStatus(data) {
persons.forEach(function(value, index, array) {
if(value.id === data.id) {
value.status = data.status;
persons.notifyMutated(index);
}
}, this);
}
```
I have seen notifyMutated(index) work for values that are not using a converter.
**Updating with github project**
[Public repo for sample (not-working)](https://github.com/ShelbyZ/winjs-data-binding) - this is a really basic app that has a listview with a set of default data and a function that is executed when the item is clicked. The function attempts to randomize one of the bound fields of the item and call notifyMutated(...) on the list to trigger a visual updated. Even with defining the WinJS.Binding.List({ binding: true }); I do not see updates unless I force it via notifyReload(), which produces a reload-flicker on the listview element. | 2012/08/17 | [
"https://Stackoverflow.com/questions/12011559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665106/"
] | To answer your two questions:
1) Why can't I set id through binding?
This is deliberately prevented. The WinJS binding system uses the ID to track the element that it's binding to (to avoid leaking DOM elements through dangling bindings). As such, it has to be able to control the id for bound templates.
2) Why isn't the converter firing more than once?
The Binding.List will tell the listview about changes in the contents of the list (items added, removed, or moved around) but it's the responsibility of the individual items to notify the listview about changes in their contents.
You need to have a data object that's bindable. There are a couple of options:
* Call `WinJS.Binding.as` on the elements as you add them to the collection
* Turn on binding mode on the Binding.List
The latter is probably easier. Basically, when you create your Binding.List, do this:
```
var list = new WinJS.Binding.List({binding: true});
```
That way the List will call binding.as on everything in the list, and things should start updating. | Regarding setting the value of id.
I found that I was able to set the value of the name attribute, for a <button>.
I had been trying to set id, but that wouldn't work.
HTH |
12,011,559 | I have the following html that is bound to an object containing id and status. I want to translate status values into a specific color (hence the converter function convertStatus). I can see the converter work on the first binding, but if I change status in the binding list I do not see any UI update nor do I see convertStatus being subsequently called. My other issue is trying to bind the id property of the first span does not seem to work as expected (perhaps it is not possible to set this value via binding...)
HTML:
```
<span data-win-bind="id: id">person</span>
<span data-win-bind="textContent: status converter.convertStatus"></span>
```
Javascript (I have tried using to modify the status value):
>
> // persons === WinJS.Binding.List
>
> // updateStatus is a function that is called as a result of status changing in the system
>
>
>
```
function updateStatus(data) {
persons.forEach(function(value, index, array) {
if(value.id === data.id) {
value.status = data.status;
persons.notifyMutated(index);
}
}, this);
}
```
I have seen notifyMutated(index) work for values that are not using a converter.
**Updating with github project**
[Public repo for sample (not-working)](https://github.com/ShelbyZ/winjs-data-binding) - this is a really basic app that has a listview with a set of default data and a function that is executed when the item is clicked. The function attempts to randomize one of the bound fields of the item and call notifyMutated(...) on the list to trigger a visual updated. Even with defining the WinJS.Binding.List({ binding: true }); I do not see updates unless I force it via notifyReload(), which produces a reload-flicker on the listview element. | 2012/08/17 | [
"https://Stackoverflow.com/questions/12011559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665106/"
] | To answer your two questions:
1) Why can't I set id through binding?
This is deliberately prevented. The WinJS binding system uses the ID to track the element that it's binding to (to avoid leaking DOM elements through dangling bindings). As such, it has to be able to control the id for bound templates.
2) Why isn't the converter firing more than once?
The Binding.List will tell the listview about changes in the contents of the list (items added, removed, or moved around) but it's the responsibility of the individual items to notify the listview about changes in their contents.
You need to have a data object that's bindable. There are a couple of options:
* Call `WinJS.Binding.as` on the elements as you add them to the collection
* Turn on binding mode on the Binding.List
The latter is probably easier. Basically, when you create your Binding.List, do this:
```
var list = new WinJS.Binding.List({binding: true});
```
That way the List will call binding.as on everything in the list, and things should start updating. | optimizeBindingReferences property
Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use Windows Library for JavaScript (WinJS) binding.
```
WinJS.Binding.optimizeBindingReferences = true;
```
source: <http://msdn.microsoft.com/en-us/library/windows/apps/jj215606.aspx> |
46,586,267 | Context
-------
For quite a lot of our CentOS servers I would like to install some monitoring software, the software is based on the CentOS version, I want to check the release version and install software based on that.
Issue
-----
It seems that the if statements are run successfully without errors while the results never should be true for both or all three if statements. I've looked into the if commands and the tests, it seems that I should use double brackets and single = symbol in bash. I believe that I'm doing something really simple wrong, but I just can't find it.
Code
----
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version"="CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run commands for this specific version
fi
if [[ "$version"="CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run commands for this specific version
fi
if [[ "$versionknown"=false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results
-------
```
Same versions as expected
Same versions as expected v2
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
true
```
Update
======
After getting some responses I've changed my code, adding spaces around the equal signs(=). Still doesn't work as intended since the comparison should return true on the second if statement which it doesn't.
Code #2
-------
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" = "CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run script for this specific version
fi
if [[ "$version" = "CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run script for this specific version
fi
if [[ "$versionknown" = false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results #2
----------
```
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
false
```
Update
======
`declare -p version` learned me that `/etc/centos-release` has a space added to the end of the script file, I believe that on CentOS release 6.9 (Final) that wasn't the case. Adding the space in the string, or all together making use of my known\_version variables and adding the space solves the issues, script now works as intended. | 2017/10/05 | [
"https://Stackoverflow.com/questions/46586267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8726241/"
] | As a general rule of thumb, on probably all of the programming languages, a single equal (`=`) sign is for assignment and not for equality check which in this case is double equal (`=`) sign.
The reason you're entering all of your `if` statements is that the result of your assignment expression is `true` and therefore the `if` statement is being evaluated as `true` and being executed.
**Update**
Thanks for @chepner's comment, a single equal (`=`) sign is used for equality check when associated with single square brackets `[ ]` or double square brackets `[[ ]]`. bash also supports double equal (`=`) sign as equality check in both cases `[ ]` or `[[ ]]`.
What you want is probably this:
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" == "CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run commands for this specific version
fi
if [[ "$version" == "CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run commands for this specific version
fi
if [[ "$versionknown" == "false" ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
``` | You are doing something wrong in your if-statement.
Simple answer:
1. Make sure to use the `==` if you want to compare strings.
2. Please use `if [ "$version" == "xyz" ]` instead of `if [[ "$version" = "xyz" ]]`
Summarized: `if [ "$version"=="CentOS release 6.9 (Final)" ]; then` and it sould work!
Regards, FrankTheTank |
46,586,267 | Context
-------
For quite a lot of our CentOS servers I would like to install some monitoring software, the software is based on the CentOS version, I want to check the release version and install software based on that.
Issue
-----
It seems that the if statements are run successfully without errors while the results never should be true for both or all three if statements. I've looked into the if commands and the tests, it seems that I should use double brackets and single = symbol in bash. I believe that I'm doing something really simple wrong, but I just can't find it.
Code
----
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version"="CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run commands for this specific version
fi
if [[ "$version"="CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run commands for this specific version
fi
if [[ "$versionknown"=false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results
-------
```
Same versions as expected
Same versions as expected v2
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
true
```
Update
======
After getting some responses I've changed my code, adding spaces around the equal signs(=). Still doesn't work as intended since the comparison should return true on the second if statement which it doesn't.
Code #2
-------
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" = "CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run script for this specific version
fi
if [[ "$version" = "CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run script for this specific version
fi
if [[ "$versionknown" = false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results #2
----------
```
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
false
```
Update
======
`declare -p version` learned me that `/etc/centos-release` has a space added to the end of the script file, I believe that on CentOS release 6.9 (Final) that wasn't the case. Adding the space in the string, or all together making use of my known\_version variables and adding the space solves the issues, script now works as intended. | 2017/10/05 | [
"https://Stackoverflow.com/questions/46586267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8726241/"
] | You need whitespace around the `=` sign; without it, the shell treats the "expression" as a single word, not a comparison of two words for equality.
```
[[ "$version" = "CentOS release 6.9 (Final)" ]]
```
`[[ a=b ]]` is equivalent to `[[ -n a=b ]]`, i.e., you are simply testing if the single word is a non-empty string.
Whether you use `=` or `==` inside `[[ ... ]]` is a matter of style; `bash` supports both.
I would avoid using a `versionknown` variable altogether, and write the code like this:
```
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" = "$known_version1" ]] ; then
echo "Same versions as expected"
#run commands for this specific version
elif [[ "$version" = "$known_version2" ]] ; then
echo "Same versions as expected v2"
#run commands for this specific version
else
echo "Different version detected than known:"
echo "$version"
echo "Aborted"
fi
```
or a `case` statement
```
case $version in
"$known_version1")
echo "Same versions as expected"
# ...
;;
"$known_version2")
echo "Same versions as expected v2"
# ...
;;
*)
echo "Different version detected than known:"
echo "$version"
echo "Aborted"
esac
``` | As a general rule of thumb, on probably all of the programming languages, a single equal (`=`) sign is for assignment and not for equality check which in this case is double equal (`=`) sign.
The reason you're entering all of your `if` statements is that the result of your assignment expression is `true` and therefore the `if` statement is being evaluated as `true` and being executed.
**Update**
Thanks for @chepner's comment, a single equal (`=`) sign is used for equality check when associated with single square brackets `[ ]` or double square brackets `[[ ]]`. bash also supports double equal (`=`) sign as equality check in both cases `[ ]` or `[[ ]]`.
What you want is probably this:
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" == "CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run commands for this specific version
fi
if [[ "$version" == "CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run commands for this specific version
fi
if [[ "$versionknown" == "false" ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
``` |
46,586,267 | Context
-------
For quite a lot of our CentOS servers I would like to install some monitoring software, the software is based on the CentOS version, I want to check the release version and install software based on that.
Issue
-----
It seems that the if statements are run successfully without errors while the results never should be true for both or all three if statements. I've looked into the if commands and the tests, it seems that I should use double brackets and single = symbol in bash. I believe that I'm doing something really simple wrong, but I just can't find it.
Code
----
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version"="CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run commands for this specific version
fi
if [[ "$version"="CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run commands for this specific version
fi
if [[ "$versionknown"=false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results
-------
```
Same versions as expected
Same versions as expected v2
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
true
```
Update
======
After getting some responses I've changed my code, adding spaces around the equal signs(=). Still doesn't work as intended since the comparison should return true on the second if statement which it doesn't.
Code #2
-------
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" = "CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run script for this specific version
fi
if [[ "$version" = "CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run script for this specific version
fi
if [[ "$versionknown" = false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results #2
----------
```
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
false
```
Update
======
`declare -p version` learned me that `/etc/centos-release` has a space added to the end of the script file, I believe that on CentOS release 6.9 (Final) that wasn't the case. Adding the space in the string, or all together making use of my known\_version variables and adding the space solves the issues, script now works as intended. | 2017/10/05 | [
"https://Stackoverflow.com/questions/46586267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8726241/"
] | You need whitespace around the `=` sign; without it, the shell treats the "expression" as a single word, not a comparison of two words for equality.
```
[[ "$version" = "CentOS release 6.9 (Final)" ]]
```
`[[ a=b ]]` is equivalent to `[[ -n a=b ]]`, i.e., you are simply testing if the single word is a non-empty string.
Whether you use `=` or `==` inside `[[ ... ]]` is a matter of style; `bash` supports both.
I would avoid using a `versionknown` variable altogether, and write the code like this:
```
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" = "$known_version1" ]] ; then
echo "Same versions as expected"
#run commands for this specific version
elif [[ "$version" = "$known_version2" ]] ; then
echo "Same versions as expected v2"
#run commands for this specific version
else
echo "Different version detected than known:"
echo "$version"
echo "Aborted"
fi
```
or a `case` statement
```
case $version in
"$known_version1")
echo "Same versions as expected"
# ...
;;
"$known_version2")
echo "Same versions as expected v2"
# ...
;;
*)
echo "Different version detected than known:"
echo "$version"
echo "Aborted"
esac
``` | You are doing something wrong in your if-statement.
Simple answer:
1. Make sure to use the `==` if you want to compare strings.
2. Please use `if [ "$version" == "xyz" ]` instead of `if [[ "$version" = "xyz" ]]`
Summarized: `if [ "$version"=="CentOS release 6.9 (Final)" ]; then` and it sould work!
Regards, FrankTheTank |
539,083 | I am trying to build a small circuit using an ESP8288-12E, 4 5V relays and a 74HC595 shift register as the main components. To power the whole circuit I am using a Hi Link HLK 5M05 5V/5W switch power supply module.
Here is how I planned the whole circuit:
[![enter image description here](https://i.stack.imgur.com/iTD0j.jpg)](https://i.stack.imgur.com/iTD0j.jpg)
If it is difficult to see in this image then I can provide PDF as well.
I took this AMS1117-3.3 to get 3.3V from my 5V power supply. Instead of 3.3C, I am getting 4.2V on my PCB. I am not sure why this is happening.
I am attaching my EasyEDA file for the PCB design also.
[![enter image description here](https://i.stack.imgur.com/ogBMW.png)](https://i.stack.imgur.com/ogBMW.png)
One more issue I am facing is that when i take my multi-meter probes near to the circuit the relays are triggering automatically. I didn't connect the ESP8266-12E on the PCB yet, as I am not getting proper voltage on ESP8266-12E VCC pin.
Any suggestions, why this issue might be happening? Any suggestions will be helpful!
If someone wants to have an EasyEDA access I can provide for this project so can visualize the same issue more easily.
<https://oshwlab.com/nehul.splendit/shift-resistor-sn74hc595-with-4-channel-relay>
Here is the link of the same project. | 2020/12/25 | [
"https://electronics.stackexchange.com/questions/539083",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/212459/"
] | If there is no load at all on the 3V3 regulator, it has no minimum required load so it won't output 3V3.
When there is no ESP connected, there is nothing connected on HC595 input pins, so they are floating. The input impedance is so high that taking multimeter probes nearby will cause the HC595 to see activity on input pins and it will randomly load in a data pattern to drive the relays to they will chatter on and off.
Also do note that inputs of HC595 fed with 5V is not compatible with 3.3V outputs of ESP. Either change the HC type to something else that can work with 3.3V input voltages, or change the supply of HC595 to 3V3.
Edit: Oh dear I just realized the supply that converts mains voltage to 5V is not external but onboard. The PCB layout is not safe for mains voltage at all. Not the mains input to supply, and not the relay contact wiring either. Please don't connect this to mains as it is unsafe. | Throw away that pcb before it kills you and burns down your house - I’m not joking. As others have observed, the clearance between tracks carrying mains voltages and low voltage tracks is nowhere near safe.
Have your mains wiring down one end of the pcb well away from the low voltage circuit. What current do you expect to switch with the relays? What voltage? I’d also suggest you use different relays like the omron G2R series - these are easier the design the pcb for and to ensure adequate clearance. The relays you’ve used require slots in the pcb and more care in the design. Do not use copper pours in the mains region!
Consider using a tpic6b595 instead of transistors and a 74hc595.
The esp12 module needs to be placed carefully - read the datasheet guidelines.
Throw away your current pcb before it becomes the first and last one you design. |
66,223,067 | Is it possible to expose all the Spring metrics in an rest endpoint?
In our environment Micrometer cannot forward directly the metrics to our monitoring system, then my idea was to have all the metrics exposed in a rest endpoint (or on a file, json format but the endpoint is preferable) and then having a script to fetch all the metrics at once, manipulate the payload and forward the metrics to our customized monitoring api.
If micrometer is not the right choice, what is it?
**EDIT**
I tried to use the actuator/prometheus endpoint. I can see the endpoint but as soon as I hit the endpoint, it hang and does not return anything:
I am using spring boot 2.2.2 and I added this dependency
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.3.1</version>
</dependency>
```
application.yml
```
management:
endpoints:
web:
exposure:
include: health, metrics, prometheus
``` | 2021/02/16 | [
"https://Stackoverflow.com/questions/66223067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/980515/"
] | You may use this redirect rule in your site root .htaccess:
```sh
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?website\.com$ [NC]
RewriteRule ^reservation/?$ https://test.com/test/page [L,NC,R=301]
```
Query string and fragment i.e. part after `#` will automatically be forwarded to the new URL. | Based on your shown samples, could you please try following. Where you want to redirect from `(www).website.com` to `new-website.com` in url.
Please make sure you clear your browser cache before testing your URLs.
```
RewriteEngine ON
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*) [NC]
RewriteRule ^ https://new-%1/test/page#!%{REQUEST_URI} [QSA,NE,R=301,L]
``` |
42,347,969 | how to block a jsp page
(i want is ,when I click the links to redirect each pages I want to block some specific pages for specific users)
I create an java script function to retrieve the jsp pages of each users(pages that user can access).But I have no idea to block other pages for the same user) | 2017/02/20 | [
"https://Stackoverflow.com/questions/42347969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983136/"
] | use js `document.getElementById("id name of link").style.display = 'none';` to remove the link from page and use **'block'** instead of **'none'** for showing the link. | You could use the `event.preventDefault();` and have a variable saying if the user should or not be blocked. Check the following example:
```js
var BlockUser = true;
function CheckUser() {
if ( BlockUser ) {
event.preventDefault();
}
}
```
```html
<a href="http://stackoverflow.com/">Link for any user</a>
<br>
<a href="http://stackoverflow.com/" onclick="CheckUser()">Link for certain users</a>
``` |
42,347,969 | how to block a jsp page
(i want is ,when I click the links to redirect each pages I want to block some specific pages for specific users)
I create an java script function to retrieve the jsp pages of each users(pages that user can access).But I have no idea to block other pages for the same user) | 2017/02/20 | [
"https://Stackoverflow.com/questions/42347969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983136/"
] | You could use the `event.preventDefault();` and have a variable saying if the user should or not be blocked. Check the following example:
```js
var BlockUser = true;
function CheckUser() {
if ( BlockUser ) {
event.preventDefault();
}
}
```
```html
<a href="http://stackoverflow.com/">Link for any user</a>
<br>
<a href="http://stackoverflow.com/" onclick="CheckUser()">Link for certain users</a>
``` | You can use this
```
document.getElementById( "id of your link element" ).style.display = 'none';
```
**`style.display`** is use for not displaying anything by setting it to **`none`** |
42,347,969 | how to block a jsp page
(i want is ,when I click the links to redirect each pages I want to block some specific pages for specific users)
I create an java script function to retrieve the jsp pages of each users(pages that user can access).But I have no idea to block other pages for the same user) | 2017/02/20 | [
"https://Stackoverflow.com/questions/42347969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983136/"
] | use js `document.getElementById("id name of link").style.display = 'none';` to remove the link from page and use **'block'** instead of **'none'** for showing the link. | Pure jsp solution:
assuming you have an array of available links: `List<String> links`, which you pass under the same name to request(or you may retrieve it from user, doesn't matter, assume you have array of those links despite way of getting it), then you can do something like:
```
...
<c:forEach var="link" items="${links}">
<a href="${link}" <c:if test="/*here you test if user have
access, i dont know how you do it*/"> class="inactiveLink" </c:if>>page link</a>
</c:forEach>
...
```
Where `...` is rest of your jsp, and define style
```
.inactiveLink {
pointer-events: none;
cursor: default;
}
```
Note that in order to use foreach - you should define jstl taglib at the top of your jsp:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
```
*In case you don't [know what is jstl](https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm), and what is [EL](http://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html) generally*
A good notion was said about disabling css and js, if you want them to be completely inaccessible, you can just print only allowed links:
```
...
<c:forEach var="link" items="${links}">
<c:if test="/*here you test if user have
access, i dont know how you do it*/">
<a href="${link}">page link</a>
</c:if>
</c:forEach>
...
``` |
42,347,969 | how to block a jsp page
(i want is ,when I click the links to redirect each pages I want to block some specific pages for specific users)
I create an java script function to retrieve the jsp pages of each users(pages that user can access).But I have no idea to block other pages for the same user) | 2017/02/20 | [
"https://Stackoverflow.com/questions/42347969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983136/"
] | Pure jsp solution:
assuming you have an array of available links: `List<String> links`, which you pass under the same name to request(or you may retrieve it from user, doesn't matter, assume you have array of those links despite way of getting it), then you can do something like:
```
...
<c:forEach var="link" items="${links}">
<a href="${link}" <c:if test="/*here you test if user have
access, i dont know how you do it*/"> class="inactiveLink" </c:if>>page link</a>
</c:forEach>
...
```
Where `...` is rest of your jsp, and define style
```
.inactiveLink {
pointer-events: none;
cursor: default;
}
```
Note that in order to use foreach - you should define jstl taglib at the top of your jsp:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
```
*In case you don't [know what is jstl](https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm), and what is [EL](http://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html) generally*
A good notion was said about disabling css and js, if you want them to be completely inaccessible, you can just print only allowed links:
```
...
<c:forEach var="link" items="${links}">
<c:if test="/*here you test if user have
access, i dont know how you do it*/">
<a href="${link}">page link</a>
</c:if>
</c:forEach>
...
``` | You can use this
```
document.getElementById( "id of your link element" ).style.display = 'none';
```
**`style.display`** is use for not displaying anything by setting it to **`none`** |
42,347,969 | how to block a jsp page
(i want is ,when I click the links to redirect each pages I want to block some specific pages for specific users)
I create an java script function to retrieve the jsp pages of each users(pages that user can access).But I have no idea to block other pages for the same user) | 2017/02/20 | [
"https://Stackoverflow.com/questions/42347969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983136/"
] | use js `document.getElementById("id name of link").style.display = 'none';` to remove the link from page and use **'block'** instead of **'none'** for showing the link. | You can use this
```
document.getElementById( "id of your link element" ).style.display = 'none';
```
**`style.display`** is use for not displaying anything by setting it to **`none`** |
44,124,940 | How would I go about dividing arrays into quarters?
For example, I want to ask the user to enter say 12 values. Then, divide them into 4 quarters and add the values in each quarter. I figured how to add all of them up, but I'm stuck on how to add them separately in groups.
Thank You.
```
import java.util.Scanner;
import java.util.stream.*;
public class SalesData {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] salesData = new int[12];
int monthNumber=1;
for (int i = 0; i < 12; i++) {
System.out.println("Please enter the data for month "+monthNumber);
salesData[i] = keyboard.nextInt();
int newNumber=monthNumber++;
}
System.out.println("The first quarter total is ");
System.out.println("The second quarter total is ");
System.out.println("The third quarter total is ");
System.out.println("The fourth quarter total is ");
double sum = IntStream.of(salesData).sum();
System.out.println("The Annual Sales Total is "+sum);
}//end main
}`
``` | 2017/05/23 | [
"https://Stackoverflow.com/questions/44124940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8051072/"
] | ```
String[] quarters = {"first", "second", "third", "fourth"};
for (int i = 0; i < 12; i += 3)
System.out.printf("The %s quarter total is %d%n",
quarters[i / 3],
Arrays.stream(salesData, i, i + 3).sum());
``` | You are on the right track, you already know all the pieces you need.
1. You know how to declare an array of a fixed size (12).
2. You know how to write a for loop.
3. You know how to index an array using the for loop counter.
So if I wanted to do the first quarter...
```
int firstQuarter = 0;
for (int i = 0; i < 3; i++)
{
firstQuarter = firstQuarter + salesData[i];
}
System.out.println("1st Quarter" + firstQuarter);
```
You could easily write one of these blocks for each quarter, but I challenge you to find a more elegant solution. Good luck! |
44,124,940 | How would I go about dividing arrays into quarters?
For example, I want to ask the user to enter say 12 values. Then, divide them into 4 quarters and add the values in each quarter. I figured how to add all of them up, but I'm stuck on how to add them separately in groups.
Thank You.
```
import java.util.Scanner;
import java.util.stream.*;
public class SalesData {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] salesData = new int[12];
int monthNumber=1;
for (int i = 0; i < 12; i++) {
System.out.println("Please enter the data for month "+monthNumber);
salesData[i] = keyboard.nextInt();
int newNumber=monthNumber++;
}
System.out.println("The first quarter total is ");
System.out.println("The second quarter total is ");
System.out.println("The third quarter total is ");
System.out.println("The fourth quarter total is ");
double sum = IntStream.of(salesData).sum();
System.out.println("The Annual Sales Total is "+sum);
}//end main
}`
``` | 2017/05/23 | [
"https://Stackoverflow.com/questions/44124940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8051072/"
] | ```
String[] quarters = {"first", "second", "third", "fourth"};
for (int i = 0; i < 12; i += 3)
System.out.printf("The %s quarter total is %d%n",
quarters[i / 3],
Arrays.stream(salesData, i, i + 3).sum());
``` | You don't say specifically, but let's just assume that quarter #1 is entries 0 - 2 in 'salesData`; quarter #2 is entries 3 to 5, etc.
Here's one way to find and print the quarter totals:
```
int salesData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int qtotal[] = new int[4];
for (int q = 0; q < 4; ++q) {
qtotal[q] = 0;
for (int i = 0; i < 3; ++i) {
qtotal[q] += salesData[q * 3 + i];
}
}
for (int q = 0; q < 4; ++q) {
System.out.printf("Quarter #%d total: %d\n ", q + 1, qtotal[q]);
}
``` |
28,277,685 | I have webpages with URL <http://siteurl/directory/onemore/>$fileID.php
I am trying to extract just the $fileID and after that use
```
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
$hits = $hits + 1;
$query = $mysqli->query("UPDATE tablename SET HITS = $hits WHERE ID = $fileID");
echo 'Total hits on page'.$hits.'';
```
I can't figure out how to get just the $fileID part and wanted to ask is the rest of my procedure correct?
**EDIT**
With the code above hits get stuck at one. I was thinking that after each page refresh they will update to +1. | 2015/02/02 | [
"https://Stackoverflow.com/questions/28277685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516574/"
] | You can determine the $fileId like this:
```
/* $_SERVER['PHP_SELF'] results to e.g. '/directory/onemore/5.php' */
/* basename(...) results to e.g. '5.php' */
$fileName = basename($_SERVER['PHP_SELF']);
/* take the text before the last occurrence of '.' */
$fileID = substr($fileName, 0, strrpos($fileName, '.'));
$query = $mysqli->query("UPDATE tablename SET HITS = HITS + 1 WHERE ID = $fileID");
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
echo 'Total hits on page'.$hits.'';
``` | Try this:
```
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
```
>
> Output
>
>
>
```
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
```
See, if that helps. |
28,277,685 | I have webpages with URL <http://siteurl/directory/onemore/>$fileID.php
I am trying to extract just the $fileID and after that use
```
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
$hits = $hits + 1;
$query = $mysqli->query("UPDATE tablename SET HITS = $hits WHERE ID = $fileID");
echo 'Total hits on page'.$hits.'';
```
I can't figure out how to get just the $fileID part and wanted to ask is the rest of my procedure correct?
**EDIT**
With the code above hits get stuck at one. I was thinking that after each page refresh they will update to +1. | 2015/02/02 | [
"https://Stackoverflow.com/questions/28277685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516574/"
] | Try this:
```
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
```
>
> Output
>
>
>
```
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
```
See, if that helps. | Getting $fileID of the URL:
Have a look at [pathinfo()](http://php.net/manual/de/function.pathinfo.php) - this function extracts the URL in different parts
In your case it would be:
```
$path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);
$fileID = $path_parts['filename'];
```
Your update query will work, in case you only want to count without showing the new value, you could make it more simple - just increment HITS while updating the table row:
```
$query = mysqli->query("UPDATE tablename SET HITS = HITS+1 WHERE ID = $fileID");
``` |
28,277,685 | I have webpages with URL <http://siteurl/directory/onemore/>$fileID.php
I am trying to extract just the $fileID and after that use
```
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
$hits = $hits + 1;
$query = $mysqli->query("UPDATE tablename SET HITS = $hits WHERE ID = $fileID");
echo 'Total hits on page'.$hits.'';
```
I can't figure out how to get just the $fileID part and wanted to ask is the rest of my procedure correct?
**EDIT**
With the code above hits get stuck at one. I was thinking that after each page refresh they will update to +1. | 2015/02/02 | [
"https://Stackoverflow.com/questions/28277685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516574/"
] | You can determine the $fileId like this:
```
/* $_SERVER['PHP_SELF'] results to e.g. '/directory/onemore/5.php' */
/* basename(...) results to e.g. '5.php' */
$fileName = basename($_SERVER['PHP_SELF']);
/* take the text before the last occurrence of '.' */
$fileID = substr($fileName, 0, strrpos($fileName, '.'));
$query = $mysqli->query("UPDATE tablename SET HITS = HITS + 1 WHERE ID = $fileID");
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
echo 'Total hits on page'.$hits.'';
``` | If you don't need to print the hits every time, you can increment it in a single query which is a bit more clear and efficient.
```
UPDATE tablename SET hits = hits + 1 WHERE id = $fileID
``` |
28,277,685 | I have webpages with URL <http://siteurl/directory/onemore/>$fileID.php
I am trying to extract just the $fileID and after that use
```
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
$hits = $hits + 1;
$query = $mysqli->query("UPDATE tablename SET HITS = $hits WHERE ID = $fileID");
echo 'Total hits on page'.$hits.'';
```
I can't figure out how to get just the $fileID part and wanted to ask is the rest of my procedure correct?
**EDIT**
With the code above hits get stuck at one. I was thinking that after each page refresh they will update to +1. | 2015/02/02 | [
"https://Stackoverflow.com/questions/28277685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516574/"
] | You can determine the $fileId like this:
```
/* $_SERVER['PHP_SELF'] results to e.g. '/directory/onemore/5.php' */
/* basename(...) results to e.g. '5.php' */
$fileName = basename($_SERVER['PHP_SELF']);
/* take the text before the last occurrence of '.' */
$fileID = substr($fileName, 0, strrpos($fileName, '.'));
$query = $mysqli->query("UPDATE tablename SET HITS = HITS + 1 WHERE ID = $fileID");
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
echo 'Total hits on page'.$hits.'';
``` | Getting $fileID of the URL:
Have a look at [pathinfo()](http://php.net/manual/de/function.pathinfo.php) - this function extracts the URL in different parts
In your case it would be:
```
$path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);
$fileID = $path_parts['filename'];
```
Your update query will work, in case you only want to count without showing the new value, you could make it more simple - just increment HITS while updating the table row:
```
$query = mysqli->query("UPDATE tablename SET HITS = HITS+1 WHERE ID = $fileID");
``` |
28,277,685 | I have webpages with URL <http://siteurl/directory/onemore/>$fileID.php
I am trying to extract just the $fileID and after that use
```
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
$hits = $hits + 1;
$query = $mysqli->query("UPDATE tablename SET HITS = $hits WHERE ID = $fileID");
echo 'Total hits on page'.$hits.'';
```
I can't figure out how to get just the $fileID part and wanted to ask is the rest of my procedure correct?
**EDIT**
With the code above hits get stuck at one. I was thinking that after each page refresh they will update to +1. | 2015/02/02 | [
"https://Stackoverflow.com/questions/28277685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516574/"
] | If you don't need to print the hits every time, you can increment it in a single query which is a bit more clear and efficient.
```
UPDATE tablename SET hits = hits + 1 WHERE id = $fileID
``` | Getting $fileID of the URL:
Have a look at [pathinfo()](http://php.net/manual/de/function.pathinfo.php) - this function extracts the URL in different parts
In your case it would be:
```
$path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);
$fileID = $path_parts['filename'];
```
Your update query will work, in case you only want to count without showing the new value, you could make it more simple - just increment HITS while updating the table row:
```
$query = mysqli->query("UPDATE tablename SET HITS = HITS+1 WHERE ID = $fileID");
``` |
22,345,614 | How can this be possible:
```
var string1 = "", string2 = "";
//comparing the charCode
console.log(string1.charCodeAt(0) === string2.charCodeAt(0)); //true
//comparing the character
console.log(string1 === string2.substring(0,1)); //false
//This is giving me a headache.
```
<http://jsfiddle.net/DerekL/B9Xdk/>
If their char codes are the same in both strings, by comparing the character itself should return `true`. It is true when I put in `a` and `ab`. But when I put in these strings, it simply breaks.
Some said that it might be the encoding that is causing the problem. But since it works perfectly fine when there's only one character in the string literal, I assume encoding has nothing to do with it.
(This question addresses the core problem in my previous questions. Don't worry I deleted them already.) | 2014/03/12 | [
"https://Stackoverflow.com/questions/22345614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283863/"
] | In JavaScript, strings are treated by characters instead of bytes, but only if they can be expressed in 16-bit code points.
A majority of the characters will cause no issues, but in this case they don't "fit" and so they occupy 2 characters as far as JavaScript is concerned.
In this case you need to do:
```
string2.substring(0, 2) // ""
```
For more information on Unicode quirkiness, see [UTF-8 Everywhere](http://utf8everywhere.org/). | You can use the method to compare 2 strings:
```
string1.localeCompare(string2);
``` |
22,345,614 | How can this be possible:
```
var string1 = "", string2 = "";
//comparing the charCode
console.log(string1.charCodeAt(0) === string2.charCodeAt(0)); //true
//comparing the character
console.log(string1 === string2.substring(0,1)); //false
//This is giving me a headache.
```
<http://jsfiddle.net/DerekL/B9Xdk/>
If their char codes are the same in both strings, by comparing the character itself should return `true`. It is true when I put in `a` and `ab`. But when I put in these strings, it simply breaks.
Some said that it might be the encoding that is causing the problem. But since it works perfectly fine when there's only one character in the string literal, I assume encoding has nothing to do with it.
(This question addresses the core problem in my previous questions. Don't worry I deleted them already.) | 2014/03/12 | [
"https://Stackoverflow.com/questions/22345614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283863/"
] | In JavaScript, strings are treated by characters instead of bytes, but only if they can be expressed in 16-bit code points.
A majority of the characters will cause no issues, but in this case they don't "fit" and so they occupy 2 characters as far as JavaScript is concerned.
In this case you need to do:
```
string2.substring(0, 2) // ""
```
For more information on Unicode quirkiness, see [UTF-8 Everywhere](http://utf8everywhere.org/). | Substring parameters are the index where he starts, and the end, where as if you change it to substr, the parameters are index where to start and how many characters. |
9,743,846 | I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.
I researched this a little bit already, and I found [this answer](https://stackoverflow.com/a/4863630/2486) to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.
What am I missing?
This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.
```
setTimeout("UpdateProgressBar();", 1000);
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
This is the UpdateProgressBar function:
```
function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;
$('#div_ProgressBar').progressbar("value", percentProcessed);
if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
**Edit**:
This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.
```
[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;
try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}
return pagesProcessed;
}
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | You can do it in a single thread.
Suppose you have a script that prints lines at random times:
```
#!/usr/bin/env python
#file: child.py
import os
import random
import sys
import time
for i in range(10):
print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i))
sys.stdout.flush()
time.sleep(random.random())
```
And you'd like to collect the output as soon as it becomes available, you could use [`select`](http://docs.python.org/dev/library/select#select.select) on POSIX systems as [@zigg suggested](https://stackoverflow.com/questions/9743838/python-subprocess-in-parallel/9746401#comment12393687_9743899):
```
#!/usr/bin/env python
from __future__ import print_function
from select import select
from subprocess import Popen, PIPE
# start several subprocesses
processes = [Popen(['./child.py', str(i)], stdout=PIPE,
bufsize=1, close_fds=True,
universal_newlines=True)
for i in range(5)]
# read output
timeout = 0.1 # seconds
while processes:
# remove finished processes from the list (O(N**2))
for p in processes[:]:
if p.poll() is not None: # process ended
print(p.stdout.read(), end='') # read the rest
p.stdout.close()
processes.remove(p)
# wait until there is something to read
rlist = select([p.stdout for p in processes], [],[], timeout)[0]
# read a line from each process that has output ready
for f in rlist:
print(f.readline(), end='') #NOTE: it can block
```
A more portable solution (that should work on Windows, Linux, OSX) can use reader threads for each process, see [Non-blocking read on a subprocess.PIPE in python](https://stackoverflow.com/q/375427/4279).
Here's [`os.pipe()`](http://docs.python.org/2/library/os#os.pipe)-based solution that works on Unix and Windows:
```
#!/usr/bin/env python
from __future__ import print_function
import io
import os
import sys
from subprocess import Popen
ON_POSIX = 'posix' in sys.builtin_module_names
# create a pipe to get data
input_fd, output_fd = os.pipe()
# start several subprocesses
processes = [Popen([sys.executable, 'child.py', str(i)], stdout=output_fd,
close_fds=ON_POSIX) # close input_fd in children
for i in range(5)]
os.close(output_fd) # close unused end of the pipe
# read output line by line as soon as it is available
with io.open(input_fd, 'r', buffering=1) as file:
for line in file:
print(line, end='')
#
for p in processes:
p.wait()
``` | You don't need to run a thread for each process. You can peek at the `stdout` streams for each process without blocking on them, and only read from them if they have data available to read.
You *do* have to be careful not to accidentally block on them, though, if you're not intending to. |
9,743,846 | I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.
I researched this a little bit already, and I found [this answer](https://stackoverflow.com/a/4863630/2486) to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.
What am I missing?
This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.
```
setTimeout("UpdateProgressBar();", 1000);
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
This is the UpdateProgressBar function:
```
function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;
$('#div_ProgressBar').progressbar("value", percentProcessed);
if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
**Edit**:
This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.
```
[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;
try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}
return pagesProcessed;
}
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | You can also collect stdout from multiple subprocesses concurrently using [`twisted`](http://twistedmatrix.com/trac/):
```
#!/usr/bin/env python
import sys
from twisted.internet import protocol, reactor
class ProcessProtocol(protocol.ProcessProtocol):
def outReceived(self, data):
print data, # received chunk of stdout from child
def processEnded(self, status):
global nprocesses
nprocesses -= 1
if nprocesses == 0: # all processes ended
reactor.stop()
# start subprocesses
nprocesses = 5
for _ in xrange(nprocesses):
reactor.spawnProcess(ProcessProtocol(), sys.executable,
args=[sys.executable, 'child.py'],
usePTY=True) # can change how child buffers stdout
reactor.run()
```
See [Using Processes in Twisted](http://twistedmatrix.com/documents/current/core/howto/process.html). | You don't need to run a thread for each process. You can peek at the `stdout` streams for each process without blocking on them, and only read from them if they have data available to read.
You *do* have to be careful not to accidentally block on them, though, if you're not intending to. |
9,743,846 | I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.
I researched this a little bit already, and I found [this answer](https://stackoverflow.com/a/4863630/2486) to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.
What am I missing?
This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.
```
setTimeout("UpdateProgressBar();", 1000);
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
This is the UpdateProgressBar function:
```
function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;
$('#div_ProgressBar').progressbar("value", percentProcessed);
if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
**Edit**:
This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.
```
[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;
try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}
return pagesProcessed;
}
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | You don't need to run a thread for each process. You can peek at the `stdout` streams for each process without blocking on them, and only read from them if they have data available to read.
You *do* have to be careful not to accidentally block on them, though, if you're not intending to. | You can wait for `process.poll()` to finish, and run other stuff concurrently:
```
import time
import sys
from subprocess import Popen, PIPE
def ex1() -> None:
command = 'sleep 2.1 && echo "happy friday"'
proc = Popen(command, shell=True, stderr=PIPE, stdout=PIPE)
while proc.poll() is None:
# do stuff here
print('waiting')
time.sleep(0.05)
out, _err = proc.communicate()
print(out, file=sys.stderr)
sys.stderr.flush()
assert proc.poll() == 0
ex1()
``` |
9,743,846 | I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.
I researched this a little bit already, and I found [this answer](https://stackoverflow.com/a/4863630/2486) to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.
What am I missing?
This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.
```
setTimeout("UpdateProgressBar();", 1000);
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
This is the UpdateProgressBar function:
```
function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;
$('#div_ProgressBar').progressbar("value", percentProcessed);
if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
**Edit**:
This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.
```
[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;
try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}
return pagesProcessed;
}
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | You can do it in a single thread.
Suppose you have a script that prints lines at random times:
```
#!/usr/bin/env python
#file: child.py
import os
import random
import sys
import time
for i in range(10):
print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i))
sys.stdout.flush()
time.sleep(random.random())
```
And you'd like to collect the output as soon as it becomes available, you could use [`select`](http://docs.python.org/dev/library/select#select.select) on POSIX systems as [@zigg suggested](https://stackoverflow.com/questions/9743838/python-subprocess-in-parallel/9746401#comment12393687_9743899):
```
#!/usr/bin/env python
from __future__ import print_function
from select import select
from subprocess import Popen, PIPE
# start several subprocesses
processes = [Popen(['./child.py', str(i)], stdout=PIPE,
bufsize=1, close_fds=True,
universal_newlines=True)
for i in range(5)]
# read output
timeout = 0.1 # seconds
while processes:
# remove finished processes from the list (O(N**2))
for p in processes[:]:
if p.poll() is not None: # process ended
print(p.stdout.read(), end='') # read the rest
p.stdout.close()
processes.remove(p)
# wait until there is something to read
rlist = select([p.stdout for p in processes], [],[], timeout)[0]
# read a line from each process that has output ready
for f in rlist:
print(f.readline(), end='') #NOTE: it can block
```
A more portable solution (that should work on Windows, Linux, OSX) can use reader threads for each process, see [Non-blocking read on a subprocess.PIPE in python](https://stackoverflow.com/q/375427/4279).
Here's [`os.pipe()`](http://docs.python.org/2/library/os#os.pipe)-based solution that works on Unix and Windows:
```
#!/usr/bin/env python
from __future__ import print_function
import io
import os
import sys
from subprocess import Popen
ON_POSIX = 'posix' in sys.builtin_module_names
# create a pipe to get data
input_fd, output_fd = os.pipe()
# start several subprocesses
processes = [Popen([sys.executable, 'child.py', str(i)], stdout=output_fd,
close_fds=ON_POSIX) # close input_fd in children
for i in range(5)]
os.close(output_fd) # close unused end of the pipe
# read output line by line as soon as it is available
with io.open(input_fd, 'r', buffering=1) as file:
for line in file:
print(line, end='')
#
for p in processes:
p.wait()
``` | You can also collect stdout from multiple subprocesses concurrently using [`twisted`](http://twistedmatrix.com/trac/):
```
#!/usr/bin/env python
import sys
from twisted.internet import protocol, reactor
class ProcessProtocol(protocol.ProcessProtocol):
def outReceived(self, data):
print data, # received chunk of stdout from child
def processEnded(self, status):
global nprocesses
nprocesses -= 1
if nprocesses == 0: # all processes ended
reactor.stop()
# start subprocesses
nprocesses = 5
for _ in xrange(nprocesses):
reactor.spawnProcess(ProcessProtocol(), sys.executable,
args=[sys.executable, 'child.py'],
usePTY=True) # can change how child buffers stdout
reactor.run()
```
See [Using Processes in Twisted](http://twistedmatrix.com/documents/current/core/howto/process.html). |
9,743,846 | I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.
I researched this a little bit already, and I found [this answer](https://stackoverflow.com/a/4863630/2486) to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.
What am I missing?
This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.
```
setTimeout("UpdateProgressBar();", 1000);
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
This is the UpdateProgressBar function:
```
function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;
$('#div_ProgressBar').progressbar("value", percentProcessed);
if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
**Edit**:
This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.
```
[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;
try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}
return pagesProcessed;
}
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | You can do it in a single thread.
Suppose you have a script that prints lines at random times:
```
#!/usr/bin/env python
#file: child.py
import os
import random
import sys
import time
for i in range(10):
print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i))
sys.stdout.flush()
time.sleep(random.random())
```
And you'd like to collect the output as soon as it becomes available, you could use [`select`](http://docs.python.org/dev/library/select#select.select) on POSIX systems as [@zigg suggested](https://stackoverflow.com/questions/9743838/python-subprocess-in-parallel/9746401#comment12393687_9743899):
```
#!/usr/bin/env python
from __future__ import print_function
from select import select
from subprocess import Popen, PIPE
# start several subprocesses
processes = [Popen(['./child.py', str(i)], stdout=PIPE,
bufsize=1, close_fds=True,
universal_newlines=True)
for i in range(5)]
# read output
timeout = 0.1 # seconds
while processes:
# remove finished processes from the list (O(N**2))
for p in processes[:]:
if p.poll() is not None: # process ended
print(p.stdout.read(), end='') # read the rest
p.stdout.close()
processes.remove(p)
# wait until there is something to read
rlist = select([p.stdout for p in processes], [],[], timeout)[0]
# read a line from each process that has output ready
for f in rlist:
print(f.readline(), end='') #NOTE: it can block
```
A more portable solution (that should work on Windows, Linux, OSX) can use reader threads for each process, see [Non-blocking read on a subprocess.PIPE in python](https://stackoverflow.com/q/375427/4279).
Here's [`os.pipe()`](http://docs.python.org/2/library/os#os.pipe)-based solution that works on Unix and Windows:
```
#!/usr/bin/env python
from __future__ import print_function
import io
import os
import sys
from subprocess import Popen
ON_POSIX = 'posix' in sys.builtin_module_names
# create a pipe to get data
input_fd, output_fd = os.pipe()
# start several subprocesses
processes = [Popen([sys.executable, 'child.py', str(i)], stdout=output_fd,
close_fds=ON_POSIX) # close input_fd in children
for i in range(5)]
os.close(output_fd) # close unused end of the pipe
# read output line by line as soon as it is available
with io.open(input_fd, 'r', buffering=1) as file:
for line in file:
print(line, end='')
#
for p in processes:
p.wait()
``` | You can wait for `process.poll()` to finish, and run other stuff concurrently:
```
import time
import sys
from subprocess import Popen, PIPE
def ex1() -> None:
command = 'sleep 2.1 && echo "happy friday"'
proc = Popen(command, shell=True, stderr=PIPE, stdout=PIPE)
while proc.poll() is None:
# do stuff here
print('waiting')
time.sleep(0.05)
out, _err = proc.communicate()
print(out, file=sys.stderr)
sys.stderr.flush()
assert proc.poll() == 0
ex1()
``` |
9,743,846 | I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.
I researched this a little bit already, and I found [this answer](https://stackoverflow.com/a/4863630/2486) to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.
What am I missing?
This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.
```
setTimeout("UpdateProgressBar();", 1000);
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
This is the UpdateProgressBar function:
```
function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;
$('#div_ProgressBar').progressbar("value", percentProcessed);
if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
**Edit**:
This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.
```
[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;
try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}
return pagesProcessed;
}
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | You can also collect stdout from multiple subprocesses concurrently using [`twisted`](http://twistedmatrix.com/trac/):
```
#!/usr/bin/env python
import sys
from twisted.internet import protocol, reactor
class ProcessProtocol(protocol.ProcessProtocol):
def outReceived(self, data):
print data, # received chunk of stdout from child
def processEnded(self, status):
global nprocesses
nprocesses -= 1
if nprocesses == 0: # all processes ended
reactor.stop()
# start subprocesses
nprocesses = 5
for _ in xrange(nprocesses):
reactor.spawnProcess(ProcessProtocol(), sys.executable,
args=[sys.executable, 'child.py'],
usePTY=True) # can change how child buffers stdout
reactor.run()
```
See [Using Processes in Twisted](http://twistedmatrix.com/documents/current/core/howto/process.html). | You can wait for `process.poll()` to finish, and run other stuff concurrently:
```
import time
import sys
from subprocess import Popen, PIPE
def ex1() -> None:
command = 'sleep 2.1 && echo "happy friday"'
proc = Popen(command, shell=True, stderr=PIPE, stdout=PIPE)
while proc.poll() is None:
# do stuff here
print('waiting')
time.sleep(0.05)
out, _err = proc.communicate()
print(out, file=sys.stderr)
sys.stderr.flush()
assert proc.poll() == 0
ex1()
``` |
22,312,325 | I have a set of 8 buttons in a horizontal row. How can i make them like the buttons in [www.dotacinema.com](http://www.dotacinema.com) where when you smaller the window the buttons go together too (or zoom in, the buttons are still visible)
Thanks
EDIT:
```
height: 38px;
float: left;
min-width: 60px;
max-width: 140px;
display: inline-block;
width: 12.5%;
background-image: url(button.jpg);
background-size: 100%;
color: white;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
color: #d0d0d0;
border: outset #555 1.5px;
cursor: pointer;
text-align: center;
font-size: 16px;
```
does not make the buttons squish together for some reason. Pls help. | 2014/03/10 | [
"https://Stackoverflow.com/questions/22312325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2881151/"
] | Make the width of the buttons a percentage of the page, and then set a minimum button width using `min-width: ;` to stop them getting any smaller than readable.
<http://jsfiddle.net/s2VvX/3/> | What they did on the site you provided is change the `ul` into a table using CSS, where each `li` is a table-cell which causes it to automatically adjust the width of the `li`s to fill the `ul`.
You can find out more by using the [Chrome Developer Tools](https://developers.google.com/chrome-developer-tools/).
Note that it's also possible using `text-align: justify`, which is demonstrated here: <http://jsfiddle.net/2kRJv/> |
65,229,771 | After working with the tensorflow's example tutorial on colab: Basic regression: Predict fuel efficiency, which can be found here: <https://www.tensorflow.org/tutorials/keras/regression>.
I've been trying to run this example on jupyter notebook via anaconda in order to be able to run it offline too.
The code that one can find on the link works fine on google colab, but when I try to run it on jupyter notebook I get a vector of nan's.
1. A run on google colab yields:
[Running the example on google colab](https://i.stack.imgur.com/wvafS.png)
2. A run on jupyter yields:
[Running the example on jupyter lab](https://i.stack.imgur.com/BvRkU.png)
**The code for building the sequential model: [where the problem might come from]**
```
horsepower_model = tf.keras.Sequential([
horsepower_normalizer,
layers.Dense(units=1)
])
horsepower_model.summary()
```
**The rest of the code can be found in this link that I have attached above:**
<https://www.tensorflow.org/tutorials/keras/regression>
**What the model has to do:**
This model takes 2 arrays from a dataset: MPG and Horsepower, and is about to use single-variable linear regression in order to predict MPG from Horsepower.
Therefore, the model is introduce a Dense layer with shape of 1 as one can see from here:
```
layers.Dense(units=1)
```
The output of the model should be the values of the MPG, based on the horsepower values.
Then we will be able to compare it with the values of the real MPG that we've got from the dataset.
Thank you in advance.
**EDIT: I upload my notebook:**
<https://www.udrop.com/Jk3/Horsepower.ipynb> | 2020/12/10 | [
"https://Stackoverflow.com/questions/65229771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14799022/"
] | I see you are using different models in them.
In **Colab** you have used model having only **5** parameters
whereas in **Notebook** you are using a dense model having **944** parameters.
**Try running the model with less parameter on notebook first**
or
Try running the same model on both.(Maybe the complex model was not trained completely.)
**EDIT 1:**
I have created a jupyter notebook and tried the code.
In my system it is working fine, try running this jupyter notebook in your system. [Jupyter Notebook](https://drive.google.com/file/d/1dDiJZ7LAsR5x3bz1Y-7EetTwWX2mXEjG/view?usp=sharing)
. If it works then maybe there is some syntax error in your code.
**EDIT 2:**
Update tensorflow:
```
pip install --ignore-installed --upgrade tensorflow
```
use this or any other command that works on your version. | Putting an extra set of brackets around each horsepower value fixes the issue for me:
```
horsepower = np.array([[h] for h in train_features['Horsepower']])
``` |
38,408,974 | I'm new in swift-ios. I'm studying [this](https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/)
when I'm trying to create cocoa file,
>
> import cocoa
>
>
>
is giving error.
I've searched in google and found cocoa class not work in ios-swift. it works in osx.
So I'm not getting what'll I do now. Any help appreciated. | 2016/07/16 | [
"https://Stackoverflow.com/questions/38408974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2007490/"
] | Cocoa is a framework for macOS. However, CocoaTouch is an umbrella module for iOS. To import the main module dependency for an iOS app, you use
```
import Foundation
```
And to import the main UI module for an iOS app, you use
```
import UIKit
``` | The term “Cocoa” has been used to refer generically to any class or object that is based on the Objective-C runtime and inherits from the root class, NSObject. |
50,621,187 | I need to click a button whose xpath is "**//input[contains(@value,'Export to Excel')]**" through **Execute Javascript** keyword. I don't know how to use it.
Can anyone help me out!!! | 2018/05/31 | [
"https://Stackoverflow.com/questions/50621187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9667509/"
] | You can write it as below
```
Execute JavaScript document.evaluate("ur xpath",document.body,null,9,null).singleNodeValue.click();
``` | The solution I found out for this problem is I have **reloaded the page** after **executing the AutoIT** script, then I was able to execute the remaining code. |
1,038,189 | which one of the 2 have the best performance?
In javascript I was heard douglas crockford say that you shouldn't use str += if you are concatenating a large string but use array.push instead.
I've seen lots of code where developers use $str .= to concatenate a large string in PHP as well, but since "everything" in PHP is based on arrays (try dumping an object), my thought was that the same rule applies for PHP.
Can anyone confirm this? | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117278/"
] | `.=` is for strings.
[`array_push()`](http://us2.php.net/manual/en/function.array-push.php) is for arrays.
They aren't the same thing in PHP. Using one on the other will generate an error. | array\_push() won't work for appending to a string in PHP, because PHP strings aren't really arrays (like you'd see them in C or JavaScript). |
1,038,189 | which one of the 2 have the best performance?
In javascript I was heard douglas crockford say that you shouldn't use str += if you are concatenating a large string but use array.push instead.
I've seen lots of code where developers use $str .= to concatenate a large string in PHP as well, but since "everything" in PHP is based on arrays (try dumping an object), my thought was that the same rule applies for PHP.
Can anyone confirm this? | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117278/"
] | Strings are mutable in PHP so using .= does not have the same affect in php as using += in javascript. That is, you will not not end up with two different strings every time you use the operator.
See:
[php String Concatenation, Performance](https://stackoverflow.com/questions/124067/php-string-concatenation-performance)
[Are php strings immutable?](https://stackoverflow.com/questions/496669/are-php-strings-immutable) | array\_push() won't work for appending to a string in PHP, because PHP strings aren't really arrays (like you'd see them in C or JavaScript). |
1,038,189 | which one of the 2 have the best performance?
In javascript I was heard douglas crockford say that you shouldn't use str += if you are concatenating a large string but use array.push instead.
I've seen lots of code where developers use $str .= to concatenate a large string in PHP as well, but since "everything" in PHP is based on arrays (try dumping an object), my thought was that the same rule applies for PHP.
Can anyone confirm this? | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117278/"
] | Strings are mutable in PHP so using .= does not have the same affect in php as using += in javascript. That is, you will not not end up with two different strings every time you use the operator.
See:
[php String Concatenation, Performance](https://stackoverflow.com/questions/124067/php-string-concatenation-performance)
[Are php strings immutable?](https://stackoverflow.com/questions/496669/are-php-strings-immutable) | `.=` is for strings.
[`array_push()`](http://us2.php.net/manual/en/function.array-push.php) is for arrays.
They aren't the same thing in PHP. Using one on the other will generate an error. |
61,339,388 | I have two tables t1 & t2. In t1, there are 1641787 records. In t2, there are 33176007 records. I want to take two columns from t2 and keep everything of t1 using a left join. When I use left join with t1 to t2, I got more records than t1. I would like to get a similar number of records as t1 after joining. Please give me a suggestion. There are many to many relationships between the tables. Here is my code:
```
SELECT t1.*, t2.City
FROM t1 LEFT JOIN t2 ON t1.ID = t2.ID;
``` | 2020/04/21 | [
"https://Stackoverflow.com/questions/61339388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5846329/"
] | You need to aggregate `t2` *before* joining:
```
SELECT t1.*, t2.City
FROM t1 LEFT JOIN
(SELECT t2.ID, ANY_VALUE(t2.City) as City
FROM t2
GROUP BY t2.ID)
) t2
ON t1.ID = t2.ID;
``` | "select **destinct** ..."
add a "order by"
Like this:
```
SELECT DESTINCT t1.*, t2.City
FROM t1 LEFT JOIN t2 ON t1.ID = t2.ID
ORDER BY t1.name ASC;
``` |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | One more tip on top of what everyone already said, make sure the pens and brushes are frozen - if you create the brush call Freeze before using it (brushes from the Brushes class (Brushes.White) are already frozen). | The bitmap approach might speed up more - BitmapSource has a Create method that takes raw data either as an array or a pointer to unsafe memory.
It should be a bit faster to set values in an array than drawing actual rectangles - however you have to checkout the pixelformats to set the individual pixels correctly. |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | One more tip on top of what everyone already said, make sure the pens and brushes are frozen - if you create the brush call Freeze before using it (brushes from the Brushes class (Brushes.White) are already frozen). | Perhaps try overlaying the canvas with a VisualBrush.
To this visualBrush simply add the 4\*4 rectangle and have it repeat in a tile mode. Alternatively you could just add the lines to it so that it doesnt overlap the edges of the rectangle... your choice :)
Your problem is in the creation of the brush... A test run indicated that this code
```
int limit = 10000 * 10000;
var converter = new BrushConverter();
for (int i = 0; i < limit; i++)
{
var blueBrush = converter.ConvertFromString("Blue") as Brush;
}
```
took 53 seconds to run. You are trying to create 100,000,000 brushes :) If it is patternable, use a patterned visual brush, if it is not patternable... perhapse look for another solution. The overhead of storing that many brushes in memory is in the Gigabytes |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | You should try StreamGeometry then.
<http://msdn.microsoft.com/en-us/library/system.windows.media.streamgeometry.aspx>
>
> For complex geometries that don’t need
> to be modified after they are created,
> you should consider using
> StreamGeometry rather than
> PathGeometry as a performance
> optimization. StreamGeometry works
> like PathGeometry, except that it can
> only be filled via procedural code.
> Its odd name refers to an
> implementation detail: To use less
> memory (and less of the CPU), its
> PathFigures and PathSegments are
> stored as a compact byte stream rather
> than a graph of .NET objects.
>
>
>
Quoted from Adam Nathan's book WPF Unleashed. | The bitmap approach might speed up more - BitmapSource has a Create method that takes raw data either as an array or a pointer to unsafe memory.
It should be a bit faster to set values in an array than drawing actual rectangles - however you have to checkout the pixelformats to set the individual pixels correctly. |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | You don't need to recreate the brush for each iteration of the loop, since they use the same color over and over:
```
SolidColorBrush blueBrush = new SolidColorBrush(Colors.Blue)
SolidColorPen bluePen = new SolidColorPen(blueBrush)
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(blueBrush, bluePen, 1), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
```
This may speed up the loop a bit. | Perhaps try overlaying the canvas with a VisualBrush.
To this visualBrush simply add the 4\*4 rectangle and have it repeat in a tile mode. Alternatively you could just add the lines to it so that it doesnt overlap the edges of the rectangle... your choice :)
Your problem is in the creation of the brush... A test run indicated that this code
```
int limit = 10000 * 10000;
var converter = new BrushConverter();
for (int i = 0; i < limit; i++)
{
var blueBrush = converter.ConvertFromString("Blue") as Brush;
}
```
took 53 seconds to run. You are trying to create 100,000,000 brushes :) If it is patternable, use a patterned visual brush, if it is not patternable... perhapse look for another solution. The overhead of storing that many brushes in memory is in the Gigabytes |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | You should try StreamGeometry then.
<http://msdn.microsoft.com/en-us/library/system.windows.media.streamgeometry.aspx>
>
> For complex geometries that don’t need
> to be modified after they are created,
> you should consider using
> StreamGeometry rather than
> PathGeometry as a performance
> optimization. StreamGeometry works
> like PathGeometry, except that it can
> only be filled via procedural code.
> Its odd name refers to an
> implementation detail: To use less
> memory (and less of the CPU), its
> PathFigures and PathSegments are
> stored as a compact byte stream rather
> than a graph of .NET objects.
>
>
>
Quoted from Adam Nathan's book WPF Unleashed. | Perhaps try overlaying the canvas with a VisualBrush.
To this visualBrush simply add the 4\*4 rectangle and have it repeat in a tile mode. Alternatively you could just add the lines to it so that it doesnt overlap the edges of the rectangle... your choice :)
Your problem is in the creation of the brush... A test run indicated that this code
```
int limit = 10000 * 10000;
var converter = new BrushConverter();
for (int i = 0; i < limit; i++)
{
var blueBrush = converter.ConvertFromString("Blue") as Brush;
}
```
took 53 seconds to run. You are trying to create 100,000,000 brushes :) If it is patternable, use a patterned visual brush, if it is not patternable... perhapse look for another solution. The overhead of storing that many brushes in memory is in the Gigabytes |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | >
> The purpose is to draw 10000\*10000
> rectangles of size 4 pixels each.
>
>
>
Do NOT draw them. That simple. This would be 40k to 40k pixels.
Most will not be visible. So they must not bee drawn. Basically only draw those that are visible in the canvas. When resizing or scrolling you repaint anyway, then do the same - only draw those that are visible.
Virtualization is the key to performance here. Take things out of the drawing loop as early as possible. Stuff not visible per definition does not need to be drawn at all.
Next alternative would be not to use a canvas. Try a bitmap. Prepare it on a separate thread, then draw this one at once. | You should try StreamGeometry then.
<http://msdn.microsoft.com/en-us/library/system.windows.media.streamgeometry.aspx>
>
> For complex geometries that don’t need
> to be modified after they are created,
> you should consider using
> StreamGeometry rather than
> PathGeometry as a performance
> optimization. StreamGeometry works
> like PathGeometry, except that it can
> only be filled via procedural code.
> Its odd name refers to an
> implementation detail: To use less
> memory (and less of the CPU), its
> PathFigures and PathSegments are
> stored as a compact byte stream rather
> than a graph of .NET objects.
>
>
>
Quoted from Adam Nathan's book WPF Unleashed. |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | >
> The purpose is to draw 10000\*10000
> rectangles of size 4 pixels each.
>
>
>
Do NOT draw them. That simple. This would be 40k to 40k pixels.
Most will not be visible. So they must not bee drawn. Basically only draw those that are visible in the canvas. When resizing or scrolling you repaint anyway, then do the same - only draw those that are visible.
Virtualization is the key to performance here. Take things out of the drawing loop as early as possible. Stuff not visible per definition does not need to be drawn at all.
Next alternative would be not to use a canvas. Try a bitmap. Prepare it on a separate thread, then draw this one at once. | You don't need to recreate the brush for each iteration of the loop, since they use the same color over and over:
```
SolidColorBrush blueBrush = new SolidColorBrush(Colors.Blue)
SolidColorPen bluePen = new SolidColorPen(blueBrush)
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(blueBrush, bluePen, 1), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
```
This may speed up the loop a bit. |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | >
> The purpose is to draw 10000\*10000
> rectangles of size 4 pixels each.
>
>
>
Do NOT draw them. That simple. This would be 40k to 40k pixels.
Most will not be visible. So they must not bee drawn. Basically only draw those that are visible in the canvas. When resizing or scrolling you repaint anyway, then do the same - only draw those that are visible.
Virtualization is the key to performance here. Take things out of the drawing loop as early as possible. Stuff not visible per definition does not need to be drawn at all.
Next alternative would be not to use a canvas. Try a bitmap. Prepare it on a separate thread, then draw this one at once. | The bitmap approach might speed up more - BitmapSource has a Create method that takes raw data either as an array or a pointer to unsafe memory.
It should be a bit faster to set values in an array than drawing actual rectangles - however you have to checkout the pixelformats to set the individual pixels correctly. |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | The bitmap approach might speed up more - BitmapSource has a Create method that takes raw data either as an array or a pointer to unsafe memory.
It should be a bit faster to set values in an array than drawing actual rectangles - however you have to checkout the pixelformats to set the individual pixels correctly. | Perhaps try overlaying the canvas with a VisualBrush.
To this visualBrush simply add the 4\*4 rectangle and have it repeat in a tile mode. Alternatively you could just add the lines to it so that it doesnt overlap the edges of the rectangle... your choice :)
Your problem is in the creation of the brush... A test run indicated that this code
```
int limit = 10000 * 10000;
var converter = new BrushConverter();
for (int i = 0; i < limit; i++)
{
var blueBrush = converter.ConvertFromString("Blue") as Brush;
}
```
took 53 seconds to run. You are trying to create 100,000,000 brushes :) If it is patternable, use a patterned visual brush, if it is not patternable... perhapse look for another solution. The overhead of storing that many brushes in memory is in the Gigabytes |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | You don't need to recreate the brush for each iteration of the loop, since they use the same color over and over:
```
SolidColorBrush blueBrush = new SolidColorBrush(Colors.Blue)
SolidColorPen bluePen = new SolidColorPen(blueBrush)
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(blueBrush, bluePen, 1), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
```
This may speed up the loop a bit. | The bitmap approach might speed up more - BitmapSource has a Create method that takes raw data either as an array or a pointer to unsafe memory.
It should be a bit faster to set values in an array than drawing actual rectangles - however you have to checkout the pixelformats to set the individual pixels correctly. |