qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
53,473,475
What does `_` mean in this example code: ``` if (_(abc.content).has("abc")){ console.log("abc found"); } ``` Many people say "\_" means a private member, but if `abc` or `content` is a private member, shouldn't we use `_abc.content` or `abc._content`? Thank you
2018/11/26
['https://Stackoverflow.com/questions/53473475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7025179/']
For that to be valid, `_` must refer to a *function*. Perhaps the script is using [`underscore`](https://underscorejs.org/#has), in which case `_(abc.content).has("abc")` returns a Boolean - `true` if the `abc.content` object has a *key* of `abc`, and `false` otherwise: ```js const abc = { content: { key1: 'foo', abc: 'bar' } }; if (_(abc.content).has("abc")){ console.log("abc found"); } console.log(_(abc.content).has("keyThatDoesNotExist")) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> ``` It probably has nothing to do with private properties, because `_` is a *standalone* function. The library used might also be lodash: ```js const abc = { content: { key1: 'foo', abc: 'bar' } }; if (_(abc.content).has("abc")){ console.log("abc found"); } console.log(_(abc.content).has("keyThatDoesNotExist")) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script> ``` But to be sure, you'll have to examine `_` - `console.log` it, or see where it's defined, to get some idea.
\_ is a valid variable name in JavaScript and can be used in any way you want just like i, a, x, length, time, date or any other variable name you can come up with. Personally I usually use underscore as a variable in a function parameter list when I wont be using that variable in the function body. ``` const func = (_) => { // _ is not used in the function body }; ``` ```js const _ = () => { console.log('Hello from underscore!'); }; _(); ```
53,473,475
What does `_` mean in this example code: ``` if (_(abc.content).has("abc")){ console.log("abc found"); } ``` Many people say "\_" means a private member, but if `abc` or `content` is a private member, shouldn't we use `_abc.content` or `abc._content`? Thank you
2018/11/26
['https://Stackoverflow.com/questions/53473475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7025179/']
That's just a variable name. You are right, conventions suggest that underscore refer to private members in an object such as: ``` const num = 2; function Multiply(num) { this._multiplier = 2; this._input = num; this.start = function(){ return this._multiplier * this._input; } } const product = new Multiply(num).start(); //4 ``` But the concept of private members has nothing to do with your example. In your case, `_()` is actually a function; ``` function _ (){ return "I love potatoes"; } ``` a function that returns an object that contains the `.has()` method. The structure of that function of yours could be dumbed down to something like ``` function _(args){ const content = args; return { has: function(data){ //do something return true; //some boolean expression } } } ```
\_ is a valid variable name in JavaScript and can be used in any way you want just like i, a, x, length, time, date or any other variable name you can come up with. Personally I usually use underscore as a variable in a function parameter list when I wont be using that variable in the function body. ``` const func = (_) => { // _ is not used in the function body }; ``` ```js const _ = () => { console.log('Hello from underscore!'); }; _(); ```
36,599,890
The below code is written in swift class ``` override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { dim(.In, alpha: dimLevel, speed: dimSpeed) } @IBAction func unwindFromEditAboutUs(segue: UIStoryboardSegue) { dim(.Out, speed:dimSpeed) } ``` I want to call this class functions from my objective C class.... plz. suggest me how can I do this...
2016/04/13
['https://Stackoverflow.com/questions/36599890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5680983/']
Simply import swift class in objective C Project ``` #import"ProjectName-Swift.h" ```
You should make bridge to do this kind of stuff. [Refer this link](https://stackoverflow.com/questions/24078043/call-swift-function-from-objective-c-class) or [this link](http://ericasadun.com/2014/08/21/swift-calling-swift-functions-from-objective-c/) and this [apple documentation](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html). Hope this will help you :)
17,375,379
I trying to build an app with 4 tabs. Every tab has a different fragment linked to it. The issue is that I want to make a custom listView for each fragment, but it ends with some unsolvable error... I have talked to other developers, but I still can't make one that works! It's really frustrating! **I have:** * A MainActivity class that works, it uses swipe-able tabs * An XML with the design I want on my custom ListView. * An XML called fragment1 with a ListView. **These are normal errors I get:** * "The method findViewById(int) is undefined for the type Fragment1UG" * "The method setContentView(int) is undefined for the type Fragment1UG. 1 quick fix available: Create method 'setContentView()'" One of the guides I'm trying to understand and use: * [Android ListView Tutorial](http://javatechig.com/android/android-listview-tutorial/#3_Building_ListViewusing_Custom_Adapter) * [Android ListFragment Tutorial](http://www.vogella.com/articles/AndroidListView/article.html) This is my 1st fragment: ``` import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class Fragment1test extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //This layout contains your list view View view = inflater.inflate(R.layout.fragment1, container, false); //now you must initialize your list view ListView yourListView = (ListView)view.findViewById(R.id.ListView1); ListView.setAdapter(new ListAdapter()); return view; } } ``` My ListAdapter.java code (from a tutorial): ``` import java.util.List; import android.content.ClipData.Item; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ListAdapter extends ArrayAdapter<Item> { public ListAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); // TODO Auto-generated constructor stub } private List<Item> items; public ListAdapter(Context context, int resource, List<Item> items) { super(context, resource, items); this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.list_design, null); } Item p = items.get(position); if (p != null) { TextView tt = (TextView) v.findViewById(R.id.game_txtTitle); TextView tt1 = (TextView) v.findViewById(R.id.game_txtRelease); TextView tt3 = (TextView) v.findViewById(R.id.game_txtPlatform); if (tt != null) { tt.setText(p.getId()); } if (tt1 != null) { tt1.setText(p.getCategory().getId()); } if (tt3 != null) { tt3.setText(p.getDescription()); } } ```
2013/06/29
['https://Stackoverflow.com/questions/17375379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2533633/']
``` public class Fragment1test extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //This layout contains your list view View view = inflater.inflate(R.layout.fragment_basic, container, false); //now you must initialize your list view ListView listview =(ListView)view.findViewById(R.id.your_listview); //EDITED Code String[] items = new String[] {"Item 1", "Item 2", "Item 3"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items); listview.setAdapter(adapter); //To have custom list view use this : you must define CustomeAdapter class // listview.setadapter(new CustomeAdapter(getActivity())); //getActivty is used instead of Context return view; } } ``` Refer [this link](http://sogacity.com/how-to-make-a-custom-arrayadapter-for-listview/) & [question](https://stackoverflow.com/a/8166802/1450401) to know how to create custom adapter Note : do not use List fragment or List activity to create custom listview EDIT ``` ListView yourListView = (ListView)view.findViewById(R.id.ListView1); //Here items must be a List<Items> according to your class instead of String[] array ListAdapter listadapter = new ListAdapter(getActivity(), android.R.layout.simple_list_item_1, items) ListView.setAdapter( listAdapter); ```
Fragments don't use `setContentView(int)`, so you can't use that, use the `inflater` in `public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)` and return the view inflated. As for `findViewById(int)` do it like this `getActivity().findViewById(int)`.
17,375,379
I trying to build an app with 4 tabs. Every tab has a different fragment linked to it. The issue is that I want to make a custom listView for each fragment, but it ends with some unsolvable error... I have talked to other developers, but I still can't make one that works! It's really frustrating! **I have:** * A MainActivity class that works, it uses swipe-able tabs * An XML with the design I want on my custom ListView. * An XML called fragment1 with a ListView. **These are normal errors I get:** * "The method findViewById(int) is undefined for the type Fragment1UG" * "The method setContentView(int) is undefined for the type Fragment1UG. 1 quick fix available: Create method 'setContentView()'" One of the guides I'm trying to understand and use: * [Android ListView Tutorial](http://javatechig.com/android/android-listview-tutorial/#3_Building_ListViewusing_Custom_Adapter) * [Android ListFragment Tutorial](http://www.vogella.com/articles/AndroidListView/article.html) This is my 1st fragment: ``` import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class Fragment1test extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //This layout contains your list view View view = inflater.inflate(R.layout.fragment1, container, false); //now you must initialize your list view ListView yourListView = (ListView)view.findViewById(R.id.ListView1); ListView.setAdapter(new ListAdapter()); return view; } } ``` My ListAdapter.java code (from a tutorial): ``` import java.util.List; import android.content.ClipData.Item; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ListAdapter extends ArrayAdapter<Item> { public ListAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); // TODO Auto-generated constructor stub } private List<Item> items; public ListAdapter(Context context, int resource, List<Item> items) { super(context, resource, items); this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.list_design, null); } Item p = items.get(position); if (p != null) { TextView tt = (TextView) v.findViewById(R.id.game_txtTitle); TextView tt1 = (TextView) v.findViewById(R.id.game_txtRelease); TextView tt3 = (TextView) v.findViewById(R.id.game_txtPlatform); if (tt != null) { tt.setText(p.getId()); } if (tt1 != null) { tt1.setText(p.getCategory().getId()); } if (tt3 != null) { tt3.setText(p.getDescription()); } } ```
2013/06/29
['https://Stackoverflow.com/questions/17375379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2533633/']
``` public class fragmentpassword extends Fragment { String[] name={"A","B","C","D"}; int [] image={R.drawable.ic_drawer,R.drawable.ic_drawer,R.drawable.ic_drawer,R.drawable.ic_drawer}; public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.layoutpassword, container, false); ListView li=(ListView)v.findViewById(R.id.listViewPassword); li.setAdapter(new PasswordAdapter(getActivity(),R.layout.passwordlay,name)); return v; } class PasswordAdapter extends ArrayAdapter { public PasswordAdapter(Context context, int resource, String[] objects) { super(context, resource, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v=((Activity)getContext()).getLayoutInflater().inflate(R.layout.passwordlay,null); TextView txt1 = (TextView) v.findViewById(R.id.textViewpasslay); txt1.setText(name[position]); ImageView img = (ImageView) v.findViewById(R.id.imageViewpasslay); img.setBackgroundResource(image[position]); return v; } } } **XML for customlist: passwordlay.xml** <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageViewpasslay" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Medium Text" android:id="@+id/textViewpasslay"/> </LinearLayout> **XML for fragment: layoutpassword.xml** <?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"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listViewPassword"/> </LinearLayout> ```
Fragments don't use `setContentView(int)`, so you can't use that, use the `inflater` in `public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)` and return the view inflated. As for `findViewById(int)` do it like this `getActivity().findViewById(int)`.
17,375,379
I trying to build an app with 4 tabs. Every tab has a different fragment linked to it. The issue is that I want to make a custom listView for each fragment, but it ends with some unsolvable error... I have talked to other developers, but I still can't make one that works! It's really frustrating! **I have:** * A MainActivity class that works, it uses swipe-able tabs * An XML with the design I want on my custom ListView. * An XML called fragment1 with a ListView. **These are normal errors I get:** * "The method findViewById(int) is undefined for the type Fragment1UG" * "The method setContentView(int) is undefined for the type Fragment1UG. 1 quick fix available: Create method 'setContentView()'" One of the guides I'm trying to understand and use: * [Android ListView Tutorial](http://javatechig.com/android/android-listview-tutorial/#3_Building_ListViewusing_Custom_Adapter) * [Android ListFragment Tutorial](http://www.vogella.com/articles/AndroidListView/article.html) This is my 1st fragment: ``` import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class Fragment1test extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //This layout contains your list view View view = inflater.inflate(R.layout.fragment1, container, false); //now you must initialize your list view ListView yourListView = (ListView)view.findViewById(R.id.ListView1); ListView.setAdapter(new ListAdapter()); return view; } } ``` My ListAdapter.java code (from a tutorial): ``` import java.util.List; import android.content.ClipData.Item; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ListAdapter extends ArrayAdapter<Item> { public ListAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); // TODO Auto-generated constructor stub } private List<Item> items; public ListAdapter(Context context, int resource, List<Item> items) { super(context, resource, items); this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.list_design, null); } Item p = items.get(position); if (p != null) { TextView tt = (TextView) v.findViewById(R.id.game_txtTitle); TextView tt1 = (TextView) v.findViewById(R.id.game_txtRelease); TextView tt3 = (TextView) v.findViewById(R.id.game_txtPlatform); if (tt != null) { tt.setText(p.getId()); } if (tt1 != null) { tt1.setText(p.getCategory().getId()); } if (tt3 != null) { tt3.setText(p.getDescription()); } } ```
2013/06/29
['https://Stackoverflow.com/questions/17375379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2533633/']
``` public class Fragment1test extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //This layout contains your list view View view = inflater.inflate(R.layout.fragment_basic, container, false); //now you must initialize your list view ListView listview =(ListView)view.findViewById(R.id.your_listview); //EDITED Code String[] items = new String[] {"Item 1", "Item 2", "Item 3"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items); listview.setAdapter(adapter); //To have custom list view use this : you must define CustomeAdapter class // listview.setadapter(new CustomeAdapter(getActivity())); //getActivty is used instead of Context return view; } } ``` Refer [this link](http://sogacity.com/how-to-make-a-custom-arrayadapter-for-listview/) & [question](https://stackoverflow.com/a/8166802/1450401) to know how to create custom adapter Note : do not use List fragment or List activity to create custom listview EDIT ``` ListView yourListView = (ListView)view.findViewById(R.id.ListView1); //Here items must be a List<Items> according to your class instead of String[] array ListAdapter listadapter = new ListAdapter(getActivity(), android.R.layout.simple_list_item_1, items) ListView.setAdapter( listAdapter); ```
``` public class fragmentpassword extends Fragment { String[] name={"A","B","C","D"}; int [] image={R.drawable.ic_drawer,R.drawable.ic_drawer,R.drawable.ic_drawer,R.drawable.ic_drawer}; public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.layoutpassword, container, false); ListView li=(ListView)v.findViewById(R.id.listViewPassword); li.setAdapter(new PasswordAdapter(getActivity(),R.layout.passwordlay,name)); return v; } class PasswordAdapter extends ArrayAdapter { public PasswordAdapter(Context context, int resource, String[] objects) { super(context, resource, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v=((Activity)getContext()).getLayoutInflater().inflate(R.layout.passwordlay,null); TextView txt1 = (TextView) v.findViewById(R.id.textViewpasslay); txt1.setText(name[position]); ImageView img = (ImageView) v.findViewById(R.id.imageViewpasslay); img.setBackgroundResource(image[position]); return v; } } } **XML for customlist: passwordlay.xml** <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageViewpasslay" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Medium Text" android:id="@+id/textViewpasslay"/> </LinearLayout> **XML for fragment: layoutpassword.xml** <?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"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listViewPassword"/> </LinearLayout> ```
80,120
Can we use multi element wing for slow flight planes, like F1 multi element rear wing? **If we know that pressure act prependicular to the surface why this two upper elements are "almost" vertical?** **It seems to me that they produce "tons" of drag instead lift.Resultant force point to far back,instead down!** [![enter image description here](https://i.stack.imgur.com/3ooHs.png)](https://i.stack.imgur.com/3ooHs.png) [![enter image description here](https://i.stack.imgur.com/6D1T2.jpg)](https://i.stack.imgur.com/6D1T2.jpg) [![enter image description here](https://i.stack.imgur.com/YSUpm.png)](https://i.stack.imgur.com/YSUpm.png)
2020/08/06
['https://aviation.stackexchange.com/questions/80120', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/-1/']
Excellent application inverted on the drag racer, which brings home the point perfectly. If you have enough excess thrust, devices like these can dramaticly increase Coefficient of Lift, but at the cost if loss of lift efficiency, or lower lift to drag ratio. In the case of the dragster, more propulsion efficiency is lost if tires break loose from the pavement, so the drag of the "inverted Fowler flap" is an acceptable trade-off to the **downlift** increasing traction. As mentioned in comments, this is why the Fiesler Storch requires 240 HP to achieve its legendary STOL performance. And just as flaps 10 is better for lift than flaps 30 for taking off, one might question the need for the second and third flap on a lifting wing, but heavy airliners love them when coming in to land as Fowler flaps.
This looks very much like a Formula Student/Formula SAE wing! The idea of the multi-element wing is for all three elements to act together, rather than as seperate sections. If you look at all of the elements joined together (imagine there are no slot gaps), the suction surface should form a constant curve\* which is informally known as the camber line. The unified camber line produces would produce a huge amount of load if the flow could stay attached to it. Unfortunately it is far too aggressive for the flow to stay attached. By splitting the section into multiple small sections, the boundary layer that has lost a lot of energy are shed, and a new higher energy boundary layer is started. The last part of the first element, and then each element after it are there to "recover" pressure from the suction peak that should be on the first element where the ground clearance is at a minimum. Therefore the peak (negative) Pressure Coefficient on subsequent elements should always be getting smaller (closer to zero). Note on the third CFD picture, the cutaway 3D wing, there is a pressure spike on the suction surface of the second element that is higher (more suction) than the first element. This means that the first element is not working hard enough, and needs more camber, and the slot gap needs more overlap so that the suction peak on the second element increases the dumping velocity of the first element. Unfortunately the first design is badly separated on the second and third elements. This is very commonly done by Formula Student Engineers, who chase headline numbers, rather than designing an efficient aero package. For using a multi-element wing for slow flight airplanes, unfortunately these aggressive designs create lots of load, but also lots of drag. For an F1 car, the drag polar can be anywhere between 3.5 and 5 depending on the configuration. FS/FSAE designs like you have shown are going to have drag polars are in the range of 5~10 for a front wing with the benefit of in-ground effects, and down to 2 for a rear wing! There is a fantastic paper called **High-Lift Aerodynamics by A. M. O. Smith which I highly recommend** you take a look at. It takes you through all of the theory and examples of how and why multi-element wings work. \* The curve should actually have small steps in it to give space to the extra mass-flow that comes through the slot gap.
80,120
Can we use multi element wing for slow flight planes, like F1 multi element rear wing? **If we know that pressure act prependicular to the surface why this two upper elements are "almost" vertical?** **It seems to me that they produce "tons" of drag instead lift.Resultant force point to far back,instead down!** [![enter image description here](https://i.stack.imgur.com/3ooHs.png)](https://i.stack.imgur.com/3ooHs.png) [![enter image description here](https://i.stack.imgur.com/6D1T2.jpg)](https://i.stack.imgur.com/6D1T2.jpg) [![enter image description here](https://i.stack.imgur.com/YSUpm.png)](https://i.stack.imgur.com/YSUpm.png)
2020/08/06
['https://aviation.stackexchange.com/questions/80120', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/-1/']
Excellent application inverted on the drag racer, which brings home the point perfectly. If you have enough excess thrust, devices like these can dramaticly increase Coefficient of Lift, but at the cost if loss of lift efficiency, or lower lift to drag ratio. In the case of the dragster, more propulsion efficiency is lost if tires break loose from the pavement, so the drag of the "inverted Fowler flap" is an acceptable trade-off to the **downlift** increasing traction. As mentioned in comments, this is why the Fiesler Storch requires 240 HP to achieve its legendary STOL performance. And just as flaps 10 is better for lift than flaps 30 for taking off, one might question the need for the second and third flap on a lifting wing, but heavy airliners love them when coming in to land as Fowler flaps.
No, it is not if you are not limited in wing area and / or wingspan. The other answers already do a splendid job explaining how this multi-element airfoil works and that it creates a lot of drag. Now look at [slow flight airplanes](https://aviation.stackexchange.com/questions/23929/why-would-maximum-fly-time-endurance-not-coincide-with-max-l-d-operating-point/23944#23944) – they all use high aspect ratio wings without complex flap systems. Doing this gives them better efficiency. Yes, they need more wing area and wing mass to achieve enough lift, but at low speed the friction drag increase caused by the larger surface is small. On the other hand, their induced drag, which is dominant at low speed, is kept small by the high wing span. The induced drag of the multi-element airfoil, on the other hand, is prohibitive, as is the pressure drag caused by the incidence of the rear elements (which actually **is** induced drag) and possible flow separation on the upper surface. This makes the multi-element airfoil less efficient: It needs much more power for the same lift. With race cars that makes sense: The wing cannot be wider than the car itself, and in order to develop the maximum possible downforce, an inefficient way of producing it has to be selected. With airplanes, no such restrictions exist and the glider-like wing is the better choice.
43,757,177
I am experiencing some performance related issues (works ok most of the time, and from time to time there's a spike in the response time from 100ms to 4/5s with no apparent reason) in services implemented in OSB. One of the hypothesis to explain this situation is the fact that the JVM could be performing a Full GC during those spikes and we are monitoring the JVM using mission control. The admins tell me that the jvm is running with full gc's disabled, using G1GC and I can see that in the startup command: ``` -XX:+DisableExplicitGC -XX:+UseG1GC -XX:MaxGCPauseMillis=500 -verbosegc -XX:+PrintGCDetails -XX:+PrintGCDateStamps ``` Also, when I analyse the gc logs, there's no logging of Full GC's performed, I could only find (which makes sense based on those configurations): ``` 2017-05-02T04:46:10.916-0700: 39228.353: [GC pause (G1 Evacuation Pause) (young), 0.0173177 secs] ``` However, as soon as I turned on flight recorder in jmc and started some load testing, I immediately noticed Full GCs being performed [![Full GC example](https://i.stack.imgur.com/kc16e.jpg)](https://i.stack.imgur.com/kc16e.jpg) and I can see it in the logs: ``` 2017-05-02T05:41:31.297: 548.719: [Full GC (Heap Inspection Initiated GC) 1780->705M(2048M), 3.040 secs] ``` As soon as I disable flight recorder, I can run the exact same load test over and over again and no Full GC's are recorded in the logs. Am I missing something here, or is Flight Recorder really forcing the JVM to do Full GC's? Regards
2017/05/03
['https://Stackoverflow.com/questions/43757177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/944245/']
The documentation [says as much](https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr005.html#BABHFCDD): > > The flight recording generated with Heap Statistics enabled will start and end with an old GC. Select that old GC in the list of GCs, and then choose the General tab to see the GC Reason as - `Heap Inspection Initiated GC`. These GCs usually take slightly longer than other GCs. > > >
If you enable Heap Statistics in the recording wizard, the JVM will stop the application and sweep the heap to collect information about it. If you want to be sure of low overhead (1%), use the default recording template (without modifications).
43,757,177
I am experiencing some performance related issues (works ok most of the time, and from time to time there's a spike in the response time from 100ms to 4/5s with no apparent reason) in services implemented in OSB. One of the hypothesis to explain this situation is the fact that the JVM could be performing a Full GC during those spikes and we are monitoring the JVM using mission control. The admins tell me that the jvm is running with full gc's disabled, using G1GC and I can see that in the startup command: ``` -XX:+DisableExplicitGC -XX:+UseG1GC -XX:MaxGCPauseMillis=500 -verbosegc -XX:+PrintGCDetails -XX:+PrintGCDateStamps ``` Also, when I analyse the gc logs, there's no logging of Full GC's performed, I could only find (which makes sense based on those configurations): ``` 2017-05-02T04:46:10.916-0700: 39228.353: [GC pause (G1 Evacuation Pause) (young), 0.0173177 secs] ``` However, as soon as I turned on flight recorder in jmc and started some load testing, I immediately noticed Full GCs being performed [![Full GC example](https://i.stack.imgur.com/kc16e.jpg)](https://i.stack.imgur.com/kc16e.jpg) and I can see it in the logs: ``` 2017-05-02T05:41:31.297: 548.719: [Full GC (Heap Inspection Initiated GC) 1780->705M(2048M), 3.040 secs] ``` As soon as I disable flight recorder, I can run the exact same load test over and over again and no Full GC's are recorded in the logs. Am I missing something here, or is Flight Recorder really forcing the JVM to do Full GC's? Regards
2017/05/03
['https://Stackoverflow.com/questions/43757177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/944245/']
The documentation [says as much](https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr005.html#BABHFCDD): > > The flight recording generated with Heap Statistics enabled will start and end with an old GC. Select that old GC in the list of GCs, and then choose the General tab to see the GC Reason as - `Heap Inspection Initiated GC`. These GCs usually take slightly longer than other GCs. > > >
Yes, JFR recording does run Full GC at regular interval. INitially we also wondered about the same but below documentation gives proper details. <https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr005.html> ``` The flight recording generated with Heap Statistics enabled will start and end with an old GC. Select that old GC in the list of GCs, and then choose the General tab to see the GC Reason as - Heap Inspection Initiated GC. These GCs usually take slightly longer than other GCs. ``` Basically the idea is to look at the objects which are not getting collected even after GC which points towards memory leak. If you want to just take a look at entire heap to get idea of all objects in heap, then JFR is not the right way. Just take a heap dump & view it using visual vm by java or any other tools available freely. While taking heap dump also verify the documentation of command to make sure that heap dump command doesn't run GC. There are options available for that, need to search. Update: Also regarding the GC hypothesis in your question, the best way is to print GC logs through JVM args. There are tools available which takes GC log as input & shows nice graphs with readable stats. So just keep GC logs enabled & do the testing. Then when you see issue/slowness etc. take a look at GC log using tools & see how long GC happpened & how much memory got cleared etc.
43,757,177
I am experiencing some performance related issues (works ok most of the time, and from time to time there's a spike in the response time from 100ms to 4/5s with no apparent reason) in services implemented in OSB. One of the hypothesis to explain this situation is the fact that the JVM could be performing a Full GC during those spikes and we are monitoring the JVM using mission control. The admins tell me that the jvm is running with full gc's disabled, using G1GC and I can see that in the startup command: ``` -XX:+DisableExplicitGC -XX:+UseG1GC -XX:MaxGCPauseMillis=500 -verbosegc -XX:+PrintGCDetails -XX:+PrintGCDateStamps ``` Also, when I analyse the gc logs, there's no logging of Full GC's performed, I could only find (which makes sense based on those configurations): ``` 2017-05-02T04:46:10.916-0700: 39228.353: [GC pause (G1 Evacuation Pause) (young), 0.0173177 secs] ``` However, as soon as I turned on flight recorder in jmc and started some load testing, I immediately noticed Full GCs being performed [![Full GC example](https://i.stack.imgur.com/kc16e.jpg)](https://i.stack.imgur.com/kc16e.jpg) and I can see it in the logs: ``` 2017-05-02T05:41:31.297: 548.719: [Full GC (Heap Inspection Initiated GC) 1780->705M(2048M), 3.040 secs] ``` As soon as I disable flight recorder, I can run the exact same load test over and over again and no Full GC's are recorded in the logs. Am I missing something here, or is Flight Recorder really forcing the JVM to do Full GC's? Regards
2017/05/03
['https://Stackoverflow.com/questions/43757177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/944245/']
If you enable Heap Statistics in the recording wizard, the JVM will stop the application and sweep the heap to collect information about it. If you want to be sure of low overhead (1%), use the default recording template (without modifications).
Yes, JFR recording does run Full GC at regular interval. INitially we also wondered about the same but below documentation gives proper details. <https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr005.html> ``` The flight recording generated with Heap Statistics enabled will start and end with an old GC. Select that old GC in the list of GCs, and then choose the General tab to see the GC Reason as - Heap Inspection Initiated GC. These GCs usually take slightly longer than other GCs. ``` Basically the idea is to look at the objects which are not getting collected even after GC which points towards memory leak. If you want to just take a look at entire heap to get idea of all objects in heap, then JFR is not the right way. Just take a heap dump & view it using visual vm by java or any other tools available freely. While taking heap dump also verify the documentation of command to make sure that heap dump command doesn't run GC. There are options available for that, need to search. Update: Also regarding the GC hypothesis in your question, the best way is to print GC logs through JVM args. There are tools available which takes GC log as input & shows nice graphs with readable stats. So just keep GC logs enabled & do the testing. Then when you see issue/slowness etc. take a look at GC log using tools & see how long GC happpened & how much memory got cleared etc.
34,492,643
I'm running a wildfly 10 app on RedHat Openshift. It is running a very small web service with no database or anything special, and it works OK. After a bit (an hour, 2 maybe) the app stops responding to 'rhc ssh appname' with the error: > > /Library/Ruby/Gems/2.0.0/gems/net-ssh-2.9.2/lib/net/ssh/transport/packet\_stream.rb:89:in > `next\_packet': connection closed by remote host (Net::SSH::Disconnect) > > > The web service still responds, but I cannot ssh or tail the logs or anything to figure out what is wrong. I have to force-stop it and start it again, and it starts working for awhile again. How do I troubleshoot further? I cannot see anything...
2015/12/28
['https://Stackoverflow.com/questions/34492643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1022260/']
SFTP into your app and look at the log files. I use WinSCP on windows.
As suggested above, this is most likely your gear running out of memory. I would suggest that you stop/start your gear, and then check for memory limit violations (<https://developers.openshift.com/en/troubleshooting-faq.html#_why_is_my_application_restarting_automatically_or_having_memory_issues>), you can also change the amount of memory that is allocated to the JVM (<https://developers.openshift.com/en/wildfly-jvm-memory.html>). The best solution would probably be to go ahead and use a larger gear size, probably at least a medium, but you'll have to see how things go.
5,927,010
I am trying to write a script that goes through an entire folder of text files, matching a string pattern. What I want is the count of patterns matched in each file. In unix it could be done by `grep -c <pattern> *`. where the `-c` option returns you the count. Is there any way to get that count using perl regex? Please let me know.
2011/05/08
['https://Stackoverflow.com/questions/5927010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/743810/']
``` my $grep_count = grep (/PATTERN/, @array); ``` Or for a file: ``` perl -we "print scalar grep /PATTERN/, <>;" file.txt ``` <http://perldoc.perl.org/functions/grep.html>
Not that I know of, but just write it, when you open each file, use `while` to go through each of its lines, and use =~ against each line (with your pattern), if matched, then add 1 to your counter.
13,046,319
I wrote a basic hello world program in haskel and tried to compile it with: ghc filename.hs. It produces .hi and .o files but no executable and displays this error in the linker: > > marox@IT-marox:~/Marox$ ghc tupel.hs > > Linking tupel ... > > /usr/bin/ld: --hash-size=31: unknown option > > /usr/bin/ld: use the --help option for usage information > > collect2: ld returned 1 exit status > > > Googling didn't return any useful information. I am on ubuntu 12.04. How can I fix this?
2012/10/24
['https://Stackoverflow.com/questions/13046319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1770728/']
Have you `binutils-gold` installed? If yes, this is the problem (since the [gold linker](http://en.wikipedia.org/wiki/Gold_%28linker%29) does not support `--hash-size` AFAIK). Possible solutions: 1. remove gold 2. your `ld` probably links to `ld.gold`, so change the symlink to `ld.ld` 3. tell the haskell compiler explicitly which linker to use with the `-pgml` option: `ghc -pgml ld.ld tupel.hs` 4. install `ghc` from source, since the configure script of `ghc` will then build `ghc` so that it won't use `--hash-size` 5. Depending on your version of `ghc`, you can adjust the linker settings in `ghc`'s setting file `/usr/lib/ghc-your.ghc.version/settings`
Update - gold on Ubuntu 12.10 appears to move GNU ld to ld.bfd. To fix this problem I deleted the ld link as recommended and remade the link with ``` ln -s ld.bfd ld ``` ghc compilations are now going through. (Couldn't see how to subvert the settings file in usr/lib/ghc, as the entry is for gcc which passes through its commandline to ld, although this would have been my preferred option, in case something else needs ld to be the way it was.) Thanks to Dominic for the pointer of where to look! It was driving me crazy...
27,757,203
I am trying to insert a DATE value into my table however I get the following error: ``` SQL Error: ORA-00984: column not allowed here 00984. 00000 - "column not allowed here" ``` this is my statement: ``` INSERT INTO TstResults (tstcode, EmpID, fname, sname, tstDate, tstRslt) VALUES ((Select tstcode from Tests where Freq ='6mnths') ,(Select EmpID from Employees where fname = 'Sam') ,'Sam' ,'Fisher' ,01-JUN-15 ,'A'); ``` Whenever I type in a date it gives me that above error. In the TstResults the tstDate column has a default value of sysdate. The only way I can out the data in the table is by removing the tstDate from the insert statement.
2015/01/03
['https://Stackoverflow.com/questions/27757203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4413868/']
Use single inverted commas around the date. ``` INSERT INTO TstResults (tstcode, EmpID, fname, sname, tstDate, tstRslt) VALUES ( (Select tstcode from Tests where Freq ='6mnths'), (Select EmpID from Employees where fname = 'Sam'), 'Sam', 'Fisher', '01-JUN-15', 'A'); ```
You are missing quotes around the date: ``` INSERT INTO TstResults (tstcode, EmpID, fname, sname, tstDate, tstRslt) VALUES ((Select tstcode from Tests where Freq ='6mnths') ,(Select EmpID from Employees where fname = 'Sam') ,'Sam' ,'Fisher' ,'01-JUN-15' ,'A'); ```
27,757,203
I am trying to insert a DATE value into my table however I get the following error: ``` SQL Error: ORA-00984: column not allowed here 00984. 00000 - "column not allowed here" ``` this is my statement: ``` INSERT INTO TstResults (tstcode, EmpID, fname, sname, tstDate, tstRslt) VALUES ((Select tstcode from Tests where Freq ='6mnths') ,(Select EmpID from Employees where fname = 'Sam') ,'Sam' ,'Fisher' ,01-JUN-15 ,'A'); ``` Whenever I type in a date it gives me that above error. In the TstResults the tstDate column has a default value of sysdate. The only way I can out the data in the table is by removing the tstDate from the insert statement.
2015/01/03
['https://Stackoverflow.com/questions/27757203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4413868/']
As explained by *a\_horse\_with\_no\_name* in a comment above, for hard-coded date, you might want to use a [*date literal*](https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements003.htm#SQLRF51062) : `DATE '2015-06-15'` On the other hand, Oracle can convert from *strings* to date too. Either *implicitly* using the client `NLS_DATE_FORMAT` parameter as demonstrated in the other answers. Or *explicitly* by calling the `TO_DATE` function with the correct parameters. In your particular case: `TO_DATE('01-JUN-15', 'DD-MON-YY', 'NLS_DATE_LANGUAGE = American')` Using *implicit* conversion might seems *quick-and-easy* but, please note however that *implicit* conversion might work today but fail in the future some clients connecting to the DB with different settings (say for client having a different *locale*). --- So, as of myself, I would push toward using a date literal: ``` INSERT INTO TstResults (tstcode, EmpID, fname, sname, tstDate, tstRslt) VALUES ((Select tstcode from Tests where Freq ='6mnths') ,(Select EmpID from Employees where fname = 'Sam') ,'Sam' ,'Fisher' , DATE '2015-06-15' ,'A') ``` Or, if you really don't want / can't use the date literal: ``` INSERT INTO TstResults (tstcode, EmpID, fname, sname, tstDate, tstRslt) VALUES ((Select tstcode from Tests where Freq ='6mnths') ,(Select EmpID from Employees where fname = 'Sam') ,'Sam' ,'Fisher' ,TO_DATE('01-JUN-15', 'DD-MON-YY', 'NLS_DATE_LANGUAGE = American') ,'A') ```
You are missing quotes around the date: ``` INSERT INTO TstResults (tstcode, EmpID, fname, sname, tstDate, tstRslt) VALUES ((Select tstcode from Tests where Freq ='6mnths') ,(Select EmpID from Employees where fname = 'Sam') ,'Sam' ,'Fisher' ,'01-JUN-15' ,'A'); ```
44,313,448
I know how to decode a JSON string and get the data from one dimensional array but how to get the data from the nested array? Below is my code: ``` $data = json_decode($json); ``` and below is the JSON return value: ``` { "area_metadata": [ { "name": "A", "label_location": { "latitude": 1, "longitude": 1 } }, { "name": "B", "label_location": { "latitude": 1, "longitude": 1 } } ], "items": [ { "update_timestamp": "2017-05-02T09:51:20+08:00", "timestamp": "2017-05-02T09:31:00+08:00", }, "locations": [ { "area": "A", "weather": "Showers" }, { "area": "B", "weather": "Cloudy" } ] } ]} ``` I had tested: ``` echo $data->items->locations[0]->area; ``` but I got this error ``` Trying to get property of non-object ``` Also,I tried to convert JSON into array instead of object: ``` $data = json_decode($json,true); if (isset($data)) { foreach ($data->items->locations as $location) { if (empty($location["area"])) { continue; } if ($location["area"] == "A") { echo $location["weather"]; } } } ``` but it also not working. Could anyone can advise which step that I did wrongly? Thanks! Edited: Below is the pastebin link with full JSON content. <https://pastebin.com/cewszSZD>
2017/06/01
['https://Stackoverflow.com/questions/44313448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5483868/']
*The JSON you provided (in your question) is malformed and using `json_decode()` on it will result in `NULL`. Thus nothing will happen when you try to access the decoded object because it doesn't exist.* The full JSON you provided is valid and the reason why your code didn't yield any results is because in `items` there is an "inner"-array: ``` (...) ["items"] => array(1) { [0] => array(4) { // ^^^^^^^^^^^^^^^^^ ["update_timestamp"] => string(25) "2017-05-02T09:21:18+08:00" ["timestamp"] => string(25) "2017-05-02T09:07:00+08:00" ["valid_period"] => array(2) { ["start"] => string(25) "2017-05-02T09:00:00+08:00" ["end"] => string(25) "2017-05-02T11:00:00+08:00" } ["forecasts"] => array(47) { [0] => array(2) { ["area"] => string(10) "Ang Mo Kio" ["forecast"] => string(19) "Partly Cloudy (Day)" } (...) ``` You'll have to access that array through key `0`, for arrays it will look like this: ``` $data = json_decode($json, true); echo $data['items'][0]['forecasts'][0]['area']; // ^^^ ``` And for objects like this: ``` $data = json_decode($json); echo $data->items[0]->forecasts[0]->area; // ^^^ ``` The second `0` changes the location (the different arrays in the `forecasts` array). You can check the output [here](https://3v4l.org/uT1Lh) (array approach) and [here](https://3v4l.org/c4VZA) (object approach).
It would be easier to help if you post all the JSON data or link to a screenshot of it. Try: ``` $items[0]['locations'][0]['area']; ``` Single quotes on strings, no quotes on numbers.
2,944,175
Let $A$ be a (maybe unbounded) linear operator on a Hilbert space $\mathcal{H}$. If $A-\lambda$ is not injective, $\lambda$ is an eigenvalue. It simply means that $A$ does not change the "direction" of some vectors and so the vectors form an invariant subspace. The rest of the spectrum of $A$ consists of $\lambda$ such that $A - \lambda$ is injective but not surjective or it is bijective but the inverse is not bounded. Spectral theorems require not only eigenvalues but such $\lambda$s. Is there some intuitive or educational meaning for the existence of such $\lambda$?
2018/10/06
['https://math.stackexchange.com/questions/2944175', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/601011/']
Fredholm was the first to define a general linear operator in the latter part of the 19th century. He converted partial differential equations to integral equations, and he studied these operators through what is now known as a resolvent equation. Fredholm connected the singularities of the resolvent $(L-\lambda I)^{-1}$ with the classical eigenfunctions of the differential operators, and this led a more general complex analysis of the resolvent $(L-\lambda I)^{-1}$. The resolvent is defined only if $L-\lambda I$ is a continuous bijection, and $\lambda \mapsto (L-\lambda I)^{-1}$ is a holomorphic operator function on this open set of $\lambda$, which is the resolvent set. As you might expect from classical holomorphic function theory, the resolvent is characterized in some sense by its singularities, which is known as the spectrum of $L$. You can classify the spectrum according to the type of defect preventing the continuous inversion of $(L-\lambda I)$, and the end result of that classification is what you're studying. The idea of a spectral respresentation is that you form a contour integral to represent $A$ and all of its powers by integrating around the spectrum: $$ A^n = \frac{1}{2\pi i}\oint\_{C} \lambda^n \frac{1}{\lambda I-A}d\lambda $$ Then you can shrink the contour down around the spectrum. You may or may not get a nice representation. At least you do for a selfadjoint operator $L$. And you get a completeness result for nice operators when you can trade all of the singularities in the finite place for a singular residue at $\infty$, which at least happens for selfadjoint operators: $$ \lim\_{\lambda\rightarrow\infty}\lambda\frac{1}{\lambda I-A}=I. $$ It's quite a remarkable generalization of Complex Analysis where complex numbers are replaced with operators over a complex Banach or Hilbert space. These techniques were later studied by Mathematicians in the early 20th century in order to prove the convergence of a variety of spectral Fourier expansions associated with equations of Math-Physics. The early genesis of such ideas seems to trace back to Cauchy's analysis of Fourier expansions. One of my favorite quotes is Abel's assessment of Cauchy: *Cauchy is mad and there is nothing that can be done about him, although, right now, he is the only one who knows how mathematics should be done.* As you might guess, Complex Analysis was used to first show that bounded operators on a Complex Banach space must have spectrum because the resolvent $(\lambda I-A)^{-1}$ is holomorphic in $\lambda$ and vanishes at $\infty$; so there must be singularities somewhere in the finite plane.
You can think of them in many ways. One way is to view your operator $A$ as a pointwise limit of operators $A\_n$ with discrete spectrum. As $n$ gets larger the eigenvalues get denser in the parts of continuous spectrum and the associated eigenspaces split up and spread themselves out over this part. A good example of this perspective is the operator "multiplication with the variable" on $L^2([0,1])$ (commonly denoted by $x$ or $x\cdot$). If you want you can consider $L^2(\Bbb R)$ instead to have an unbounded operator. Divide $[0,1]$ or $\Bbb R$ into intervals $(I\_{n,k})\_{k}$ of length $1/n$ and let $E\_{n,k}$ be the characteristic function of $I\_{n,k}$ and $\lambda\_{n,k}$ be the midpoint of the interval $I\_{n,k}$. Now let $A\_n$ be the operator that multiplies a function with $$\sum\_{k}\lambda\_{n,k}\ E\_{n,k}(x).$$ This function is a step-function approximation of $x$. My suggestion is that you draw a picture of what $A\_n$ does for low $n$, then let $n$ get larger. You will be able to see the above remarks manifest themselves in this process.
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
You don't need an inner loop, use the [string](http://msdn.microsoft.com/en-us/library/xsa4321w%28v=vs.110%29.aspx) overload that let's you repeat a char ``` for (int i = 1; i <= 10; i++) { Console.WriteLine(String.Format("{0}\n", new String('*', i)); } ```
Your loop will never end once it's compiled as there's no condition, but that's another issue. One problem is the semi-colon was outside the parenthesis in the nested for loop. ``` for (string o = "*";;) ```
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
You can *simplify* your solution: ``` ... static void Main(string[] args) { // More natural to declare loop variable (int i) in the loop for (int i = 1; i <= 10; ++i) Console.WriteLine(new String('*', i)); // <- No inner loop required Console.ReadLine(); } ... ```
Your loop will never end once it's compiled as there's no condition, but that's another issue. One problem is the semi-colon was outside the parenthesis in the nested for loop. ``` for (string o = "*";;) ```
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
try this code ``` for (int i = 0; i < 10; i++) { for (int j = 0; j <=i; j++) { Console.Write("*"); } Console.WriteLine(); } ```
Your loop will never end once it's compiled as there's no condition, but that's another issue. One problem is the semi-colon was outside the parenthesis in the nested for loop. ``` for (string o = "*";;) ```
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
You don't need an inner loop, use the [string](http://msdn.microsoft.com/en-us/library/xsa4321w%28v=vs.110%29.aspx) overload that let's you repeat a char ``` for (int i = 1; i <= 10; i++) { Console.WriteLine(String.Format("{0}\n", new String('*', i)); } ```
You can *simplify* your solution: ``` ... static void Main(string[] args) { // More natural to declare loop variable (int i) in the loop for (int i = 1; i <= 10; ++i) Console.WriteLine(new String('*', i)); // <- No inner loop required Console.ReadLine(); } ... ```
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
You don't need an inner loop, use the [string](http://msdn.microsoft.com/en-us/library/xsa4321w%28v=vs.110%29.aspx) overload that let's you repeat a char ``` for (int i = 1; i <= 10; i++) { Console.WriteLine(String.Format("{0}\n", new String('*', i)); } ```
Just change the inner for loop: ``` for (int j = 0; j < i; j++) { Console.Write("*"); } ```
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
try this code ``` for (int i = 0; i < 10; i++) { for (int j = 0; j <=i; j++) { Console.Write("*"); } Console.WriteLine(); } ```
You can *simplify* your solution: ``` ... static void Main(string[] args) { // More natural to declare loop variable (int i) in the loop for (int i = 1; i <= 10; ++i) Console.WriteLine(new String('*', i)); // <- No inner loop required Console.ReadLine(); } ... ```
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
You can *simplify* your solution: ``` ... static void Main(string[] args) { // More natural to declare loop variable (int i) in the loop for (int i = 1; i <= 10; ++i) Console.WriteLine(new String('*', i)); // <- No inner loop required Console.ReadLine(); } ... ```
Just change the inner for loop: ``` for (int j = 0; j < i; j++) { Console.Write("*"); } ```
22,895,562
I have an assignment for college, anyway i need to make this pattern OutPut: ``` * ** *** **** ***** ****** ******* ******** ********* ********** ``` Here's my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_11 { class Program { static void Main(string[] args) { int i; for (i = 1; i <= 10; i++) { for (string o = "*";); //Nested for loop { Console.Write(o); } Console.Write("\n"); } Console.ReadLine(); } } } ``` Error 1 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Error 2 Invalid expression term ')' Error 3 Invalid expression term '{' Error 4 ) expected Error 5 { expected
2014/04/06
['https://Stackoverflow.com/questions/22895562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3415389/']
try this code ``` for (int i = 0; i < 10; i++) { for (int j = 0; j <=i; j++) { Console.Write("*"); } Console.WriteLine(); } ```
Just change the inner for loop: ``` for (int j = 0; j < i; j++) { Console.Write("*"); } ```
60,497,943
I have a table as follows: ``` ID | col1 | Date Time 1 | WA | 2/11/20 1 | CI | 1/11/20 2 | CI | 2/11/20 2 | WA | 3/11/20 3 | WA | 2/10/20 3 | WA | 1/11/20 3 | WA | 2/11/20 4 | WA | 1/10/20 4 | CI | 2/10/20 4 | SA | 3/10/20 ``` I want to find all ID values for which col1 had some other value in addition to WA as well and the most latest value in col1 should be 'WA'. i.e. from the sample data above , only ID values 1 & 2 should be returned. Because both of those have an additional value (i.e., CI) in additon to WA, but still the most latest value for them is WA. How do I get that?? FYI, there could be some IDs that don't have WA value at all. I want to eliminate them. Also those that only have WA value, I want to eliminate those as well. Thanks for the help.
2020/03/02
['https://Stackoverflow.com/questions/60497943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10096621/']
There are several problems here. 1. **You `delete[]` instead of `free`.** `strdup` comes from the C library. [The documentation](https://en.cppreference.com/w/c/experimental/dynamic/strdup) tells us how to clean it up. Microsoft's similar `_strdup` [works the same way](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strdup-wcsdup-mbsdup?view=vs-2019). *You must read the documentation for functions that you use*, particularly if you're having trouble with them. That is why it is there. 2. **You invoke the destructor of `A` manually, when you shouldn't.** The object has automatic storage duration, and will be destroyed automatically. When you for some reason call the destructor yourself, that means it'll be ultimately called *twice*. That means the erroneous deallocation call `delete[] myChar` will also be called twice, which is clearly worng. 3. **Your object's copy semantics are broken.** Okay, so you don't copy it here. But any object that manages memory should follow the rule of zero, the rule of three, or the rule of five. 4. **You're checking for leaks too early.** `myA` is still alive when you call `_CrtDumpMemoryLeaks()`, so of course it's going to see that it hasn't been destroyed/freed yet, and deem that to be a memory leak. You're supposed to call that function after you've attempted to rid yourself of all your resources, not before. Here's your directly fixed code: ``` #include "pch.h" #include <iostream> class A { public: A(const char *fn) { myChar = _strdup(fn); } A(const A& other) { myChar = _strdup(other.myChar); } A& operator=(const A& other) { if (&other != this) { free(myChar); myChar = _strdup(other.myChar); } return *this; } ~A() { free(myChar); } char *myChar; }; int main() { { A myA("lala"); } _CrtDumpMemoryLeaks(); //leak detector } ``` And here's what it should have been: ``` #include <string> #include <utility> // for std::move #include <crtdbg.h> // for _CrtDumpMemoryLeaks class A { public: A(std::string str) : m_str(std::move(str)) {} private: std::string str; }; int main() { { A myA("lala"); } _CrtDumpMemoryLeaks(); // leak detector } ```
There are many different allocation schemes out there. Too many to just guess or assume how to free things. So you first look up the documentation on the function. Even just googling something like "msdn \_strdup" often gets there or close (for stuff that comes with Windows / Visual Studio / Microsoft). <https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strdup-wcsdup-mbsdup?view=vs-2019> > > The \_strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space. > > > and > > Because \_strdup calls malloc to allocate storage space for the copy of strSource, it is good practice always to release this memory by calling the free routine on the pointer that's returned by the call to \_strdup. > > > So you need to use `free`
3,870,947
I am new to analysis and following is the question: Show that the sequence $\frac{n+1}{n}$ is monotone, bounded and find its limit. The way I approached it is the following: **To show that it is monotone,** We can write the sequence as $a\_n = 1 + \frac{1}{n}$. Since $n\_{2} > n\_{1}$, we have that $\frac{1}{n\_2}<\frac{1}{n\_1} $. And hence $1 + \frac{1}{n\_{1}} > 1 + \frac{1}{n\_{2}}$. So this shows that the sequence is monotonically decreasing. **Question 1:** With analysis I never know if my argument is complete, so is it complete here? Am I missing something? **To show that it is bounded,** We know that since $n\in \mathbb{N}$, we have that $0 < \frac{1}{n} \le 1$, and so $1 < 1+\frac{1}{n} \le 2$. Hence it is bounded. **Question 2:** Another analysis question, how do I even know that I am not using things that have not been defined yet? Like, have I taken things for granted in my proof above? **Finally, to find the limit,** Can we just say that since this is a monotonically decreasing sequence, that is also bounded we can say that: $\lim\_{n\rightarrow \infty} x\_{n} = inf$ ${x\_{n} : n \in \mathbb{N}}$, we can say that the limit in this case would be 1? **Question 3:** I feel like this is not enough, and we would still have to show officially that 1 is the infimum of this sequence, which I am not sure how I can prove without saying that it makes intuitive sense for me? So if someone could tell me what the official proof of this part would be that would be great. **Final Question:** Is what I have so far correct or have I made any assumptions that one should not make while solving analysis questions?!
2020/10/18
['https://math.stackexchange.com/questions/3870947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
What you did is just fine. Of course, we are not aware of which theorems you can use. Yes, there is a theorem that says that a bounded and decreasing sequence always converges and that its limit is then the infimum of the set of its terms. And, yes, in order to use it, you will have to prove that$$\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}=1,$$but that's easy: * for each $n\in\Bbb N$, $1\leqslant1+\frac1n=\frac{n+1}n$, and therefore $1$ is a lower bound of the set $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$; * if $a>1$, then, by the Archimedian property, there is a $n\in\Bbb N$ such that $n>\frac1{a-1}$. But then $a>1+\frac1n=\frac{n+1}n$, and therefore $a$ is *not* a lower bound of $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$. So, $1$ is the *greatest* lower bound of that set; in other words,$$1=\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}.$$
Your monotonicity and boundedness proofs are very fine. For the limit existence you can use the theorem "an increasing (resp. decreasing) sequence upper (resp. lower) bounded is convergent". But in this case $|x\_n-1|=\frac 1n\to 0$ is quite obvious and you do not need much more.
3,870,947
I am new to analysis and following is the question: Show that the sequence $\frac{n+1}{n}$ is monotone, bounded and find its limit. The way I approached it is the following: **To show that it is monotone,** We can write the sequence as $a\_n = 1 + \frac{1}{n}$. Since $n\_{2} > n\_{1}$, we have that $\frac{1}{n\_2}<\frac{1}{n\_1} $. And hence $1 + \frac{1}{n\_{1}} > 1 + \frac{1}{n\_{2}}$. So this shows that the sequence is monotonically decreasing. **Question 1:** With analysis I never know if my argument is complete, so is it complete here? Am I missing something? **To show that it is bounded,** We know that since $n\in \mathbb{N}$, we have that $0 < \frac{1}{n} \le 1$, and so $1 < 1+\frac{1}{n} \le 2$. Hence it is bounded. **Question 2:** Another analysis question, how do I even know that I am not using things that have not been defined yet? Like, have I taken things for granted in my proof above? **Finally, to find the limit,** Can we just say that since this is a monotonically decreasing sequence, that is also bounded we can say that: $\lim\_{n\rightarrow \infty} x\_{n} = inf$ ${x\_{n} : n \in \mathbb{N}}$, we can say that the limit in this case would be 1? **Question 3:** I feel like this is not enough, and we would still have to show officially that 1 is the infimum of this sequence, which I am not sure how I can prove without saying that it makes intuitive sense for me? So if someone could tell me what the official proof of this part would be that would be great. **Final Question:** Is what I have so far correct or have I made any assumptions that one should not make while solving analysis questions?!
2020/10/18
['https://math.stackexchange.com/questions/3870947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
Answers to 1 and 2 are fine. But you ask a *really* good question about how do you know what you can accept as obvious or not. You should have early one spent half a lesson (or told to read) axioms and definitions of the rational/real field. You therefore have Axiom: if $a < b$ the $a+m < b+m$ for all $m$, and if $c > 0$ than $ac < bc$. And from there you have a proposition that if $1 < k \iff 0< \frac 1k < 1$ (Pf: if $1 < k$ and $\frac 1k \ge 1$ we'd have the contradictory $\frac 1kk \ge 1\cdot k$. If $\frac 1k \le 0$ then $1=\frac 1kk<0\cdot k = 0$. [But note we also have to prove $0\cdot k = 0$, and $1 > 0$ which... well, they should be excercises under your belt] But once you get *through* the lesson (which slogs a *heck* of a lot of stuff; so much stuff that if you actually *gave* it the time you *think* it requires you'd never get to lesson 2) you can assume all basic "facts" about numbers. And .... well, rule of thumb. Feel free to say For all $n > 1$ we have $0 < \frac 1n \le 1$ without justification. BUT be prepared to back it up *if* you are asked. Question 3: Yes you *do* have to prove that $\lim\_{n\to \infty} \frac {n+1}n = 1$. But once you see that $\frac {n+1}n =1+\frac 1n$ that's easy with a $N$ epsilon proof: $|\frac {n+1}n -1|=|(1+\frac 1n) - 1| = |\frac 1n| = \frac 1n < \epsilon \iff$ $\frac 1n < \epsilon \iff$ $n > \frac 1\epsilon$. So by the definition of $\lim\_{n\to \infty} a\_n=L$ we have that there exists an $N: = \frac 1\epsilon$ so that $n > N\implies |\frac {n+1}n -1| < \epsilon$. Thus we have proven $\lim\_{n\to \infty} \frac {n+1}n = 1$. BUT..... again.... once you prove something once you can assume it is known forever. You have *probably* already proven 1) If $\lim a\_x =L$ then $\lim (a\_x + c) = L +c$ for a constant $c$[$\*$] and you have *probably* already proven 2) $\lim\_{n\to \infty} \frac 1n =0$[$\*\*$]. If so, you can just state: As $\frac {n+1}n$ is bounded below and is monotonic decreasing the limit exists[$\*\*\*$] and so $\lim\_{n\to \infty} \frac {n+1}n = \lim\_{n\to \infty}(1 +\frac 1n) = 1+\lim\_{n\to \infty} \frac 1n = 1+0 =1$. That's it. ======= [$\*$]As $|(c+ a\_x) -(c+L)| = |a\_x - L|$ so $|a\_x -L| < \epsilon \iff |(c+ a\_x) -(c+L)|<\epsilon$ so $\lim a\_x = L \iff \lim (c+a\_x) = L + c$. [$\*\*$]ANd $|\frac 1n -0| = \frac n < \epsilon \iff n > \frac 1{\epsilon}$ so $\lim\_{n\to \infty}\frac 1n = 0$. [$\*\*\*$] Actually this needs to be justified, but presumably you already *have*. It is the basic property of Real Numbers that if a set is bounded above or below then the $\sup$ or $\inf$ exists. If a set if monotonic and bounded below then. $\lim\_{n\to \infty} a\_n$ exists and that it must be equal to $\inf a\_n$. This is because for any $\epsilon >0$ then $\inf a\_n + \epsilon$ is not a lower bound and there a $N$ so that $\inf a\_n \le a\_N < \inf a\_n + \epsilon$. And as $a\_n$ is monotonic decrease all $k > N$ are such that $\inf a\_n \le a\_k < a\_N < \inf a\_n + \epsilon$. So $|(\inf a\_n)-a\_k| < \epsilon$. SO $\lim\_{n\to \infty} a\_n = \inf a\_n$.
Your monotonicity and boundedness proofs are very fine. For the limit existence you can use the theorem "an increasing (resp. decreasing) sequence upper (resp. lower) bounded is convergent". But in this case $|x\_n-1|=\frac 1n\to 0$ is quite obvious and you do not need much more.
3,870,947
I am new to analysis and following is the question: Show that the sequence $\frac{n+1}{n}$ is monotone, bounded and find its limit. The way I approached it is the following: **To show that it is monotone,** We can write the sequence as $a\_n = 1 + \frac{1}{n}$. Since $n\_{2} > n\_{1}$, we have that $\frac{1}{n\_2}<\frac{1}{n\_1} $. And hence $1 + \frac{1}{n\_{1}} > 1 + \frac{1}{n\_{2}}$. So this shows that the sequence is monotonically decreasing. **Question 1:** With analysis I never know if my argument is complete, so is it complete here? Am I missing something? **To show that it is bounded,** We know that since $n\in \mathbb{N}$, we have that $0 < \frac{1}{n} \le 1$, and so $1 < 1+\frac{1}{n} \le 2$. Hence it is bounded. **Question 2:** Another analysis question, how do I even know that I am not using things that have not been defined yet? Like, have I taken things for granted in my proof above? **Finally, to find the limit,** Can we just say that since this is a monotonically decreasing sequence, that is also bounded we can say that: $\lim\_{n\rightarrow \infty} x\_{n} = inf$ ${x\_{n} : n \in \mathbb{N}}$, we can say that the limit in this case would be 1? **Question 3:** I feel like this is not enough, and we would still have to show officially that 1 is the infimum of this sequence, which I am not sure how I can prove without saying that it makes intuitive sense for me? So if someone could tell me what the official proof of this part would be that would be great. **Final Question:** Is what I have so far correct or have I made any assumptions that one should not make while solving analysis questions?!
2020/10/18
['https://math.stackexchange.com/questions/3870947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
Answers to 1 and 2 are fine. But you ask a *really* good question about how do you know what you can accept as obvious or not. You should have early one spent half a lesson (or told to read) axioms and definitions of the rational/real field. You therefore have Axiom: if $a < b$ the $a+m < b+m$ for all $m$, and if $c > 0$ than $ac < bc$. And from there you have a proposition that if $1 < k \iff 0< \frac 1k < 1$ (Pf: if $1 < k$ and $\frac 1k \ge 1$ we'd have the contradictory $\frac 1kk \ge 1\cdot k$. If $\frac 1k \le 0$ then $1=\frac 1kk<0\cdot k = 0$. [But note we also have to prove $0\cdot k = 0$, and $1 > 0$ which... well, they should be excercises under your belt] But once you get *through* the lesson (which slogs a *heck* of a lot of stuff; so much stuff that if you actually *gave* it the time you *think* it requires you'd never get to lesson 2) you can assume all basic "facts" about numbers. And .... well, rule of thumb. Feel free to say For all $n > 1$ we have $0 < \frac 1n \le 1$ without justification. BUT be prepared to back it up *if* you are asked. Question 3: Yes you *do* have to prove that $\lim\_{n\to \infty} \frac {n+1}n = 1$. But once you see that $\frac {n+1}n =1+\frac 1n$ that's easy with a $N$ epsilon proof: $|\frac {n+1}n -1|=|(1+\frac 1n) - 1| = |\frac 1n| = \frac 1n < \epsilon \iff$ $\frac 1n < \epsilon \iff$ $n > \frac 1\epsilon$. So by the definition of $\lim\_{n\to \infty} a\_n=L$ we have that there exists an $N: = \frac 1\epsilon$ so that $n > N\implies |\frac {n+1}n -1| < \epsilon$. Thus we have proven $\lim\_{n\to \infty} \frac {n+1}n = 1$. BUT..... again.... once you prove something once you can assume it is known forever. You have *probably* already proven 1) If $\lim a\_x =L$ then $\lim (a\_x + c) = L +c$ for a constant $c$[$\*$] and you have *probably* already proven 2) $\lim\_{n\to \infty} \frac 1n =0$[$\*\*$]. If so, you can just state: As $\frac {n+1}n$ is bounded below and is monotonic decreasing the limit exists[$\*\*\*$] and so $\lim\_{n\to \infty} \frac {n+1}n = \lim\_{n\to \infty}(1 +\frac 1n) = 1+\lim\_{n\to \infty} \frac 1n = 1+0 =1$. That's it. ======= [$\*$]As $|(c+ a\_x) -(c+L)| = |a\_x - L|$ so $|a\_x -L| < \epsilon \iff |(c+ a\_x) -(c+L)|<\epsilon$ so $\lim a\_x = L \iff \lim (c+a\_x) = L + c$. [$\*\*$]ANd $|\frac 1n -0| = \frac n < \epsilon \iff n > \frac 1{\epsilon}$ so $\lim\_{n\to \infty}\frac 1n = 0$. [$\*\*\*$] Actually this needs to be justified, but presumably you already *have*. It is the basic property of Real Numbers that if a set is bounded above or below then the $\sup$ or $\inf$ exists. If a set if monotonic and bounded below then. $\lim\_{n\to \infty} a\_n$ exists and that it must be equal to $\inf a\_n$. This is because for any $\epsilon >0$ then $\inf a\_n + \epsilon$ is not a lower bound and there a $N$ so that $\inf a\_n \le a\_N < \inf a\_n + \epsilon$. And as $a\_n$ is monotonic decrease all $k > N$ are such that $\inf a\_n \le a\_k < a\_N < \inf a\_n + \epsilon$. So $|(\inf a\_n)-a\_k| < \epsilon$. SO $\lim\_{n\to \infty} a\_n = \inf a\_n$.
What you did is just fine. Of course, we are not aware of which theorems you can use. Yes, there is a theorem that says that a bounded and decreasing sequence always converges and that its limit is then the infimum of the set of its terms. And, yes, in order to use it, you will have to prove that$$\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}=1,$$but that's easy: * for each $n\in\Bbb N$, $1\leqslant1+\frac1n=\frac{n+1}n$, and therefore $1$ is a lower bound of the set $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$; * if $a>1$, then, by the Archimedian property, there is a $n\in\Bbb N$ such that $n>\frac1{a-1}$. But then $a>1+\frac1n=\frac{n+1}n$, and therefore $a$ is *not* a lower bound of $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$. So, $1$ is the *greatest* lower bound of that set; in other words,$$1=\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}.$$
3,870,947
I am new to analysis and following is the question: Show that the sequence $\frac{n+1}{n}$ is monotone, bounded and find its limit. The way I approached it is the following: **To show that it is monotone,** We can write the sequence as $a\_n = 1 + \frac{1}{n}$. Since $n\_{2} > n\_{1}$, we have that $\frac{1}{n\_2}<\frac{1}{n\_1} $. And hence $1 + \frac{1}{n\_{1}} > 1 + \frac{1}{n\_{2}}$. So this shows that the sequence is monotonically decreasing. **Question 1:** With analysis I never know if my argument is complete, so is it complete here? Am I missing something? **To show that it is bounded,** We know that since $n\in \mathbb{N}$, we have that $0 < \frac{1}{n} \le 1$, and so $1 < 1+\frac{1}{n} \le 2$. Hence it is bounded. **Question 2:** Another analysis question, how do I even know that I am not using things that have not been defined yet? Like, have I taken things for granted in my proof above? **Finally, to find the limit,** Can we just say that since this is a monotonically decreasing sequence, that is also bounded we can say that: $\lim\_{n\rightarrow \infty} x\_{n} = inf$ ${x\_{n} : n \in \mathbb{N}}$, we can say that the limit in this case would be 1? **Question 3:** I feel like this is not enough, and we would still have to show officially that 1 is the infimum of this sequence, which I am not sure how I can prove without saying that it makes intuitive sense for me? So if someone could tell me what the official proof of this part would be that would be great. **Final Question:** Is what I have so far correct or have I made any assumptions that one should not make while solving analysis questions?!
2020/10/18
['https://math.stackexchange.com/questions/3870947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
What you did is just fine. Of course, we are not aware of which theorems you can use. Yes, there is a theorem that says that a bounded and decreasing sequence always converges and that its limit is then the infimum of the set of its terms. And, yes, in order to use it, you will have to prove that$$\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}=1,$$but that's easy: * for each $n\in\Bbb N$, $1\leqslant1+\frac1n=\frac{n+1}n$, and therefore $1$ is a lower bound of the set $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$; * if $a>1$, then, by the Archimedian property, there is a $n\in\Bbb N$ such that $n>\frac1{a-1}$. But then $a>1+\frac1n=\frac{n+1}n$, and therefore $a$ is *not* a lower bound of $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$. So, $1$ is the *greatest* lower bound of that set; in other words,$$1=\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}.$$
You did the proofs for monotonicity and boundedness totally fine. For the third proof, you can use the **Monotone Convergence Theorem** which states that **if a sequence is a bounded, decreasing sequence, then the limit of the sequence exists at the greatest lower bound (or infimum) of the sequence.** In other words, if $<x\_n>$ is a monotonically decreasing sequence, then $lim\_{n\rightarrow\infty}x\_n\rightarrow inf$ $x\_n, n\in\mathbb{N}$ You've already proved that $x\_n=\frac{n+1}{n}=1+\frac{1}{n}$ is a monotonically decreasing sequence and $1\le 1+\frac{1}{n}\le 2$. So the sequence converges to the $inf$ $x\_n$. Now to find the infimum of the sequence $<x\_n>$: Let $r>1$ for any $r\in\mathbb{R}$. Then, $r-1>0$. Upon applying the Archimedean Property, we will find an $n\_0\in\mathbb{N}$ such that, $\frac{1}{r-1}<n\_0\Rightarrow r>1+\frac{1}{n\_0}$. Now, as $r$ is arbitrary, thus we have that any $r>1$ is not a lower bound of the sequence $<x\_n>$. Thus, the greatest upper bound of the sequence is $1$, since the sequence has a lower bound as $1$. So, $inf$ $x\_n=1$. Thus, you get that the sequence has the limit as $1$ by the **Monotone Convergence Theorem**. There's another easy and interesting way to show that $x\_n\rightarrow 1$: I'll use the result that if $a\_n$ and $b\_n$ are two sequences such that $a\_n\rightarrow a$ and $b\_n\rightarrow b$ for some $a,b\in\mathbb{R}$, then $a\_n+b\_n\rightarrow a+b$. Simply write $<x\_n>=1+\frac{1}{n}$ as the sum of two individual sequences $a\_n=1\forall n\in\mathbb{N}$ and $b\_n=\frac{1}{n}\forall n\in\mathbb{N}$. Now we observe that $a\_n\rightarrow1=a$ and $b\_n\rightarrow0=b$. Thus, $x\_n=a\_n+b\_n\rightarrow a+b=1+0=1 \Rightarrow x\_n\rightarrow1$. This completes the proof that $lim\_{n\rightarrow\infty}x\_n=1$
3,870,947
I am new to analysis and following is the question: Show that the sequence $\frac{n+1}{n}$ is monotone, bounded and find its limit. The way I approached it is the following: **To show that it is monotone,** We can write the sequence as $a\_n = 1 + \frac{1}{n}$. Since $n\_{2} > n\_{1}$, we have that $\frac{1}{n\_2}<\frac{1}{n\_1} $. And hence $1 + \frac{1}{n\_{1}} > 1 + \frac{1}{n\_{2}}$. So this shows that the sequence is monotonically decreasing. **Question 1:** With analysis I never know if my argument is complete, so is it complete here? Am I missing something? **To show that it is bounded,** We know that since $n\in \mathbb{N}$, we have that $0 < \frac{1}{n} \le 1$, and so $1 < 1+\frac{1}{n} \le 2$. Hence it is bounded. **Question 2:** Another analysis question, how do I even know that I am not using things that have not been defined yet? Like, have I taken things for granted in my proof above? **Finally, to find the limit,** Can we just say that since this is a monotonically decreasing sequence, that is also bounded we can say that: $\lim\_{n\rightarrow \infty} x\_{n} = inf$ ${x\_{n} : n \in \mathbb{N}}$, we can say that the limit in this case would be 1? **Question 3:** I feel like this is not enough, and we would still have to show officially that 1 is the infimum of this sequence, which I am not sure how I can prove without saying that it makes intuitive sense for me? So if someone could tell me what the official proof of this part would be that would be great. **Final Question:** Is what I have so far correct or have I made any assumptions that one should not make while solving analysis questions?!
2020/10/18
['https://math.stackexchange.com/questions/3870947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
What you did is just fine. Of course, we are not aware of which theorems you can use. Yes, there is a theorem that says that a bounded and decreasing sequence always converges and that its limit is then the infimum of the set of its terms. And, yes, in order to use it, you will have to prove that$$\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}=1,$$but that's easy: * for each $n\in\Bbb N$, $1\leqslant1+\frac1n=\frac{n+1}n$, and therefore $1$ is a lower bound of the set $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$; * if $a>1$, then, by the Archimedian property, there is a $n\in\Bbb N$ such that $n>\frac1{a-1}$. But then $a>1+\frac1n=\frac{n+1}n$, and therefore $a$ is *not* a lower bound of $\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}$. So, $1$ is the *greatest* lower bound of that set; in other words,$$1=\inf\left\{\frac{n+1}n\,\middle|\,n\in\Bbb N\right\}.$$
**Monotone:** $$n<m\implies \frac1n>\frac1m\implies\frac1n+1>\frac1m+1$$ is sufficiently formal. **Bounded:** $$n> 0\implies \frac1n>0\implies \frac1n+1>1$$ is sufficiently formal. **Limit:** It is pretty obvious that $\dfrac1n+1$ can be made as close as you want to $1$. This intuition can be validated formally by $$\forall\epsilon>0:n>N=\frac1\epsilon\implies\left|\frac1n+1-1\right|<\epsilon,$$ which constructively proves that $\exists N$, and $$\lim\_{n\to\infty}\frac{n+1}n=1.$$
3,870,947
I am new to analysis and following is the question: Show that the sequence $\frac{n+1}{n}$ is monotone, bounded and find its limit. The way I approached it is the following: **To show that it is monotone,** We can write the sequence as $a\_n = 1 + \frac{1}{n}$. Since $n\_{2} > n\_{1}$, we have that $\frac{1}{n\_2}<\frac{1}{n\_1} $. And hence $1 + \frac{1}{n\_{1}} > 1 + \frac{1}{n\_{2}}$. So this shows that the sequence is monotonically decreasing. **Question 1:** With analysis I never know if my argument is complete, so is it complete here? Am I missing something? **To show that it is bounded,** We know that since $n\in \mathbb{N}$, we have that $0 < \frac{1}{n} \le 1$, and so $1 < 1+\frac{1}{n} \le 2$. Hence it is bounded. **Question 2:** Another analysis question, how do I even know that I am not using things that have not been defined yet? Like, have I taken things for granted in my proof above? **Finally, to find the limit,** Can we just say that since this is a monotonically decreasing sequence, that is also bounded we can say that: $\lim\_{n\rightarrow \infty} x\_{n} = inf$ ${x\_{n} : n \in \mathbb{N}}$, we can say that the limit in this case would be 1? **Question 3:** I feel like this is not enough, and we would still have to show officially that 1 is the infimum of this sequence, which I am not sure how I can prove without saying that it makes intuitive sense for me? So if someone could tell me what the official proof of this part would be that would be great. **Final Question:** Is what I have so far correct or have I made any assumptions that one should not make while solving analysis questions?!
2020/10/18
['https://math.stackexchange.com/questions/3870947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
Answers to 1 and 2 are fine. But you ask a *really* good question about how do you know what you can accept as obvious or not. You should have early one spent half a lesson (or told to read) axioms and definitions of the rational/real field. You therefore have Axiom: if $a < b$ the $a+m < b+m$ for all $m$, and if $c > 0$ than $ac < bc$. And from there you have a proposition that if $1 < k \iff 0< \frac 1k < 1$ (Pf: if $1 < k$ and $\frac 1k \ge 1$ we'd have the contradictory $\frac 1kk \ge 1\cdot k$. If $\frac 1k \le 0$ then $1=\frac 1kk<0\cdot k = 0$. [But note we also have to prove $0\cdot k = 0$, and $1 > 0$ which... well, they should be excercises under your belt] But once you get *through* the lesson (which slogs a *heck* of a lot of stuff; so much stuff that if you actually *gave* it the time you *think* it requires you'd never get to lesson 2) you can assume all basic "facts" about numbers. And .... well, rule of thumb. Feel free to say For all $n > 1$ we have $0 < \frac 1n \le 1$ without justification. BUT be prepared to back it up *if* you are asked. Question 3: Yes you *do* have to prove that $\lim\_{n\to \infty} \frac {n+1}n = 1$. But once you see that $\frac {n+1}n =1+\frac 1n$ that's easy with a $N$ epsilon proof: $|\frac {n+1}n -1|=|(1+\frac 1n) - 1| = |\frac 1n| = \frac 1n < \epsilon \iff$ $\frac 1n < \epsilon \iff$ $n > \frac 1\epsilon$. So by the definition of $\lim\_{n\to \infty} a\_n=L$ we have that there exists an $N: = \frac 1\epsilon$ so that $n > N\implies |\frac {n+1}n -1| < \epsilon$. Thus we have proven $\lim\_{n\to \infty} \frac {n+1}n = 1$. BUT..... again.... once you prove something once you can assume it is known forever. You have *probably* already proven 1) If $\lim a\_x =L$ then $\lim (a\_x + c) = L +c$ for a constant $c$[$\*$] and you have *probably* already proven 2) $\lim\_{n\to \infty} \frac 1n =0$[$\*\*$]. If so, you can just state: As $\frac {n+1}n$ is bounded below and is monotonic decreasing the limit exists[$\*\*\*$] and so $\lim\_{n\to \infty} \frac {n+1}n = \lim\_{n\to \infty}(1 +\frac 1n) = 1+\lim\_{n\to \infty} \frac 1n = 1+0 =1$. That's it. ======= [$\*$]As $|(c+ a\_x) -(c+L)| = |a\_x - L|$ so $|a\_x -L| < \epsilon \iff |(c+ a\_x) -(c+L)|<\epsilon$ so $\lim a\_x = L \iff \lim (c+a\_x) = L + c$. [$\*\*$]ANd $|\frac 1n -0| = \frac n < \epsilon \iff n > \frac 1{\epsilon}$ so $\lim\_{n\to \infty}\frac 1n = 0$. [$\*\*\*$] Actually this needs to be justified, but presumably you already *have*. It is the basic property of Real Numbers that if a set is bounded above or below then the $\sup$ or $\inf$ exists. If a set if monotonic and bounded below then. $\lim\_{n\to \infty} a\_n$ exists and that it must be equal to $\inf a\_n$. This is because for any $\epsilon >0$ then $\inf a\_n + \epsilon$ is not a lower bound and there a $N$ so that $\inf a\_n \le a\_N < \inf a\_n + \epsilon$. And as $a\_n$ is monotonic decrease all $k > N$ are such that $\inf a\_n \le a\_k < a\_N < \inf a\_n + \epsilon$. So $|(\inf a\_n)-a\_k| < \epsilon$. SO $\lim\_{n\to \infty} a\_n = \inf a\_n$.
You did the proofs for monotonicity and boundedness totally fine. For the third proof, you can use the **Monotone Convergence Theorem** which states that **if a sequence is a bounded, decreasing sequence, then the limit of the sequence exists at the greatest lower bound (or infimum) of the sequence.** In other words, if $<x\_n>$ is a monotonically decreasing sequence, then $lim\_{n\rightarrow\infty}x\_n\rightarrow inf$ $x\_n, n\in\mathbb{N}$ You've already proved that $x\_n=\frac{n+1}{n}=1+\frac{1}{n}$ is a monotonically decreasing sequence and $1\le 1+\frac{1}{n}\le 2$. So the sequence converges to the $inf$ $x\_n$. Now to find the infimum of the sequence $<x\_n>$: Let $r>1$ for any $r\in\mathbb{R}$. Then, $r-1>0$. Upon applying the Archimedean Property, we will find an $n\_0\in\mathbb{N}$ such that, $\frac{1}{r-1}<n\_0\Rightarrow r>1+\frac{1}{n\_0}$. Now, as $r$ is arbitrary, thus we have that any $r>1$ is not a lower bound of the sequence $<x\_n>$. Thus, the greatest upper bound of the sequence is $1$, since the sequence has a lower bound as $1$. So, $inf$ $x\_n=1$. Thus, you get that the sequence has the limit as $1$ by the **Monotone Convergence Theorem**. There's another easy and interesting way to show that $x\_n\rightarrow 1$: I'll use the result that if $a\_n$ and $b\_n$ are two sequences such that $a\_n\rightarrow a$ and $b\_n\rightarrow b$ for some $a,b\in\mathbb{R}$, then $a\_n+b\_n\rightarrow a+b$. Simply write $<x\_n>=1+\frac{1}{n}$ as the sum of two individual sequences $a\_n=1\forall n\in\mathbb{N}$ and $b\_n=\frac{1}{n}\forall n\in\mathbb{N}$. Now we observe that $a\_n\rightarrow1=a$ and $b\_n\rightarrow0=b$. Thus, $x\_n=a\_n+b\_n\rightarrow a+b=1+0=1 \Rightarrow x\_n\rightarrow1$. This completes the proof that $lim\_{n\rightarrow\infty}x\_n=1$
3,870,947
I am new to analysis and following is the question: Show that the sequence $\frac{n+1}{n}$ is monotone, bounded and find its limit. The way I approached it is the following: **To show that it is monotone,** We can write the sequence as $a\_n = 1 + \frac{1}{n}$. Since $n\_{2} > n\_{1}$, we have that $\frac{1}{n\_2}<\frac{1}{n\_1} $. And hence $1 + \frac{1}{n\_{1}} > 1 + \frac{1}{n\_{2}}$. So this shows that the sequence is monotonically decreasing. **Question 1:** With analysis I never know if my argument is complete, so is it complete here? Am I missing something? **To show that it is bounded,** We know that since $n\in \mathbb{N}$, we have that $0 < \frac{1}{n} \le 1$, and so $1 < 1+\frac{1}{n} \le 2$. Hence it is bounded. **Question 2:** Another analysis question, how do I even know that I am not using things that have not been defined yet? Like, have I taken things for granted in my proof above? **Finally, to find the limit,** Can we just say that since this is a monotonically decreasing sequence, that is also bounded we can say that: $\lim\_{n\rightarrow \infty} x\_{n} = inf$ ${x\_{n} : n \in \mathbb{N}}$, we can say that the limit in this case would be 1? **Question 3:** I feel like this is not enough, and we would still have to show officially that 1 is the infimum of this sequence, which I am not sure how I can prove without saying that it makes intuitive sense for me? So if someone could tell me what the official proof of this part would be that would be great. **Final Question:** Is what I have so far correct or have I made any assumptions that one should not make while solving analysis questions?!
2020/10/18
['https://math.stackexchange.com/questions/3870947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
Answers to 1 and 2 are fine. But you ask a *really* good question about how do you know what you can accept as obvious or not. You should have early one spent half a lesson (or told to read) axioms and definitions of the rational/real field. You therefore have Axiom: if $a < b$ the $a+m < b+m$ for all $m$, and if $c > 0$ than $ac < bc$. And from there you have a proposition that if $1 < k \iff 0< \frac 1k < 1$ (Pf: if $1 < k$ and $\frac 1k \ge 1$ we'd have the contradictory $\frac 1kk \ge 1\cdot k$. If $\frac 1k \le 0$ then $1=\frac 1kk<0\cdot k = 0$. [But note we also have to prove $0\cdot k = 0$, and $1 > 0$ which... well, they should be excercises under your belt] But once you get *through* the lesson (which slogs a *heck* of a lot of stuff; so much stuff that if you actually *gave* it the time you *think* it requires you'd never get to lesson 2) you can assume all basic "facts" about numbers. And .... well, rule of thumb. Feel free to say For all $n > 1$ we have $0 < \frac 1n \le 1$ without justification. BUT be prepared to back it up *if* you are asked. Question 3: Yes you *do* have to prove that $\lim\_{n\to \infty} \frac {n+1}n = 1$. But once you see that $\frac {n+1}n =1+\frac 1n$ that's easy with a $N$ epsilon proof: $|\frac {n+1}n -1|=|(1+\frac 1n) - 1| = |\frac 1n| = \frac 1n < \epsilon \iff$ $\frac 1n < \epsilon \iff$ $n > \frac 1\epsilon$. So by the definition of $\lim\_{n\to \infty} a\_n=L$ we have that there exists an $N: = \frac 1\epsilon$ so that $n > N\implies |\frac {n+1}n -1| < \epsilon$. Thus we have proven $\lim\_{n\to \infty} \frac {n+1}n = 1$. BUT..... again.... once you prove something once you can assume it is known forever. You have *probably* already proven 1) If $\lim a\_x =L$ then $\lim (a\_x + c) = L +c$ for a constant $c$[$\*$] and you have *probably* already proven 2) $\lim\_{n\to \infty} \frac 1n =0$[$\*\*$]. If so, you can just state: As $\frac {n+1}n$ is bounded below and is monotonic decreasing the limit exists[$\*\*\*$] and so $\lim\_{n\to \infty} \frac {n+1}n = \lim\_{n\to \infty}(1 +\frac 1n) = 1+\lim\_{n\to \infty} \frac 1n = 1+0 =1$. That's it. ======= [$\*$]As $|(c+ a\_x) -(c+L)| = |a\_x - L|$ so $|a\_x -L| < \epsilon \iff |(c+ a\_x) -(c+L)|<\epsilon$ so $\lim a\_x = L \iff \lim (c+a\_x) = L + c$. [$\*\*$]ANd $|\frac 1n -0| = \frac n < \epsilon \iff n > \frac 1{\epsilon}$ so $\lim\_{n\to \infty}\frac 1n = 0$. [$\*\*\*$] Actually this needs to be justified, but presumably you already *have*. It is the basic property of Real Numbers that if a set is bounded above or below then the $\sup$ or $\inf$ exists. If a set if monotonic and bounded below then. $\lim\_{n\to \infty} a\_n$ exists and that it must be equal to $\inf a\_n$. This is because for any $\epsilon >0$ then $\inf a\_n + \epsilon$ is not a lower bound and there a $N$ so that $\inf a\_n \le a\_N < \inf a\_n + \epsilon$. And as $a\_n$ is monotonic decrease all $k > N$ are such that $\inf a\_n \le a\_k < a\_N < \inf a\_n + \epsilon$. So $|(\inf a\_n)-a\_k| < \epsilon$. SO $\lim\_{n\to \infty} a\_n = \inf a\_n$.
**Monotone:** $$n<m\implies \frac1n>\frac1m\implies\frac1n+1>\frac1m+1$$ is sufficiently formal. **Bounded:** $$n> 0\implies \frac1n>0\implies \frac1n+1>1$$ is sufficiently formal. **Limit:** It is pretty obvious that $\dfrac1n+1$ can be made as close as you want to $1$. This intuition can be validated formally by $$\forall\epsilon>0:n>N=\frac1\epsilon\implies\left|\frac1n+1-1\right|<\epsilon,$$ which constructively proves that $\exists N$, and $$\lim\_{n\to\infty}\frac{n+1}n=1.$$
8,191
The perennial concern about low quality questions and low quality answers is resurfacing again. It is my impression (not backed by data) that many VLQ answers are posted by rep 1 unregistered people. This seems to be true also of some low quality questions. Is there data or could data be obtained to back up or refute this impression? Could ELU run an experiment (for say, 3 months) requiring new users to register before posting? This seems like an effort which might: (a) reduce the VLQ posts; (b) be unlikely to scare off people we want to attract; and (c) not require a lot of work to implement and analyze. **Addendum in response to comments so far**: Is it likely that ELU will be **permitted** by SE to require registration, either as a test or permanently? If not, we should move on.
2016/07/22
['https://english.meta.stackexchange.com/questions/8191', 'https://english.meta.stackexchange.com', 'https://english.meta.stackexchange.com/users/121061/']
A strain on the community? How hard is a downvote on a poorly written question?
I can understand why you've proposed "taking mandatory English quiz". Yes, it is frustrating to see all those low-quality posts and find that we are not doing enough to prevent or slow down the influx of low-quality posts. My question is "Is there anything we can do?" One user once proposed all questions be *put on hold* automatically and users vote to open an on-topic question among them. This suggestion illustrates there have been so many off-topic and low-quality questions and answers posted and deleted on ELU. ELU is open to everybody in the world. Even a user who doesn't bother to register their user name can post a question and answer (except to closed and protected questions) and edit any post they want. We can't stop new users from asking, answering a question and editing a post. We need to 1. Post a comment for clarification, additional information, request to show research. 2. Flag a question if you don't have 3,000 reputation points needed to vote to put a question on hold. 3. Downvote a post which is not useful and doesn't show research efforts. 4. Monitor suggested edits, especially those submitted by anonymous users, and review first posts and late answers carefully. There are mechanisms we can use to deal with low-quality posts. I am one of the most aggressive users who are employing them to clean up the site. Even though asking new users to take mandatory English quiz might help reduce the number of low-quality posts, it is not an ideal solution considering the manpower and time it will take. Related questions: [What can we do to make this site more "intimidating"?](https://english.meta.stackexchange.com/questions/7429/what-can-we-do-to-make-this-site-more-intimidating) [Does ELU Have Worse Questions Than Other Sites?](https://english.meta.stackexchange.com/questions/7535/does-elu-have-worse-questions-than-other-sites) [Extraordinary spike in low-quality questions by 1 rep users](https://english.meta.stackexchange.com/questions/7576/extraordinary-spike-in-low-quality-questions-by-1-rep-users)
8,191
The perennial concern about low quality questions and low quality answers is resurfacing again. It is my impression (not backed by data) that many VLQ answers are posted by rep 1 unregistered people. This seems to be true also of some low quality questions. Is there data or could data be obtained to back up or refute this impression? Could ELU run an experiment (for say, 3 months) requiring new users to register before posting? This seems like an effort which might: (a) reduce the VLQ posts; (b) be unlikely to scare off people we want to attract; and (c) not require a lot of work to implement and analyze. **Addendum in response to comments so far**: Is it likely that ELU will be **permitted** by SE to require registration, either as a test or permanently? If not, we should move on.
2016/07/22
['https://english.meta.stackexchange.com/questions/8191', 'https://english.meta.stackexchange.com', 'https://english.meta.stackexchange.com/users/121061/']
A strain on the community? How hard is a downvote on a poorly written question?
My account is two years old, but I started off few months ago. I'm not a native English speaker, and I have made mistakes a lot. If such a quiz was mandatory, I wouldn't even have joined at all.
8,191
The perennial concern about low quality questions and low quality answers is resurfacing again. It is my impression (not backed by data) that many VLQ answers are posted by rep 1 unregistered people. This seems to be true also of some low quality questions. Is there data or could data be obtained to back up or refute this impression? Could ELU run an experiment (for say, 3 months) requiring new users to register before posting? This seems like an effort which might: (a) reduce the VLQ posts; (b) be unlikely to scare off people we want to attract; and (c) not require a lot of work to implement and analyze. **Addendum in response to comments so far**: Is it likely that ELU will be **permitted** by SE to require registration, either as a test or permanently? If not, we should move on.
2016/07/22
['https://english.meta.stackexchange.com/questions/8191', 'https://english.meta.stackexchange.com', 'https://english.meta.stackexchange.com/users/121061/']
A strain on the community? How hard is a downvote on a poorly written question?
To answer your question of why it hasn't been done yet: It had not been requested before. The number of downvotes here indicates that the community does not support this plan. Therefore, it is safe to conclude that it won't be implemented.
8,191
The perennial concern about low quality questions and low quality answers is resurfacing again. It is my impression (not backed by data) that many VLQ answers are posted by rep 1 unregistered people. This seems to be true also of some low quality questions. Is there data or could data be obtained to back up or refute this impression? Could ELU run an experiment (for say, 3 months) requiring new users to register before posting? This seems like an effort which might: (a) reduce the VLQ posts; (b) be unlikely to scare off people we want to attract; and (c) not require a lot of work to implement and analyze. **Addendum in response to comments so far**: Is it likely that ELU will be **permitted** by SE to require registration, either as a test or permanently? If not, we should move on.
2016/07/22
['https://english.meta.stackexchange.com/questions/8191', 'https://english.meta.stackexchange.com', 'https://english.meta.stackexchange.com/users/121061/']
My account is two years old, but I started off few months ago. I'm not a native English speaker, and I have made mistakes a lot. If such a quiz was mandatory, I wouldn't even have joined at all.
I can understand why you've proposed "taking mandatory English quiz". Yes, it is frustrating to see all those low-quality posts and find that we are not doing enough to prevent or slow down the influx of low-quality posts. My question is "Is there anything we can do?" One user once proposed all questions be *put on hold* automatically and users vote to open an on-topic question among them. This suggestion illustrates there have been so many off-topic and low-quality questions and answers posted and deleted on ELU. ELU is open to everybody in the world. Even a user who doesn't bother to register their user name can post a question and answer (except to closed and protected questions) and edit any post they want. We can't stop new users from asking, answering a question and editing a post. We need to 1. Post a comment for clarification, additional information, request to show research. 2. Flag a question if you don't have 3,000 reputation points needed to vote to put a question on hold. 3. Downvote a post which is not useful and doesn't show research efforts. 4. Monitor suggested edits, especially those submitted by anonymous users, and review first posts and late answers carefully. There are mechanisms we can use to deal with low-quality posts. I am one of the most aggressive users who are employing them to clean up the site. Even though asking new users to take mandatory English quiz might help reduce the number of low-quality posts, it is not an ideal solution considering the manpower and time it will take. Related questions: [What can we do to make this site more "intimidating"?](https://english.meta.stackexchange.com/questions/7429/what-can-we-do-to-make-this-site-more-intimidating) [Does ELU Have Worse Questions Than Other Sites?](https://english.meta.stackexchange.com/questions/7535/does-elu-have-worse-questions-than-other-sites) [Extraordinary spike in low-quality questions by 1 rep users](https://english.meta.stackexchange.com/questions/7576/extraordinary-spike-in-low-quality-questions-by-1-rep-users)
8,191
The perennial concern about low quality questions and low quality answers is resurfacing again. It is my impression (not backed by data) that many VLQ answers are posted by rep 1 unregistered people. This seems to be true also of some low quality questions. Is there data or could data be obtained to back up or refute this impression? Could ELU run an experiment (for say, 3 months) requiring new users to register before posting? This seems like an effort which might: (a) reduce the VLQ posts; (b) be unlikely to scare off people we want to attract; and (c) not require a lot of work to implement and analyze. **Addendum in response to comments so far**: Is it likely that ELU will be **permitted** by SE to require registration, either as a test or permanently? If not, we should move on.
2016/07/22
['https://english.meta.stackexchange.com/questions/8191', 'https://english.meta.stackexchange.com', 'https://english.meta.stackexchange.com/users/121061/']
To answer your question of why it hasn't been done yet: It had not been requested before. The number of downvotes here indicates that the community does not support this plan. Therefore, it is safe to conclude that it won't be implemented.
I can understand why you've proposed "taking mandatory English quiz". Yes, it is frustrating to see all those low-quality posts and find that we are not doing enough to prevent or slow down the influx of low-quality posts. My question is "Is there anything we can do?" One user once proposed all questions be *put on hold* automatically and users vote to open an on-topic question among them. This suggestion illustrates there have been so many off-topic and low-quality questions and answers posted and deleted on ELU. ELU is open to everybody in the world. Even a user who doesn't bother to register their user name can post a question and answer (except to closed and protected questions) and edit any post they want. We can't stop new users from asking, answering a question and editing a post. We need to 1. Post a comment for clarification, additional information, request to show research. 2. Flag a question if you don't have 3,000 reputation points needed to vote to put a question on hold. 3. Downvote a post which is not useful and doesn't show research efforts. 4. Monitor suggested edits, especially those submitted by anonymous users, and review first posts and late answers carefully. There are mechanisms we can use to deal with low-quality posts. I am one of the most aggressive users who are employing them to clean up the site. Even though asking new users to take mandatory English quiz might help reduce the number of low-quality posts, it is not an ideal solution considering the manpower and time it will take. Related questions: [What can we do to make this site more "intimidating"?](https://english.meta.stackexchange.com/questions/7429/what-can-we-do-to-make-this-site-more-intimidating) [Does ELU Have Worse Questions Than Other Sites?](https://english.meta.stackexchange.com/questions/7535/does-elu-have-worse-questions-than-other-sites) [Extraordinary spike in low-quality questions by 1 rep users](https://english.meta.stackexchange.com/questions/7576/extraordinary-spike-in-low-quality-questions-by-1-rep-users)
21,090,499
I am new to PHP. I have a problem. I have a simple HTML form where when I select the country from select / option list provided, i want PHP to echo message on country I selected. Also I want PHP include function to list the form specific to that country name (by concatanating). Can someone please help me by pointing where I went wrong. I am new to PHP, self taught and have no idea if this approach is correct. Thanks in advance for anticipated help. ``` <pre> <form name="form1" method="post" action="component_project_in_countries.php"> <label for="country">View outlets in which country? </label> <select name="country_chosen" onchange="document.form1.submit()" id="country"> <option value="">All Middle Eastern Countries</option> <option value="Iraq">Iraq</option> <option value="Kuwait">Kuwait</option> <option value="Bahrain">Bahrain</option> <option value="Saudi">Saudi Arabia</option> <option value="Qatar">Qatar</option> <option value="Oman">Oman</option> <option value="Yemen">Yemen</option> <option value="Jordan">Jordan</option> <option value="Israel">Israel</option> </select> </form> <br> <?php $country_selected = ''; $country_selected = $_POST['country_chosen']; echo "You have chosen to view outlets in " . $country_selected; include ("inc/OutletsIn" . $country_selected .".php";) ?> </pre> ``` Thank you for your help on my earlier post. I am able to echo out and concatenate file name in PHP include. But I have a new problem. The option value i selected (country name) does not get displayed in the box. How can i hold the chosen value for the session. Please advise. Thank you again.
2014/01/13
['https://Stackoverflow.com/questions/21090499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3189978/']
First check that a value has been given to `$_POST['country_chosen']` with `isset()`. Then remove that extra semi-colon that is causing a syntax error (in your `include()`) statement: ``` if(isset($_POST['country_chosen'])){ $country_selected = $_POST['country_chosen']; echo "You have chosen to view outlets in " . $country_selected; include("inc/OutletsIn" . $country_selected .".php"); } ``` Includes something (like) `inc/OutletsInIsrael.php`
``` if(!empty($_POST['country_chosen'])){ $country_selected = $_POST['country_chosen']; echo "You have chosen to view outlets in " . $country_selected; require "inc/OutletsIn".$country_selected.".php"; //no brackets required } else { /* throw error */ } ```
21,090,499
I am new to PHP. I have a problem. I have a simple HTML form where when I select the country from select / option list provided, i want PHP to echo message on country I selected. Also I want PHP include function to list the form specific to that country name (by concatanating). Can someone please help me by pointing where I went wrong. I am new to PHP, self taught and have no idea if this approach is correct. Thanks in advance for anticipated help. ``` <pre> <form name="form1" method="post" action="component_project_in_countries.php"> <label for="country">View outlets in which country? </label> <select name="country_chosen" onchange="document.form1.submit()" id="country"> <option value="">All Middle Eastern Countries</option> <option value="Iraq">Iraq</option> <option value="Kuwait">Kuwait</option> <option value="Bahrain">Bahrain</option> <option value="Saudi">Saudi Arabia</option> <option value="Qatar">Qatar</option> <option value="Oman">Oman</option> <option value="Yemen">Yemen</option> <option value="Jordan">Jordan</option> <option value="Israel">Israel</option> </select> </form> <br> <?php $country_selected = ''; $country_selected = $_POST['country_chosen']; echo "You have chosen to view outlets in " . $country_selected; include ("inc/OutletsIn" . $country_selected .".php";) ?> </pre> ``` Thank you for your help on my earlier post. I am able to echo out and concatenate file name in PHP include. But I have a new problem. The option value i selected (country name) does not get displayed in the box. How can i hold the chosen value for the session. Please advise. Thank you again.
2014/01/13
['https://Stackoverflow.com/questions/21090499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3189978/']
First check that a value has been given to `$_POST['country_chosen']` with `isset()`. Then remove that extra semi-colon that is causing a syntax error (in your `include()`) statement: ``` if(isset($_POST['country_chosen'])){ $country_selected = $_POST['country_chosen']; echo "You have chosen to view outlets in " . $country_selected; include("inc/OutletsIn" . $country_selected .".php"); } ``` Includes something (like) `inc/OutletsInIsrael.php`
Here is your updated code, just copy & replace : **component\_project\_in\_countries.php** ``` <pre> <form name="form1" method="post" action="component_project_in_countries.php"> <label for="country">View outlets in which country? </label> <select name="country_chosen" onchange="document.form1.submit()" id="country"> <option value="">All Middle Eastern Countries</option> <option value="Iraq">Iraq</option> <option value="Kuwait">Kuwait</option> <option value="Bahrain">Bahrain</option> <option value="Saudi">Saudi Arabia</option> <option value="Qatar">Qatar</option> <option value="Oman">Oman</option> <option value="Yemen">Yemen</option> <option value="Jordan">Jordan</option> <option value="Israel">Israel</option> </select> </form> <br> <?php if(isset($_POST['country_chosen'])) { $country_selected = ''; $country_selected = $_POST['country_chosen']; echo "You have chosen to view outlets in " . $country_selected; include ("inc/OutletsIn" . $country_selected .".php");// here you have added `;` on wrong place. } ?> </pre> ``` New answer, Just replace the code of select box : ``` <select name="country_chosen" onchange="document.form1.submit()" id="country"> <option value="">All Middle Eastern Countries</option> <option value="Iraq" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Iraq')) echo 'selected' ?> >Iraq</option> <option value="Kuwait" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Kuwait')) echo 'selected' ?> >Kuwait</option> <option value="Bahrain" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Bahrain')) echo 'selected' ?> >Bahrain</option> <option value="Saudi" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Saudi')) echo 'selected' ?> >Saudi Arabia</option> <option value="Qatar" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Qatar')) echo 'selected' ?> >Qatar</option> <option value="Oman" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Oman')) echo 'selected' ?> >Oman</option> <option value="Yemen" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Yemen')) echo 'selected' ?> >Yemen</option> <option value="Jordan" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Jordan')) echo 'selected' ?> >Jordan</option> <option value="Israel" <?php if(isset($_POST['country_chosen']) && ($_POST['country_chosen']=='Israel')) echo 'selected' ?> >Israel</option> </select> ```
23,683,604
I made a script in order to create this "slideshow": <http://jsfiddle.net/LWBJG/2/> yet I can not go back to the last slide if I hit "previous" when it is on the first slide I tried using the last-child selector but had no success I also tried resetting the count directly like so: ``` if(count==1){ count=2; $(".slideshow :nth-child("+count+")").fadeIn(); } ``` I've been stuck with this for two days, I'm trying to understand what I'm doing wrong! **all I what's left to do is to go to the last slide if I hit "previous" while I'm "standing" on the first slide**
2014/05/15
['https://Stackoverflow.com/questions/23683604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114993/']
First you need to hide all the other `.slideshow img` elements not being shown when your page first loads. You can do that multiple ways, but here's an example: ``` $(".slideshow img:not(:nth-child(" + count + "))").hide(); ``` Next, you need to hide the current showing slide when going to the previous one: ``` $(".slideshow :nth-child(" + count + ")").fadeOut(); ``` Finally, you need to set the count to the number of elements in `.slideshow img` when going to the last image: ``` count = $(".slideshow img").length; ``` Here's a working example: <http://jsfiddle.net/LWBJG/22/>
You simply were not fading out in the prev loop like you were in the next button loop. ``` $(".slideshow :nth-child("+count+")").fadeOut() ``` Also, in the css, i put the following code: ``` .slideshow > img:not(:first-child) { display:none;} ``` This makes only the first img appear as default, and then the other ones will fade in as necessary. The way you currently have it, is count is updating properly but your images are inline and are appearing behind the current image number 1.. But on your next loop click, you properly fade out the images. Hope this helps. Here is the <http://jsfiddle.net/LWBJG/18/>
23,683,604
I made a script in order to create this "slideshow": <http://jsfiddle.net/LWBJG/2/> yet I can not go back to the last slide if I hit "previous" when it is on the first slide I tried using the last-child selector but had no success I also tried resetting the count directly like so: ``` if(count==1){ count=2; $(".slideshow :nth-child("+count+")").fadeIn(); } ``` I've been stuck with this for two days, I'm trying to understand what I'm doing wrong! **all I what's left to do is to go to the last slide if I hit "previous" while I'm "standing" on the first slide**
2014/05/15
['https://Stackoverflow.com/questions/23683604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114993/']
First you need to hide all the other `.slideshow img` elements not being shown when your page first loads. You can do that multiple ways, but here's an example: ``` $(".slideshow img:not(:nth-child(" + count + "))").hide(); ``` Next, you need to hide the current showing slide when going to the previous one: ``` $(".slideshow :nth-child(" + count + ")").fadeOut(); ``` Finally, you need to set the count to the number of elements in `.slideshow img` when going to the last image: ``` count = $(".slideshow img").length; ``` Here's a working example: <http://jsfiddle.net/LWBJG/22/>
Using multiple `fadeIn()`s might lead to a mess. In your case, if you really want to do so, you can first `fadeOut()` all images before `fadeIn()` the desired one. This solves the problem. ``` $(".slideshow img").fadeOut(); $(".slideshow :nth-child("+count+")").fadeIn(); ``` `hide()` should also work.
23,683,604
I made a script in order to create this "slideshow": <http://jsfiddle.net/LWBJG/2/> yet I can not go back to the last slide if I hit "previous" when it is on the first slide I tried using the last-child selector but had no success I also tried resetting the count directly like so: ``` if(count==1){ count=2; $(".slideshow :nth-child("+count+")").fadeIn(); } ``` I've been stuck with this for two days, I'm trying to understand what I'm doing wrong! **all I what's left to do is to go to the last slide if I hit "previous" while I'm "standing" on the first slide**
2014/05/15
['https://Stackoverflow.com/questions/23683604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114993/']
First you need to hide all the other `.slideshow img` elements not being shown when your page first loads. You can do that multiple ways, but here's an example: ``` $(".slideshow img:not(:nth-child(" + count + "))").hide(); ``` Next, you need to hide the current showing slide when going to the previous one: ``` $(".slideshow :nth-child(" + count + ")").fadeOut(); ``` Finally, you need to set the count to the number of elements in `.slideshow img` when going to the last image: ``` count = $(".slideshow img").length; ``` Here's a working example: <http://jsfiddle.net/LWBJG/22/>
Yes i know, i'am late to the party, but I played around a bit. Maybe someone will find the solution useful later on. Here is a demo: <http://jsfiddle.net/NicoO/LWBJG/25/> ``` var $slideContainer = $(".slideshow") var totalSlides = getAllSlides().length; var slideIndex = 0; function getAllSlides(){ return $slideContainer.children("img"); } function getSlide(index){ return $slideContainer.children().eq(index); } function slideExists(index){ return getSlide(index).length; } function getCurrentSlide(){ return getSlide(slideIndex); } function animateSlide(){ getAllSlides().fadeOut(); getCurrentSlide().fadeIn(); } $("#next").on("click", function () { slideIndex++; if(!slideExists(slideIndex)) slideIndex = 0; animateSlide(); }); $("#prev").on("click", function () { slideIndex--; if(!slideExists(slideIndex)) slideIndex = totalSlides-1; animateSlide(); }); ```
14,469,396
I'm trying to get download manager request working and I'm getting a strange error. Here's the code: ``` package com.vsnetworks.vswebkads; import java.io.File; import android.net.Uri; import android.os.Bundle; import android.annotation.TargetApi; import android.app.Activity; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.content.Context; import android.util.Log; @TargetApi(9) public class MainActivity extends Activity { static final String DL_STR = "downloads"; @Override public void onCreate(Bundle savedInstanceState) { Log.v("VERS TEST", "1.1"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); File externalDir = getExternalFilesDir(null); externalDir.mkdirs(); File dlDir = new File(externalDir, MainActivity.DL_STR); if (!dlDir.exists()) dlDir.mkdirs(); DownloadManager dlManager = (DownloadManager) getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse("https://www.google.com/images/srpr/logo3w.png"); //uri = Uri.parse("http://download.thinkbroadband.com/20MB.zip"); DownloadManager.Request request = new Request(uri); request.setAllowedNetworkTypes(Request.NETWORK_WIFI); request.setDestinationInExternalFilesDir(getApplicationContext(), null, "downloads/test.png"); request.setTitle("test"); dlManager.enqueue(request); } } ``` Interestingly, if I uncomment the second uri = line, the download works great and the file ends up in the directory. Which leads me to think it's that I'm trying to download via SSL that is causing the problem. However, according to these two threads ssl is supported for download manager (in comments for the first one): [Android DownloadManager and SSL (https)](https://stackoverflow.com/questions/8106155/android-downloadmanager-and-ssl-https) [android2.3 DownloadManager](https://stackoverflow.com/questions/14212339/android2-3-downloadmanager) I also don't seem to get any error telling me download manager only works with http like in the second link. Here's the error I do see: ``` 01-22 17:23:42.385: I/DownloadManager(1061): Initiating request for download 4068 01-22 17:23:42.905: I/DownloadManager(1061): Initiating request for download 4068 01-22 17:23:42.905: W/DownloadManager(1061): Aborting request for download 4068: Trying to resume a download that can't be resumed 01-22 17:23:42.905: D/DownloadManager(1061): setupDestinationFile() unable to resume download, deleting /storage/sdcard0/Android/data/com.vsnetworks.vswebkads/files/downloads/test.png 01-22 17:23:42.915: D/DownloadManager(1061): cleanupDestination() deleting /storage/sdcard0/Android/data/com.vsnetworks.vswebkads/files/downloads/test.png ``` I just updated android on my tablet today, it's sitting on version 4.1.1, so I don't think it's a version problem. So, can I do a download manager request using https, and if so, is this the correct method to do it?
2013/01/22
['https://Stackoverflow.com/questions/14469396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1756493/']
In this case, the error appears to be device related. When we switched testing to a nexus 10, the code worked and this error did not appear.
Check your server logs, sometimes the DownloadManager initiates a partial download request (which cause the misleading double log output "Initiating request for download". Your server has to handle this request properly, otherwise you get this error. See my answer for this question: [Can't resume download](https://stackoverflow.com/questions/20776833/cant-resume-download/21076744#21076744)
28,654,728
First of all, I'm not a Java programmer and I'm just modifying existing code to suit my needs so please bear with me because of my very limited knowledge in Java. This is a part of my code: ``` public String getIp() throws Exception { URL whatismyip = new URL("http://checkip.amazonaws.com"); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( whatismyip.openStream())); String ip = in.readLine(); return ip; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` Now when I try to call `getIp()`, I'm having a compilation failure: `unreported exception java.lang.Exception; must be caught or declared to be thrown`. Here's part of the code that calls the `getIp()`: ``` Phrase downloadDate = new Phrase(); downloadDate.add(new Chunk("On: " + new SimpleDateFormat("MMMM d, yyyy").format(new Date()), FONT_DATE)); downloadDate.add(new Chunk(" at " + new SimpleDateFormat("h:mm a z").format(new Date()), FONT_DATE)); Phrase downloader = new Phrase("This article was downloaded by: " + getEperson(), FONT_DATE); String IP = getIp(); Phrase userIP = new Phrase("IP Address: " + IP, FONT_DATE); Phrase userDownloadDate = new Phrase(downloadDate); Paragraph downloadDetails = new Paragraph(); downloadDetails.add(downloader); downloadDetails.add(downloadDate); downloadDetails.add(userIP); ``` This may be a trivial question to ask, but I'm wondering why I'm having the error "must be caught or declared to be thrown" when it is already declared in the `public String getIp()`?
2015/02/22
['https://Stackoverflow.com/questions/28654728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1919069/']
From the `NSBox` [documentation](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSBox_Class/#//apple_ref/occ/instm/NSBox/setFillColor:): > > **Special Considerations** > > > Functional only when the receiver’s box type (`boxType`) is `NSBoxCustom` and its border type (`borderType`) is `NSLineBorder`. > > >
set **Box Type** to **Custom** , as in the attachment: [![enter image description here](https://i.stack.imgur.com/ASB1c.png)](https://i.stack.imgur.com/ASB1c.png)
63,768,916
I'm trying to use the cvlib package which use yolov3 model to recognize objects on images on windows 10. Let's take an easy example: ``` import cvlib as cv import time from cvlib.object_detection import draw_bbox inittimer=time.time() bbox, label, conf = cv.detect_common_objects(img,confidence=0.5,model='yolov3-worker',enable_gpu=True) print('The process tooks %.3f s'%(time.time()-inittimer) output_image = draw_bbox(img, bbox, label, conf) ``` The results give ~60ms. cvlib use opencv to compute this cnn part. If now I try to see how much GPU tensorflow used, using subprocess, It tooks only 824MiB. while the program runs, if I start nvidia-smi it gives me this result: [![enter image description here](https://i.stack.imgur.com/yvAcx.png)](https://i.stack.imgur.com/yvAcx.png) As u can see there is much more memory available here. My question is simple.. why Cvlib (and so tensorflow) doesn't use all of it to improve the time's detection? EDIT: As far as I understand, cvlib use tensorflow but it also use opencv detector. I installed opencv using cmake and Cuda 10.2 I don't understand why but in the nvidia-smi it's written CUDA Version : 11.0 which is not. Maybe that's the part of the problem?
2020/09/06
['https://Stackoverflow.com/questions/63768916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13350827/']
You can verify if opencv is using CUDA or not. This can be done using the following ``` import cv2 print(cv2.cuda.getCudaEnabledDeviceCount()) ``` This should get you the number of CUDA enabled devices in your machine. You should also check the build information by using the following ``` import cv2 print cv2.getBuildInformation() ``` The output for both the above cases can indicate whether your opencv can access GPU or not. In case it doesn't access GPU then you may consider reinstallation.
``` workon opencv_cuda cd opencv mkdir build cd build cmake -D CMAKE_BUILD_TYPE=RELEASE ``` and share the result. It should be something like this [![enter image description here](https://i.stack.imgur.com/kVq5c.png)](https://i.stack.imgur.com/kVq5c.png)
63,768,916
I'm trying to use the cvlib package which use yolov3 model to recognize objects on images on windows 10. Let's take an easy example: ``` import cvlib as cv import time from cvlib.object_detection import draw_bbox inittimer=time.time() bbox, label, conf = cv.detect_common_objects(img,confidence=0.5,model='yolov3-worker',enable_gpu=True) print('The process tooks %.3f s'%(time.time()-inittimer) output_image = draw_bbox(img, bbox, label, conf) ``` The results give ~60ms. cvlib use opencv to compute this cnn part. If now I try to see how much GPU tensorflow used, using subprocess, It tooks only 824MiB. while the program runs, if I start nvidia-smi it gives me this result: [![enter image description here](https://i.stack.imgur.com/yvAcx.png)](https://i.stack.imgur.com/yvAcx.png) As u can see there is much more memory available here. My question is simple.. why Cvlib (and so tensorflow) doesn't use all of it to improve the time's detection? EDIT: As far as I understand, cvlib use tensorflow but it also use opencv detector. I installed opencv using cmake and Cuda 10.2 I don't understand why but in the nvidia-smi it's written CUDA Version : 11.0 which is not. Maybe that's the part of the problem?
2020/09/06
['https://Stackoverflow.com/questions/63768916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13350827/']
I got it! The problem come from the fact that I created a new `Net` object for each itteration. Here is the related issue on github where you can follow it: <https://github.com/opencv/opencv/issues/16348> With a custom function, it now works at ~60 fps. Be aware that cvlib is, maybe, not done for real time computation.
You can verify if opencv is using CUDA or not. This can be done using the following ``` import cv2 print(cv2.cuda.getCudaEnabledDeviceCount()) ``` This should get you the number of CUDA enabled devices in your machine. You should also check the build information by using the following ``` import cv2 print cv2.getBuildInformation() ``` The output for both the above cases can indicate whether your opencv can access GPU or not. In case it doesn't access GPU then you may consider reinstallation.
63,768,916
I'm trying to use the cvlib package which use yolov3 model to recognize objects on images on windows 10. Let's take an easy example: ``` import cvlib as cv import time from cvlib.object_detection import draw_bbox inittimer=time.time() bbox, label, conf = cv.detect_common_objects(img,confidence=0.5,model='yolov3-worker',enable_gpu=True) print('The process tooks %.3f s'%(time.time()-inittimer) output_image = draw_bbox(img, bbox, label, conf) ``` The results give ~60ms. cvlib use opencv to compute this cnn part. If now I try to see how much GPU tensorflow used, using subprocess, It tooks only 824MiB. while the program runs, if I start nvidia-smi it gives me this result: [![enter image description here](https://i.stack.imgur.com/yvAcx.png)](https://i.stack.imgur.com/yvAcx.png) As u can see there is much more memory available here. My question is simple.. why Cvlib (and so tensorflow) doesn't use all of it to improve the time's detection? EDIT: As far as I understand, cvlib use tensorflow but it also use opencv detector. I installed opencv using cmake and Cuda 10.2 I don't understand why but in the nvidia-smi it's written CUDA Version : 11.0 which is not. Maybe that's the part of the problem?
2020/09/06
['https://Stackoverflow.com/questions/63768916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13350827/']
I got it! The problem come from the fact that I created a new `Net` object for each itteration. Here is the related issue on github where you can follow it: <https://github.com/opencv/opencv/issues/16348> With a custom function, it now works at ~60 fps. Be aware that cvlib is, maybe, not done for real time computation.
``` workon opencv_cuda cd opencv mkdir build cd build cmake -D CMAKE_BUILD_TYPE=RELEASE ``` and share the result. It should be something like this [![enter image description here](https://i.stack.imgur.com/kVq5c.png)](https://i.stack.imgur.com/kVq5c.png)
58,511,850
I have the following object: ``` [{animal: 1, hasLegs: true},{animal: 1, hasTail: false}, {animal: 2, hasLegs: true},{animal: 2, hasTail: true},{animal: 3}] ``` I would like to restructure it to the following: ``` [ { animal:1, info: { hasLegs: true, hasTail: false }, { animal:2, info: { hasLegs: true, hasTail: true }, { animal:3, into: {}, ] ``` such that all objects in the array with that is `animal:1` is unified under that key and adding the remaining keys with values under the key `info`. Been trying to use the `map()`-function but can not get the hang of it, and do not know if `map()` alone can solve this.
2019/10/22
['https://Stackoverflow.com/questions/58511850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2762175/']
This is a similar answer, but should be slightly more performant since it takes advantage of map hashing instead of doing a find for each entry. ```js const data = [{animal: 1, hasLegs: true},{animal: 1, hasTail: false}, {animal: 2, hasLegs: true},{animal: 2, hasTail: true},{animal: 3}] const infoMap = data.reduce((rollup, { animal, ...info }) => { const entry = rollup[animal] = rollup[animal] || {} Object.assign(entry, info) return rollup }, {}) const result = Object.keys(infoMap) .map((animal) => ({ animal, info: infoMap[animal] })) console.log(result) ```
```js const array = [{ animal: 1, hasLegs: true }, { animal: 1, hasTail: false }, { animal: 2, hasLegs: true }, { animal: 2, hasTail: true }, { animal: 3 }]; const result = []; array.forEach(obj => { let newEntry = null; if (result.findIndex(entry => entry.animal === obj.animal) === -1) { newEntry = { animal: obj.animal, info: {} } result.push(newEntry); } const entry = newEntry || result.find(entry => entry.animal === obj.animal); Object.keys(obj).forEach(key => { if (key === 'animal') return; entry.info[key] = obj[key]; }); }); console.log(result); ```
58,511,850
I have the following object: ``` [{animal: 1, hasLegs: true},{animal: 1, hasTail: false}, {animal: 2, hasLegs: true},{animal: 2, hasTail: true},{animal: 3}] ``` I would like to restructure it to the following: ``` [ { animal:1, info: { hasLegs: true, hasTail: false }, { animal:2, info: { hasLegs: true, hasTail: true }, { animal:3, into: {}, ] ``` such that all objects in the array with that is `animal:1` is unified under that key and adding the remaining keys with values under the key `info`. Been trying to use the `map()`-function but can not get the hang of it, and do not know if `map()` alone can solve this.
2019/10/22
['https://Stackoverflow.com/questions/58511850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2762175/']
I would suggest creating a lookup object from the initial array. This way, you don't need to look through the entire array on every element (which would make it `O(n²)`). So given our list beforehand: ```js const animals = [ { animal: 1, hasLegs: true }, { animal: 1, hasTail: false }, { animal: 2, hasLegs: true }, { animal: 2, hasTail: true }, { animal: 3 } ] ``` We create a lookup table with `reduce`, merging every object that we find in the original array into the value object of the animal: ```js const lookup = animals.reduce((acc, val) => { // use object destructuring and object spread to pick out // the "animal" field and the rest into separate variables const { animal, ...info } = val // get existing info object, or create new empty if not found const existingInfo = acc[animal] || {} // merge existing info and new info from this object acc[animal] = { ...existingInfo, ...info } return acc }, {}) ``` At this point, the structure is like this: ```js { '1': { hasLegs: true, hasTail: false }, '2': { hasLegs: true, hasTail: true }, '3': {} } ``` Now we just need to go through this object and turn it into an array, and pick the key into the "animal" field: ```js const after = Object.entries(lookup).map(([key, value]) => { return { animal: key, info: value } }) ``` This produces the result we want: ```js [ { animal: '1', info: { hasLegs: true, hasTail: false } }, { animal: '2', info: { hasLegs: true, hasTail: true } }, { animal: '3', info: {} } ] ``` Note though that `Object.entries` may not be supported in older browsers. If you're targeting older browsers, check out how Robb Traister does it in his answer with `Object.keys`
```js const array = [{ animal: 1, hasLegs: true }, { animal: 1, hasTail: false }, { animal: 2, hasLegs: true }, { animal: 2, hasTail: true }, { animal: 3 }]; const result = []; array.forEach(obj => { let newEntry = null; if (result.findIndex(entry => entry.animal === obj.animal) === -1) { newEntry = { animal: obj.animal, info: {} } result.push(newEntry); } const entry = newEntry || result.find(entry => entry.animal === obj.animal); Object.keys(obj).forEach(key => { if (key === 'animal') return; entry.info[key] = obj[key]; }); }); console.log(result); ```
58,511,850
I have the following object: ``` [{animal: 1, hasLegs: true},{animal: 1, hasTail: false}, {animal: 2, hasLegs: true},{animal: 2, hasTail: true},{animal: 3}] ``` I would like to restructure it to the following: ``` [ { animal:1, info: { hasLegs: true, hasTail: false }, { animal:2, info: { hasLegs: true, hasTail: true }, { animal:3, into: {}, ] ``` such that all objects in the array with that is `animal:1` is unified under that key and adding the remaining keys with values under the key `info`. Been trying to use the `map()`-function but can not get the hang of it, and do not know if `map()` alone can solve this.
2019/10/22
['https://Stackoverflow.com/questions/58511850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2762175/']
I would suggest creating a lookup object from the initial array. This way, you don't need to look through the entire array on every element (which would make it `O(n²)`). So given our list beforehand: ```js const animals = [ { animal: 1, hasLegs: true }, { animal: 1, hasTail: false }, { animal: 2, hasLegs: true }, { animal: 2, hasTail: true }, { animal: 3 } ] ``` We create a lookup table with `reduce`, merging every object that we find in the original array into the value object of the animal: ```js const lookup = animals.reduce((acc, val) => { // use object destructuring and object spread to pick out // the "animal" field and the rest into separate variables const { animal, ...info } = val // get existing info object, or create new empty if not found const existingInfo = acc[animal] || {} // merge existing info and new info from this object acc[animal] = { ...existingInfo, ...info } return acc }, {}) ``` At this point, the structure is like this: ```js { '1': { hasLegs: true, hasTail: false }, '2': { hasLegs: true, hasTail: true }, '3': {} } ``` Now we just need to go through this object and turn it into an array, and pick the key into the "animal" field: ```js const after = Object.entries(lookup).map(([key, value]) => { return { animal: key, info: value } }) ``` This produces the result we want: ```js [ { animal: '1', info: { hasLegs: true, hasTail: false } }, { animal: '2', info: { hasLegs: true, hasTail: true } }, { animal: '3', info: {} } ] ``` Note though that `Object.entries` may not be supported in older browsers. If you're targeting older browsers, check out how Robb Traister does it in his answer with `Object.keys`
This is a similar answer, but should be slightly more performant since it takes advantage of map hashing instead of doing a find for each entry. ```js const data = [{animal: 1, hasLegs: true},{animal: 1, hasTail: false}, {animal: 2, hasLegs: true},{animal: 2, hasTail: true},{animal: 3}] const infoMap = data.reduce((rollup, { animal, ...info }) => { const entry = rollup[animal] = rollup[animal] || {} Object.assign(entry, info) return rollup }, {}) const result = Object.keys(infoMap) .map((animal) => ({ animal, info: infoMap[animal] })) console.log(result) ```
70,713,408
How do I select/copy info from web with Selenium and copy into IntelliJ to String? I'm using IntelliJ in Java. I am trying to use: ``` Navegador.getInstance().instanciaNavegador().findElement(By.xpath("//div[@id='cpf']/span[2]")).sendKeys(Keys.chord(Keys.CONTROL, "v")); ```
2022/01/14
['https://Stackoverflow.com/questions/70713408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17934597/']
As [Kraigolas commented](https://stackoverflow.com/questions/70713383/for-loop-to-replace-value-in-one-dataframe-with-x-if-it-appears-in-another-dataf#comment125009505_70713383), you can easily do this without looping. Check if elements are in another array with [`np.in1d`](https://numpy.org/doc/stable/reference/generated/numpy.in1d.html) and then map truth values to "X" and "Y": ``` import pandas as pd import numpy as np df1 = pd.DataFrame() df1["col1"] = ["A", "B", "C", "D", "E"] df2 = pd.DataFrame() df2["col2"] = ["A", "C", "D"] df1["col3"] = list(map(lambda x: "X" if x else "Y", np.in1d(df1.col1, df2.col2))) print(df1) ``` Output: ``` col1 col3 0 A X 1 B Y 2 C X 3 D X 4 E Y ```
Given question with `dataframe` in title, variables `df1` and `df2` together with `col1` and `col2` probably is related to [pandas](/questions/tagged/pandas "show questions tagged 'pandas'") or [numpy](/questions/tagged/numpy "show questions tagged 'numpy'"). Without any further context provided, like code, we can only recommend vague options but not help with a specific solution. Functions from Numpy, Pandas and Python built-in ------------------------------------------------ Following are some functions in the solution space: 1. element is in other collection: `numpy.in1d` (explained below), [`pandas.Series.isin`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html), [`set & other` or `set.intersection()`](https://docs.python.org/3/library/stdtypes.html?highlight=set%20intersection#frozenset.intersection) 2. map boolean to string or character: `numpy.where` (explained below), [`pandas.Series.where`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html), [`map`](https://docs.python.org/3/library/functions.html?highlight=map%20function#map) ### Value in 1-D array (exists / present / duplicated) See numpy's [`in1d(ar1, ar2, assume_unique=False, invert=False)`](https://numpy.org/doc/stable/reference/generated/numpy.in1d.html) function: > > Test whether each element of a 1-D array is also present in a second array. > > > ```py import numpy as np array_1 = np.array(['A', 'B', 'C']) print(array_1) # ['A' 'B' 'C'] array_1_elements_exist = np.in1d(array_1, ['C', 'D']) print(array_1_elements_exist) # [False False True] ``` ### Map to either X or Y (binary classification) The mapping can be done using Python's built-in [`map(mapping_function, array_or_list)`](https://www.w3schools.com/python/ref_func_map.asp) as [answered by rikyeah](https://stackoverflow.com/a/70714258/5730279). Or directly use numpy's [`where(condition, [x, y, ])`](https://numpy.org/doc/stable/reference/generated/numpy.where.html) > > Return elements chosen from x or y depending on condition. > > > to map binary values (in statistics this is called [*binary classification*](https://en.wikipedia.org/wiki/Statistical_classification#Binary_and_multiclass_classification)): ```py import numpy as np array_bool = np.array([True, False]) print(array_bool) # array([ True, False]) array_str = np.where(array_bool, 'x', 'y') print(array_bool) # array(['x', 'y'], dtype='|S1') ``` Comparing two dataframes? (missing context for specific application) -------------------------------------------------------------------- As the question hasn't shown a reproducible example yet, it is unclear how the combined functionality can be applied in context. Until some [example](https://stackoverflow.com/help/minimal-reproducible-example) is provided in given question, the combination of both functions is left open. Example applications of these functions to *pandas* are: * [python: check if an numpy array contains any element of another array](https://stackoverflow.com/questions/36190533/python-check-if-an-numpy-array-contains-any-element-of-another-array/36190611#36190611) * [Difference between pandas DataFrame 'where' and Numpy 'where'](https://stackoverflow.com/questions/44893381/difference-between-pandas-dataframe-where-and-numpy-where) * [comparing two DataFrames, specific questions](https://stackoverflow.com/questions/44273037/comparing-two-dataframes-specific-questions) Or in built-in Python: * Python docs [intersection](https://docs.python.org/3/library/stdtypes.html?highlight=set%20intersection#frozenset.intersection) * [using a conditional and lambda in map](https://stackoverflow.com/questions/31153002/using-a-conditional-and-lambda-in-map)
40,620
I have a Visualforce page to collect the Name and Email of clients. My Visualforce page looks like this: ``` <apex:page Controller="WebsiteController" > <apex:sectionHeader title="Registration" subtitle="Please fill in the details"/> <apex:form > <apex:pageMessages /> <apex:pageBlock title="Email updates"> <apex:pageBlockButtons > <apex:commandButton action="{!submit}" value="Submit"/> <apex:commandButton action="{!reset}" value="Reset"/> </apex:pageBlockButtons> <apex:pageBlockSection > //here is my problem: the page shows an input field for email, but not name <apex:inputField value="{!contact.Name}" required="true"/> <apex:inputField value="{!contact.Email}" required="true"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> ``` I have no idea why one input field is shown and the other is not - I am probably missing a small detail.
2014/06/16
['https://salesforce.stackexchange.com/questions/40620', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/8737/']
`LargestRevision.size()` will never return `null`. The `size()` method will return `0` if the list is empty. From the [documentation](https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_list.htm): > > **size()** > > Returns the number of elements in the list. > > > **Signature** > > `public Integer size()` > > > **Return Value** > > Type: Integer > > > **Example** > > > > ``` > List<Integer> myList = new List<Integer>(); > Integer size = myList.size(); > system.assertEquals(size, 0); > > List<Integer> myList2 = new Integer[6]; > Integer size2 = myList2.size(); > system.assertEquals(size2, 6); > > ``` > > Changing to the following should resolve this: ``` if(LargestRevision.size() > 0) { clonedQuteLink.Revision_Number__c=LargestRevision.get(0).Revision_Number__c+1; clonedQuteLink.Quote_Link__c = quoteLink.Quote_Link__c; } ```
You should replace the first part of the if with ``` if(LargestRevision!=null and LargestRevision.size()!=0){ clonedQuteLink.Revision_Number__c=LargestRevision.get(0).Revision_Number__c+1; clonedQuteLink.Quote_Link__c = quoteLink.Quote_Link__c; } ``` because if LargestRevision is null (no values found) then you cannot call .size() on a null
69,084,365
I'm using the below code to open an URL. Downloading a PDF from React native webview after opening on Android gives: > > "invaild pdf format or corrupted" > > > but it works fine on iOS. ``` <WebView renderToHardwareTextureAndroid={true} startInLoadingState={isLoading} renderLoading={() => { return <BarIndicator color="blue" />; }} mediaPlaybackRequiresUserAction={false} javaScriptEnabled={true} source={{ uri: webviewUrl, headers: webviewHeaders, }} style={drawerWebviewStyles.container} /> ```
2021/09/07
['https://Stackoverflow.com/questions/69084365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16477546/']
If you want full control over subscriptions, you can create a custom `Publisher` and `Subscription`. `Publisher`'s `func receive<S: Subscriber>(subscriber: S)` method is the one that gets called when the publisher receives a new subscriber. If you simply want to make a network request when this happens, you just need to create a custom `Publisher` and return a `Future` that wraps the network request from this method. In general, you should use `Future` for one-off async events, `PassthroughSubject` is not the ideal `Publisher` to use for network requests.
You can handle publisher events and inject side effect to track subscriptions, like ``` class LoginService { static func generateLoginPublisher(onSubscription: @escaping (Subscription) -> Void) -> AnyPublisher<Client, NetworkError> { return PassthroughSubject<Client, NetworkError>() .handleEvents(receiveSubscription: onSubscription, receiveOutput: nil, receiveCompletion: nil, receiveCancel: nil, receiveRequest: nil) .eraseToAnyPublisher() } } ``` so ``` loginPublisher = LoginService.generateLoginPublisher() { subscription in // do anything needed here when on new subscription appeared } ```
69,084,365
I'm using the below code to open an URL. Downloading a PDF from React native webview after opening on Android gives: > > "invaild pdf format or corrupted" > > > but it works fine on iOS. ``` <WebView renderToHardwareTextureAndroid={true} startInLoadingState={isLoading} renderLoading={() => { return <BarIndicator color="blue" />; }} mediaPlaybackRequiresUserAction={false} javaScriptEnabled={true} source={{ uri: webviewUrl, headers: webviewHeaders, }} style={drawerWebviewStyles.container} /> ```
2021/09/07
['https://Stackoverflow.com/questions/69084365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16477546/']
I finally solved my problem using `Future` instead of `PassthroughtSubject` as Dávid Pásztor suggested. Using `Future` I don't have to worried about `LoginService.login()` logic finish before I create `loginSubscriber`. `LoginSevice.login()` method: ``` static func login(_ email: String,_ password: String) -> Future<Client, NetworkError>{ return Future<Client, NetworkError>{ completion in let url = NetworkBuilder.getApiUrlWith(extraPath: "login") print(url) let parameters: [String: String] = [ "password": password, "login": email ] print(parameters) let request = AF.request( url, method: .post, parameters: parameters, encoder: JSONParameterEncoder.default ) request.validate(statusCode: 200...299) request.responseDecodable(of: Client.self) { response in if let loginResponse = response.value{//Success completion(.success(loginResponse)) } else{//Failure completion(.failure(NetworkError.thingsJustHappen)) } } } } ``` Implementation: ``` loginSubscriber = LoginService.login(email, password) .sink { error in print("Something bad happened") self.isLoading = false } receiveValue: { value in self.saveClient(value) self.client = (value) self.isLoading = false } ```
You can handle publisher events and inject side effect to track subscriptions, like ``` class LoginService { static func generateLoginPublisher(onSubscription: @escaping (Subscription) -> Void) -> AnyPublisher<Client, NetworkError> { return PassthroughSubject<Client, NetworkError>() .handleEvents(receiveSubscription: onSubscription, receiveOutput: nil, receiveCompletion: nil, receiveCancel: nil, receiveRequest: nil) .eraseToAnyPublisher() } } ``` so ``` loginPublisher = LoginService.generateLoginPublisher() { subscription in // do anything needed here when on new subscription appeared } ```
69,084,365
I'm using the below code to open an URL. Downloading a PDF from React native webview after opening on Android gives: > > "invaild pdf format or corrupted" > > > but it works fine on iOS. ``` <WebView renderToHardwareTextureAndroid={true} startInLoadingState={isLoading} renderLoading={() => { return <BarIndicator color="blue" />; }} mediaPlaybackRequiresUserAction={false} javaScriptEnabled={true} source={{ uri: webviewUrl, headers: webviewHeaders, }} style={drawerWebviewStyles.container} /> ```
2021/09/07
['https://Stackoverflow.com/questions/69084365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16477546/']
If you want full control over subscriptions, you can create a custom `Publisher` and `Subscription`. `Publisher`'s `func receive<S: Subscriber>(subscriber: S)` method is the one that gets called when the publisher receives a new subscriber. If you simply want to make a network request when this happens, you just need to create a custom `Publisher` and return a `Future` that wraps the network request from this method. In general, you should use `Future` for one-off async events, `PassthroughSubject` is not the ideal `Publisher` to use for network requests.
I finally solved my problem using `Future` instead of `PassthroughtSubject` as Dávid Pásztor suggested. Using `Future` I don't have to worried about `LoginService.login()` logic finish before I create `loginSubscriber`. `LoginSevice.login()` method: ``` static func login(_ email: String,_ password: String) -> Future<Client, NetworkError>{ return Future<Client, NetworkError>{ completion in let url = NetworkBuilder.getApiUrlWith(extraPath: "login") print(url) let parameters: [String: String] = [ "password": password, "login": email ] print(parameters) let request = AF.request( url, method: .post, parameters: parameters, encoder: JSONParameterEncoder.default ) request.validate(statusCode: 200...299) request.responseDecodable(of: Client.self) { response in if let loginResponse = response.value{//Success completion(.success(loginResponse)) } else{//Failure completion(.failure(NetworkError.thingsJustHappen)) } } } } ``` Implementation: ``` loginSubscriber = LoginService.login(email, password) .sink { error in print("Something bad happened") self.isLoading = false } receiveValue: { value in self.saveClient(value) self.client = (value) self.isLoading = false } ```
170,161
We had wooden Marvin double hung tilt-pac windows installed but all without screens. However, there aren't any screen tracks. On the exterior trim, there is a groove/corner on three sides that would fit a screen (~36x54.5) , but it would have to be secured with hardware somehow. And this trim corner does not extend to the bottom sill - rather, the bottom sill is sloped down and smooth. I attached a picture of the lower corner to see where the screen would fit - I am pointing to the relevant corner where I thought I could fit in the screen. How do I secure a screen to the trim without a screen track and without letting water into the trim/sill? I am worried about screwing things into the wood and letting water in. [![window sill and trim area to fit a screen](https://i.stack.imgur.com/jFQTX.jpg)](https://i.stack.imgur.com/jFQTX.jpg)
2019/07/30
['https://diy.stackexchange.com/questions/170161', 'https://diy.stackexchange.com', 'https://diy.stackexchange.com/users/89457/']
It does look like that a screen could fit where you're pointing. I've included a picture of some screen hangers and a lock.[![enter image description here](https://i.stack.imgur.com/KLBnJ.jpg)](https://i.stack.imgur.com/KLBnJ.jpg) The hangers would go on the top of the screen and trim allowing the screen to be lifted into your trim track. The locking device would be screwed into the center of the sill and mounted to hold the screen securely into the trim. Any water that accumulated during rain would be able to run under the screen. The hardware would be permanently attacked to the upper frame, screen and sill so it could be caulked and sealed to prevent any water from migrating into the wood.
Typical approach for modern screens/windows (as Jack has shown the very vintage approach) is that the screen has a frame (typically aluminum) that has springs on one side or two sides so it can be fitted into the slot by compressing the springs, and when released is held in the slot by spring pressure. The sill is "trackless" so it won't trap water and create a problem. The screen frame being held in by the side grooves seals it well enough if it's properly fitted.
48,005,916
I want to try add background image through url But image is not showing. Here what am I using. ```html <div style="background-image:url(https://i.amz.mshcdn.com/pr8NZRyZf0Kmz4FSGMkLtxUwZ70=/575x323/filters:quality(90)/https%3A%2F%2Fblueprint-api-production.s3.amazonaws.com%2Fuploads%2Fstory%2Fthumbnail%2F65469%2F23ede933-7d84-40fb-a9ee-eb7787a3feac.jpg);">content goes here...</div> ``` I checked url is working if you copy and past url in browser you will see image. Then why it's not showing in background. One of my wordpress site automatically fetch url for background image. Please let me know how can I solve this.
2017/12/28
['https://Stackoverflow.com/questions/48005916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9148852/']
You need to add quotes. In most of the cases it's not mandatory but in your case, it's needed as you have some special characters that can create confusion. For example, You have a closing `)` inside the URL which made it to be closed before the end. ```html <div style="background-image:url('https://i.amz.mshcdn.com/pr8NZRyZf0Kmz4FSGMkLtxUwZ70=/575x323/filters:quality(90)/https%3A%2F%2Fblueprint-api-production.s3.amazonaws.com%2Fuploads%2Fstory%2Fthumbnail%2F65469%2F23ede933-7d84-40fb-a9ee-eb7787a3feac.jpg');height:200px;">content goes here...</div> ``` **UPDATE** As you are not able to add quotes in the URL (because it's generated automatically with wordpress). Here is a jQuery solution that will add the quotes for you. (but you need to be able to target only this div). ```js //change the selector to get only the needed DIV var sel = $('div') var url = sel.attr('style'); url = url.replace("url(","url('"); //add the first quote url = url.replace("jpg)","jpg')"); //add the last quote sel.attr('style',url); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="background-image:url(https://i.amz.mshcdn.com/pr8NZRyZf0Kmz4FSGMkLtxUwZ70=/575x323/filters:quality(90)/https%3A%2F%2Fblueprint-api-production.s3.amazonaws.com%2Fuploads%2Fstory%2Fthumbnail%2F65469%2F23ede933-7d84-40fb-a9ee-eb7787a3feac.jpg);height:200px;">content goes here...</div> ``` *This method is not generic and will only work in this case, so you may update the code in other situation*
See the [specification](https://www.w3.org/TR/CSS2/syndata.html#uri): > > Some characters appearing in an unquoted URI, such as parentheses, white space characters, single quotes (') and double quotes ("), must be escaped with a backslash so that the resulting URI value is a URI token: '(', ')'. > > > Either: * escape those characters * use a quoted `url()` (example below) * use URLs without those characters in ```html <div style="background-image:url('https://i.amz.mshcdn.com/pr8NZRyZf0Kmz4FSGMkLtxUwZ70=/575x323/filters:quality(90)/https%3A%2F%2Fblueprint-api-production.s3.amazonaws.com%2Fuploads%2Fstory%2Fthumbnail%2F65469%2F23ede933-7d84-40fb-a9ee-eb7787a3feac.jpg');">content goes here...</div> ```
57,924,568
Need help for the below problem. How to use loop function to find the number of 'Null' values in each column for a data frame. Thanks Example: `df<-data.frame(name=c("Patrik","Tom","Harry","Bose"), Age=c(45,NA,54,34), Location=c("NA","CA",NA,"IR"))`
2019/09/13
['https://Stackoverflow.com/questions/57924568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10045435/']
Ok, regarding your second code snippet there are several things that I noticed. You are using the cookie-parser package that you affected to the cookieParser variable but after you use `Cookies.get` but I don't see where `Cookies` is coming from? so maybe what you want to do is `cookieParser.get` but by checking the cookie-parser package I didn't see any `get` method so it's hard to help you here. Other than that you should be able to see your cookies by using `req.cookies` inside your function. I hope it will help you a bit...
Let me say you that if you want to store a JWT into a cookie and other extra information it could be stored or not depending on the size of your cookie. For more information about max size for cookies check this: <https://www.quora.com/What-Is-The-Maximum-Size-Of-Cookie-In-A-Web-Browser> On another hand, I saw a problem in your implementation that I recommend you the below: If you are receiving a JWT, you would keep the nature of a JWT authenticator. <https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e>
12,941,564
Thanks for all the help so far. I was able to send the $Email variable to the stdio stream and receive it in the vb script. I am having a problem now with some of the code ``` Option Strict On Imports MySql.Data.MySqlClient Imports System.Runtime.Serialization Module jrConnect Sub Main(ByVal cmdArgs() As String) Dim returnValue As Integer = 0 ' See if there are any arguments. If cmdArgs.Length > 0 Then For argNum As Integer = 0 To UBound(cmdArgs, 1) Console.Write("your email address is " & cmdArgs(argNum)) If cmdArgs(argNum) <> "" Then Dim email As String = cmdArgs(argNum) Console.Write("Your email is " & email) End If Next argNum End If Dim cs As String = "*********" Dim conn As New MySqlConnection(cs) Dim entID As String Try conn.Open() Dim stm As String = "SELECT ***** FROM **** WHERE email =" & "'" & email & "'" Dim cmd As MySqlCommand = New MySqlCommand(stm, conn) Dim reader As MySqlDataReader = cmd.ExecuteReader() While reader.Read() entID = reader.GetString(0) End While reader.Close() Dim stm2 = "SELECT ***** FROM ****** WHERE ***** = " & entID Dim cmd2 As MySqlCommand = New MySqlCommand(stm2, conn) Dim reader2 As MySqlDataReader = cmd2.ExecuteReader() Dim counter As Integer = 0 While reader2.Read() And counter < 3 Console.WriteLine(reader2.GetString(0) & "%") counter = counter + 1 End While reader.Close() Catch ex As MySqlException Finally conn.Close() End Try End Sub End Module ``` It will print the email address correctly but when it calls the email address in the sql statement it states that "email is not declared" Is it changing the value of it in the "Next argNum" command? It only writes the email to console once. Here is my NSIS script if necessary as well. ``` Outfile "test.exe" Section SetOutPath $DOCUMENTS/ Var /GLOBAL Email StrCpy $Email "[email protected]" nsExec::ExecToLog '"C:path/vbapp.exe" $Email' Pop $1 Pop $2 DetailPrint $1 DetailPrint $2 SectionEnd ```
2012/10/17
['https://Stackoverflow.com/questions/12941564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1748297/']
From the NSIS manual: ``` nsExec will execute command-line based programs and capture the output without opening a dos box ``` Your `console.Readline` will expect some kind of interation and since its not connected to stdin/stdout, will fail. Since you dont want the DOS box, and you want to send the email string via stdin rather than enter it manually, use `ExecDos::exec` ``` ExecDos::exec /TIMEOUT=2000 "$DOCUMENTS\VBApp.exe" "$Email$\n" ``` Note the `$` in front of `\n` for NSIS to send a literal new line rather than the string `\n`
You are trying to read from stdin but nsExec does not provide any data you can read from stdin. Change the VB program to parse the commandline instead or use [ExecDos](http://nsis.sourceforge.net/ExecDos_plug-in) or [ExecCmd](http://nsis.sourceforge.net/ExecCmd_plug-in) if your child process has to get the data from stdin...
10,903,013
I have an xml document that looks like this: ``` <oldEle userlabel="label1"> <ele1>%02d.jpeg</ele1> </oldEle> <oldEle userlabel="label2"> <ele1>%02d.tiff</ele1> </oldEle> ``` I want it to be this: ``` <JPEG userlabel="label1"> <ele1>%02d.jpeg</ele1> </JPEG> <TIFF userlabel="label2"> <ele1>%02d.tiff</ele1> </TIFF> ``` I've tried this. ``` <xsl:template match="//xmlns:oldNode[contains(//xmlsns:oldNode/root:ele1, '.')]"> <xsl:element name="{translate(substring-after(//xmlns:ele1, '.'), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> ``` but only get the first of the file ext. e.g. if jpeg is first, I would get for both of the nodes. Could someone offer expertise advice on why this is not working. BTW, I also tried this but same thing happened: ``` <xsl:template match="//xmlns:oldNode[contains(//root:ele1, '.jpeg')]"> <xsl:element name="JPEG"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="//xmlns:oldNode[contains(//root:ele1, '.tiff')]"> <xsl:element name="TIFF"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> ```
2012/06/05
['https://Stackoverflow.com/questions/10903013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1140072/']
``` <xsl:template match="oldNode"> <xsl:choose> <xsl:when test="contains(ele1,'.jpeg')"> <xsl:element name="JPEG"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:when> <xsl:when test="contains(ele1,'.tiff')"> <xsl:element name="TIFF"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:when> </xsl:choose> </xsl:template> ```
**Here is the same answer as to your previous question -- this solves completely the old and the current problem and no recursion is used**: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <my:suffixes> <s>jpeg</s><s>JPEG</s> <s>tiff</s><s>TIFF</s> <s>giv</s><s>GIV</s> <s>png</s><s>PNG</s> </my:suffixes> <xsl:variable name="vSufs" select="document('')/*/my:suffixes/s"/> <xsl:template match="node()|@*" name="identity"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:variable name="vSufFound" select= "$vSufs[position() mod 2 = 1] [substring(translate(current()/ele1, ., ''), string-length(translate(current()/ele1, ., '')) ) = '.' ]"/> <xsl:choose> <xsl:when test="not($vSufFound)"> <xsl:call-template name="identity"/> </xsl:when> <xsl:otherwise> <xsl:element name="{$vSufFound/following-sibling::s[1]}"> <xsl:apply-templates select="node()|@*"/> </xsl:element> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ``` **When this transformation is applied on the provided XML document, the wanted, correct result is produced:** ``` <t> <JPEG userlabel="label1"> <ele1>%02d.jpeg</ele1> </JPEG> <TIFF userlabel="label2"> <ele1>%02d.tiff</ele1> </TIFF> </t> ``` **Explanation**: In this transformation we are using the following XPath 1.0 expression to implement the standard XPath 2.0 `ends-with($t, $suf)` function: ``` $suf = substring($t, string-length($t) - string-length($suf) +1) ```
10,903,013
I have an xml document that looks like this: ``` <oldEle userlabel="label1"> <ele1>%02d.jpeg</ele1> </oldEle> <oldEle userlabel="label2"> <ele1>%02d.tiff</ele1> </oldEle> ``` I want it to be this: ``` <JPEG userlabel="label1"> <ele1>%02d.jpeg</ele1> </JPEG> <TIFF userlabel="label2"> <ele1>%02d.tiff</ele1> </TIFF> ``` I've tried this. ``` <xsl:template match="//xmlns:oldNode[contains(//xmlsns:oldNode/root:ele1, '.')]"> <xsl:element name="{translate(substring-after(//xmlns:ele1, '.'), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> ``` but only get the first of the file ext. e.g. if jpeg is first, I would get for both of the nodes. Could someone offer expertise advice on why this is not working. BTW, I also tried this but same thing happened: ``` <xsl:template match="//xmlns:oldNode[contains(//root:ele1, '.jpeg')]"> <xsl:element name="JPEG"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="//xmlns:oldNode[contains(//root:ele1, '.tiff')]"> <xsl:element name="TIFF"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> ```
2012/06/05
['https://Stackoverflow.com/questions/10903013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1140072/']
The first problem is with your matching template ``` <xsl:template match="//xmlns:oldNode[contains(//xmlsns:oldNode/root:ele1, '.')]"> ``` In particular, with the **contains** element you probably don't want the `//oldNode` at the front, as this will start looking for the first **oldNode** relative to the root element. What you really want is to look for the **ele1** element relative to the element you have currently matched ``` <xsl:template match="//oldNode[contains(ele1, '.')]"> ``` (I am not sure if you mean **oldNode** or **oldEle** by the way. I am also not sure where your namespaces fit in, so I have not shown them here). The second problem is with the **xsl:element**, as you are doing a similar thing here ``` <xsl:element name="{translate(substring-after(//xmlns:ele1, '.'), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')}"> ``` Because of the `//` in the **substring-after**, it will pick up the first **ele1** relative to the root element of the XML, and not the one relative to your current element. You probably need to do this ``` <xsl:element name="{translate(substring-after(ele1, '.'), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')}"> ``` Try this template instead ``` <xsl:template match="//oldNode[contains(ele1, '.')]"> <xsl:element name="{translate(substring-after(//ele1, '.'), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> ``` Similarly, for you second set of templates, you should be doing something like this ``` <xsl:template match="//oldNode[contains(ele1, '.jpeg')]"> ```
**Here is the same answer as to your previous question -- this solves completely the old and the current problem and no recursion is used**: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <my:suffixes> <s>jpeg</s><s>JPEG</s> <s>tiff</s><s>TIFF</s> <s>giv</s><s>GIV</s> <s>png</s><s>PNG</s> </my:suffixes> <xsl:variable name="vSufs" select="document('')/*/my:suffixes/s"/> <xsl:template match="node()|@*" name="identity"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:variable name="vSufFound" select= "$vSufs[position() mod 2 = 1] [substring(translate(current()/ele1, ., ''), string-length(translate(current()/ele1, ., '')) ) = '.' ]"/> <xsl:choose> <xsl:when test="not($vSufFound)"> <xsl:call-template name="identity"/> </xsl:when> <xsl:otherwise> <xsl:element name="{$vSufFound/following-sibling::s[1]}"> <xsl:apply-templates select="node()|@*"/> </xsl:element> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ``` **When this transformation is applied on the provided XML document, the wanted, correct result is produced:** ``` <t> <JPEG userlabel="label1"> <ele1>%02d.jpeg</ele1> </JPEG> <TIFF userlabel="label2"> <ele1>%02d.tiff</ele1> </TIFF> </t> ``` **Explanation**: In this transformation we are using the following XPath 1.0 expression to implement the standard XPath 2.0 `ends-with($t, $suf)` function: ``` $suf = substring($t, string-length($t) - string-length($suf) +1) ```
2,295,660
What is the best way to capture video in a WPF application? I am looking for a way to detect the video devices, and then capture video from the selected one.
2010/02/19
['https://Stackoverflow.com/questions/2295660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66071/']
There is no WPF support for this. You need to use the traditional, expected windows APIs for video capture, such as DXVA.
If you are OK with using ActiveX controls in WPF app, you can use VideoCapX from <http://www.fathsoft.com/videocapx.html>
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
If you use Python, [`email.parser.Parser`](http://docs.python.org/library/email.parser.html#parser-class-api) will allow you to parse a multipart MIME document.
This may be a crazy idea, but I would try stripping the headers with procmail.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
If you use Python, [`email.parser.Parser`](http://docs.python.org/library/email.parser.html#parser-class-api) will allow you to parse a multipart MIME document.
This probably contains some typos or something, but bear with me anyway. First determine the boundary (`input` is the file containing the data - pipe if necessary): ``` boundary=`grep '^Content-Type: multipart/form-data; boundary=' input|sed 's/.*boundary=//'` ``` Then filter the `Filedata` part: ``` fd='Content-Disposition: form-data; name="Filedata"' sed -n "/$fd/,/$boundary/p" ``` The last part is filter a few extra lines - header lines before and including the empty line and the boundary itself, so change the last line from previous to: ``` sed -n "/$fd/,/$boundary/p" | sed '1,/^$/d' | sed '$d' ``` * `sed -n "/$fd/,/$boundary/p"` filters the lines between the `Filedata` header and the boundary (inclusive), * `sed '1,/^$/d'` is deleting everything up to and including the first line (so removes the headers) and * `sed '$d'` removes the last line (the boundary). After this, you wait for Dennis (see comments) to optimize it and you get this: ``` sed "1,/$fd/d;/^$/d;/$boundary/,$d" ``` Now that you've come here, scratch all this and do what Ignacio suggested. Reason - this probably won't work (reliably) for this, as GIF is binary data. Ah, it was a good exercise! Anyway, for the lovers of `sed`, here's the excellent page: * <http://sed.sourceforge.net/sed1line.txt> Outstanding information.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
If you use Python, [`email.parser.Parser`](http://docs.python.org/library/email.parser.html#parser-class-api) will allow you to parse a multipart MIME document.
Look at the [Mime::Tools suite](http://search.cpan.org/perldoc?MIME%3a%3aTools) for Perl. It has a rich set of classes; I’m sure you could put something together in just a few lines.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
You want to do this as the file is going over, or is this something you want to do after the file comes over? Almost any scripting language should work. My AWK is a bit rusty, but... ``` awk '/^Content-Type: application\/octet-stream/,/^--------/' ``` That should print everything between `application/octet-stream` and the `----------` lines. It might also include both those lines too which means you'll have to do something a bit more complex: ``` BEGIN {state = 0} { if ($0 ~ /^------------/) { state = 0; } if (state == 1) { print $0 } if ($0 ~ /^Content-Type: application\/octet-stream/) { state = 1; } } ``` The `application\/octet-stream` line is after the print statement because you want to set `state` to `1` after you see `application/octet-stream`. Of course, being Unix, you could pipe the output of your program through awk and then save the file.
If you use Python, [`email.parser.Parser`](http://docs.python.org/library/email.parser.html#parser-class-api) will allow you to parse a multipart MIME document.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
This may be a crazy idea, but I would try stripping the headers with procmail.
This probably contains some typos or something, but bear with me anyway. First determine the boundary (`input` is the file containing the data - pipe if necessary): ``` boundary=`grep '^Content-Type: multipart/form-data; boundary=' input|sed 's/.*boundary=//'` ``` Then filter the `Filedata` part: ``` fd='Content-Disposition: form-data; name="Filedata"' sed -n "/$fd/,/$boundary/p" ``` The last part is filter a few extra lines - header lines before and including the empty line and the boundary itself, so change the last line from previous to: ``` sed -n "/$fd/,/$boundary/p" | sed '1,/^$/d' | sed '$d' ``` * `sed -n "/$fd/,/$boundary/p"` filters the lines between the `Filedata` header and the boundary (inclusive), * `sed '1,/^$/d'` is deleting everything up to and including the first line (so removes the headers) and * `sed '$d'` removes the last line (the boundary). After this, you wait for Dennis (see comments) to optimize it and you get this: ``` sed "1,/$fd/d;/^$/d;/$boundary/,$d" ``` Now that you've come here, scratch all this and do what Ignacio suggested. Reason - this probably won't work (reliably) for this, as GIF is binary data. Ah, it was a good exercise! Anyway, for the lovers of `sed`, here's the excellent page: * <http://sed.sourceforge.net/sed1line.txt> Outstanding information.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
You want to do this as the file is going over, or is this something you want to do after the file comes over? Almost any scripting language should work. My AWK is a bit rusty, but... ``` awk '/^Content-Type: application\/octet-stream/,/^--------/' ``` That should print everything between `application/octet-stream` and the `----------` lines. It might also include both those lines too which means you'll have to do something a bit more complex: ``` BEGIN {state = 0} { if ($0 ~ /^------------/) { state = 0; } if (state == 1) { print $0 } if ($0 ~ /^Content-Type: application\/octet-stream/) { state = 1; } } ``` The `application\/octet-stream` line is after the print statement because you want to set `state` to `1` after you see `application/octet-stream`. Of course, being Unix, you could pipe the output of your program through awk and then save the file.
This may be a crazy idea, but I would try stripping the headers with procmail.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
Look at the [Mime::Tools suite](http://search.cpan.org/perldoc?MIME%3a%3aTools) for Perl. It has a rich set of classes; I’m sure you could put something together in just a few lines.
This probably contains some typos or something, but bear with me anyway. First determine the boundary (`input` is the file containing the data - pipe if necessary): ``` boundary=`grep '^Content-Type: multipart/form-data; boundary=' input|sed 's/.*boundary=//'` ``` Then filter the `Filedata` part: ``` fd='Content-Disposition: form-data; name="Filedata"' sed -n "/$fd/,/$boundary/p" ``` The last part is filter a few extra lines - header lines before and including the empty line and the boundary itself, so change the last line from previous to: ``` sed -n "/$fd/,/$boundary/p" | sed '1,/^$/d' | sed '$d' ``` * `sed -n "/$fd/,/$boundary/p"` filters the lines between the `Filedata` header and the boundary (inclusive), * `sed '1,/^$/d'` is deleting everything up to and including the first line (so removes the headers) and * `sed '$d'` removes the last line (the boundary). After this, you wait for Dennis (see comments) to optimize it and you get this: ``` sed "1,/$fd/d;/^$/d;/$boundary/,$d" ``` Now that you've come here, scratch all this and do what Ignacio suggested. Reason - this probably won't work (reliably) for this, as GIF is binary data. Ah, it was a good exercise! Anyway, for the lovers of `sed`, here's the excellent page: * <http://sed.sourceforge.net/sed1line.txt> Outstanding information.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
You want to do this as the file is going over, or is this something you want to do after the file comes over? Almost any scripting language should work. My AWK is a bit rusty, but... ``` awk '/^Content-Type: application\/octet-stream/,/^--------/' ``` That should print everything between `application/octet-stream` and the `----------` lines. It might also include both those lines too which means you'll have to do something a bit more complex: ``` BEGIN {state = 0} { if ($0 ~ /^------------/) { state = 0; } if (state == 1) { print $0 } if ($0 ~ /^Content-Type: application\/octet-stream/) { state = 1; } } ``` The `application\/octet-stream` line is after the print statement because you want to set `state` to `1` after you see `application/octet-stream`. Of course, being Unix, you could pipe the output of your program through awk and then save the file.
This probably contains some typos or something, but bear with me anyway. First determine the boundary (`input` is the file containing the data - pipe if necessary): ``` boundary=`grep '^Content-Type: multipart/form-data; boundary=' input|sed 's/.*boundary=//'` ``` Then filter the `Filedata` part: ``` fd='Content-Disposition: form-data; name="Filedata"' sed -n "/$fd/,/$boundary/p" ``` The last part is filter a few extra lines - header lines before and including the empty line and the boundary itself, so change the last line from previous to: ``` sed -n "/$fd/,/$boundary/p" | sed '1,/^$/d' | sed '$d' ``` * `sed -n "/$fd/,/$boundary/p"` filters the lines between the `Filedata` header and the boundary (inclusive), * `sed '1,/^$/d'` is deleting everything up to and including the first line (so removes the headers) and * `sed '$d'` removes the last line (the boundary). After this, you wait for Dennis (see comments) to optimize it and you get this: ``` sed "1,/$fd/d;/^$/d;/$boundary/,$d" ``` Now that you've come here, scratch all this and do what Ignacio suggested. Reason - this probably won't work (reliably) for this, as GIF is binary data. Ah, it was a good exercise! Anyway, for the lovers of `sed`, here's the excellent page: * <http://sed.sourceforge.net/sed1line.txt> Outstanding information.
4,236,020
I have a program that accepts HTTP post of files and write all the POST result into a file, I want to write a script to delete the HTTP headers, only leave the binary file data, how to do it? The file content is below (the data between `Content-Type: application/octet-stream` and `------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3` is what I want: ``` POST /?user_name=vvvvvvvv&size=837&file_name=logo.gif& HTTP/1.1^M Accept: text/*^M Content-Type: multipart/form-data; boundary=----------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M User-Agent: Shockwave Flash^M Host: 192.168.0.198:9998^M Content-Length: 1251^M Connection: Keep-Alive^M Cache-Control: no-cache^M Cookie: cb_fullname=ddddddd; cb_user_name=cdc^M ^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filename"^M ^M logo.gif^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Filedata"; filename="logo.gif"^M Content-Type: application/octet-stream^M ^M GIF89an^@I^^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3^M Content-Disposition: form-data; name="Upload"^M ^M Submit Query^M ------------KM7cH2GI3cH2Ef1Ij5gL6GI3Ij5GI3- ```
2010/11/21
['https://Stackoverflow.com/questions/4236020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']
You want to do this as the file is going over, or is this something you want to do after the file comes over? Almost any scripting language should work. My AWK is a bit rusty, but... ``` awk '/^Content-Type: application\/octet-stream/,/^--------/' ``` That should print everything between `application/octet-stream` and the `----------` lines. It might also include both those lines too which means you'll have to do something a bit more complex: ``` BEGIN {state = 0} { if ($0 ~ /^------------/) { state = 0; } if (state == 1) { print $0 } if ($0 ~ /^Content-Type: application\/octet-stream/) { state = 1; } } ``` The `application\/octet-stream` line is after the print statement because you want to set `state` to `1` after you see `application/octet-stream`. Of course, being Unix, you could pipe the output of your program through awk and then save the file.
Look at the [Mime::Tools suite](http://search.cpan.org/perldoc?MIME%3a%3aTools) for Perl. It has a rich set of classes; I’m sure you could put something together in just a few lines.
149,833
I have added product grid in Magento 2 admin form using this link: [product grid](http://www.webspeaks.in/2016/05/magento-2-add-products-grid-to-custom-admin-module.html). But now I am creating admin form using ui component and I am not able to change product grid using ui component. Please help me. > > view/adminhtml/layout/productlabel\_productlabel\_edit.xml > > > ``` <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <uiComponent name="productlabel_form"/> </referenceContainer> </body> </page> ``` > > view/adminhtml/ui\_component/productlabel\_form.xml > > > ``` <fieldset name="assign_products"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="label" xsi:type="string" translate="true">Products in Category</item> <item name="collapsible" xsi:type="boolean">true</item> <item name="sortOrder" xsi:type="number">40</item> </item> </argument> <container name="assign_products_container" > <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="sortOrder" xsi:type="number">160</item> </item> </argument> <htmlContent name="html_content"> <argument name="block" xsi:type="object">Magento\Catalog\Block\Adminhtml\Category\AssignProducts</argument> </htmlContent> </container> </fieldset> ``` Please Help!
2016/12/12
['https://magento.stackexchange.com/questions/149833', 'https://magento.stackexchange.com', 'https://magento.stackexchange.com/users/44843/']
Please check this. **Step 1: Add the following code in your ui form** ``` <fieldset name="assign_products"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="label" xsi:type="string" translate="true">Assign Products</item> <item name="collapsible" xsi:type="boolean">true</item> <item name="sortOrder" xsi:type="number">40</item> </item> </argument> <container name="assign_products_container" > <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="sortOrder" xsi:type="number">60</item> </item> </argument> <htmlContent name="html_content"> <argument name="block" xsi:type="object">Namespace\Module\Block\Adminhtml\Products\Edit\AssignProducts</argument> </htmlContent> </container> </fieldset> ``` **Step 2: Create `AssignProducts.php` in `Namespace\Module\Block\Adminhtml\Products\Edit`** ``` namespace Namespace\Module\Block\Adminhtml\Products\Edit; class AssignProducts extends \Magento\Backend\Block\Template { /** * Block template * * @var string */ protected $_template = 'products/assign_products.phtml'; /** * @var \Magento\Catalog\Block\Adminhtml\Category\Tab\Product */ protected $blockGrid; /** * @var \Magento\Framework\Registry */ protected $registry; /** * @var \Magento\Framework\Json\EncoderInterface */ protected $jsonEncoder; protected $_productCollectionFactory; /** * AssignProducts constructor. * * @param \Magento\Backend\Block\Template\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder * @param array $data */ public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Json\EncoderInterface $jsonEncoder, \Namespace\Module\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, //your custom collection array $data = [] ) { $this->registry = $registry; $this->jsonEncoder = $jsonEncoder; $this->_productCollectionFactory = $productCollectionFactory; parent::__construct($context, $data); } /** * Retrieve instance of grid block * * @return \Magento\Framework\View\Element\BlockInterface * @throws \Magento\Framework\Exception\LocalizedException */ public function getBlockGrid() { if (null === $this->blockGrid) { $this->blockGrid = $this->getLayout()->createBlock( 'Namespace\Module\Block\Adminhtml\Products\Edit\Tab\Product', 'category.product.grid' ); } return $this->blockGrid; } /** * Return HTML of grid block * * @return string */ public function getGridHtml() { return $this->getBlockGrid()->toHtml(); } /** * @return string */ public function getProductsJson() { $vProducts = $this->_productCollectionFactory->create() ->addFieldToFilter('customer_id', $this->getItem()->getCustomerId()) ->addFieldToSelect('product_id'); $products = array(); foreach($vProducts as $pdct){ $products[$pdct->getProductId()] = ''; } if (!empty($products)) { return $this->jsonEncoder->encode($products); } return '{}'; } public function getItem() { return $this->registry->registry('my_item'); } } ``` **Step3:Create Product.php in `Namespace\Module\Block\Adminhtml\Products\Edit\Tab\`** ``` namespace Namespace\Module\Block\Adminhtml\Products\Edit\Tab; use Magento\Backend\Block\Widget\Grid; use Magento\Backend\Block\Widget\Grid\Column; use Magento\Backend\Block\Widget\Grid\Extended; class Product extends \Magento\Backend\Block\Widget\Grid\Extended { protected $logger; /** * Core registry * * @var \Magento\Framework\Registry */ protected $_coreRegistry = null; /** * @var \Magento\Catalog\Model\ProductFactory */ protected $_productFactory; protected $_productCollectionFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Backend\Helper\Data $backendHelper, \Magento\Catalog\Model\ProductFactory $productFactory, \Namespace\Module\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, \Magento\Framework\Registry $coreRegistry, array $data = [] ) { $this->_productFactory = $productFactory; $this->_coreRegistry = $coreRegistry; $this->_productCollectionFactory = $productCollectionFactory; parent::__construct($context, $backendHelper, $data); } /** * @return void */ protected function _construct() { parent::_construct(); $this->setId('catalog_category_products'); $this->setDefaultSort('entity_id'); $this->setUseAjax(true); } /** * @return array|null */ public function getItem() { return $this->_coreRegistry->registry('my_item'); } /** * @param Column $column * @return $this */ protected function _addColumnFilterToCollection($column) { // Set custom filter for in category flag if ($column->getId() == 'in_category') { $productIds = $this->_getSelectedProducts(); if (empty($productIds)) { $productIds = 0; } if ($column->getFilter()->getValue()) { $this->getCollection()->addFieldToFilter('entity_id', ['in' => $productIds]); } elseif (!empty($productIds)) { $this->getCollection()->addFieldToFilter('entity_id', ['nin' => $productIds]); } } else { parent::_addColumnFilterToCollection($column); } return $this; } /** * @return Grid */ protected function _prepareCollection() { if ($this->getItem()->getId()) { $this->setDefaultFilter(['in_category' => 1]); } $collection = $this->_productFactory->create()->getCollection()->addAttributeToSelect( 'name' )->addAttributeToSelect( 'sku' )->addAttributeToSelect( 'price' )->joinField( 'position', 'catalog_category_product', 'position', 'product_id=entity_id', 'category_id=' . (int)$this->getRequest()->getParam('id', 0), 'left' ); $storeId = (int)$this->getRequest()->getParam('store', 0); if ($storeId > 0) { $collection->addStoreFilter($storeId); } $this->setCollection($collection); if ($this->getItem()->getProductsReadonly()) { $productIds = $this->_getSelectedProducts(); if (empty($productIds)) { $productIds = 0; } $this->getCollection()->addFieldToFilter('entity_id', ['in' => $productIds]); } return parent::_prepareCollection(); } /** * @return Extended */ protected function _prepareColumns() { if (!$this->getItem()->getProductsReadonly()) { $this->addColumn( 'in_category', [ 'type' => 'checkbox', 'name' => 'in_category', 'values' => $this->_getSelectedProducts(), 'index' => 'entity_id', 'header_css_class' => 'col-select col-massaction', 'column_css_class' => 'col-select col-massaction' ] ); } $this->addColumn( 'entity_id', [ 'header' => __('ID'), 'sortable' => true, 'index' => 'entity_id', 'header_css_class' => 'col-id', 'column_css_class' => 'col-id' ] ); $this->addColumn('name', ['header' => __('Name'), 'index' => 'name']); $this->addColumn('sku', ['header' => __('SKU'), 'index' => 'sku']); $this->addColumn( 'price', [ 'header' => __('Price'), 'type' => 'currency', 'currency_code' => (string)$this->_scopeConfig->getValue( \Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ), 'index' => 'price' ] ); $this->addColumn( 'position', [ 'header' => __('Position'), 'type' => 'number', 'index' => 'position', 'editable' => !$this->getItem()->getProductsReadonly() ] ); return parent::_prepareColumns(); } /** * @return string */ public function getGridUrl() { return $this->getUrl('module/products/grid', ['_current' => true]); } /** * @return array */ protected function _getSelectedProducts() { $products = $this->getRequest()->getPost('selected_products'); if ($products === null) { $vProducts = $this->_productCollectionFactory->create() ->addFieldToFilter('customer_id', $this->getItem()->getCustomerId()) ->addFieldToSelect('product_id'); $products = array(); foreach($vProducts as $pdct){ $products[] = $pdct->getProductId(); } } return $products; } } ``` **Step4:Create `assign_products.phtml` in `Namespace\Module\view\adminhtml\templates\products\`** ``` <?php $blockGrid = $block->getBlockGrid(); $gridJsObjectName = $blockGrid->getJsObjectName(); ?> <?php echo $block->getGridHtml(); ?> <input type="hidden" name="category_products" id="in_category_products" data-form-part="your_form" value="" /> <script type="text/x-magento-init"> { "*": { "Namespace_Module/products/assign-products": { "selectedProducts": <?php /* @escapeNotVerified */ echo $block->getProductsJson(); ?>, "gridJsObjectName": <?php /* @escapeNotVerified */ echo '"' . $gridJsObjectName . '"' ?: '{}'; ?> } } } </script> <!-- @todo remove when "UI components" will support such initialization --> <script> require('mage/apply/main').apply(); </script> ``` **Step 4: Copy `vendor/magento/module-catalog/view/adminhtml/web/catalog/category/assign-products.js` to `Namespace/Module/view/adminhtml/web/products/`** **Step 5: Create `Grid.php` `Namespace/Module/Controller/Adminhtml/Products`** ``` namespace Namespace\Module\Controller\Adminhtml\Products; class Grid extends \Namespace\Module\Controller\Adminhtml\Products\Product { /** * @var \Magento\Framework\Controller\Result\RawFactory */ protected $resultRawFactory; /** * @var \Magento\Framework\View\LayoutFactory */ protected $layoutFactory; /** * @param \Magento\Backend\App\Action\Context $context * @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory * @param \Magento\Framework\View\LayoutFactory $layoutFactory */ public function __construct( \Magento\Backend\App\Action\Context $context, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Magento\Framework\View\LayoutFactory $layoutFactory ) { parent::__construct($context); $this->resultRawFactory = $resultRawFactory; $this->layoutFactory = $layoutFactory; } /** * Grid Action * Display list of products related to current category * * @return \Magento\Framework\Controller\Result\Raw */ public function execute() { $item = $this->_initItem(true); if (!$item) { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); return $resultRedirect->setPath('module/item/new', ['_current' => true, 'id' => null]); } /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); return $resultRaw->setContents( $this->layoutFactory->create()->createBlock( 'Namespace\Module\Block\Adminhtml\Products\Edit\Tab\Product', 'category.product.grid' )->toHtml() ); } protected function _initItem($getRootInstead = false) { $id = (int)$this->getRequest()->getParam('id', false); $myModel = $this->_objectManager->create('Namespace\Module\Model\Item'); if ($id) { $myModel->load($id); } $this->_objectManager->get('Magento\Framework\Registry')->register('item', $myModel); $this->_objectManager->get('Magento\Framework\Registry')->register('my_item', $myModel); $this->_objectManager->get('Magento\Cms\Model\Wysiwyg\Config'); return $storeModel; } } ``` **Step 6: Create `Product.php Namespace/Module/Controller/Adminhtml/Products`** ``` namespace Namespace\Module\Controller\Adminhtml\Products; abstract class Product extends \Magento\Backend\App\Action { /** * Authorization level of a basic admin session * * @see _isAllowed() */ const ADMIN_RESOURCE = 'Namespace_Module::item_list'; } ```
1. if you are getting this **getProductsReadonly() on null** type of error try to remove getCategory() check and also remove getId() check than products grid will be shown 2. Namespace\Module\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, //your custom collection ? can you please give example If you don't know what is this 2nd number question than it is simple copy Product/Collection.php class from Module-cataloge and create in your custom module in same path rename only namespace with your module name. Kindly kudos me if you done or if you have any queries regarding this comment here
17,616,338
I have ViewModel and Model as below ``` public class MyViewModel { public List<MyModel> MyItems { get; set; } /* There are many other properties*/ } public class MyModel { public string MyType { get; set; } public decimal value1 { get; set; } public decimal value2 { get; set; } } ``` I am binding the razor view as below. For column 1 I can just show the string. For columns 2 and 3 I need to show text boxes with data from the model. ``` <table > <thead> <tr> <th>My Column1</th> <th>My Column2</th> <th>My Column3</th> </tr> </thead> <tbody> @foreach (var myItem in Model.MyItems) { <tr> <td> @myItem.MyType </td> <td>@Html.TextBoxFor( ??? )</td> <td></td> </tr> } </tbody> </table> ``` In normal cases I see that we can do like @Html.TextBoxFor(m => m.myvalue1). But how to do it in the above case. Please suggest.
2013/07/12
['https://Stackoverflow.com/questions/17616338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461535/']
The HtmlHelpers in Razor works better by indexer. You have to do: ``` @for (var i = 0; i < Model.MyItems.Count; ++i) { <tr> <td>@Model.MyItems[i]</td> <td>@Html.TextBoxFor(m => m.MyItems[i])</td> <td></td> </tr> } ```
You are already parsing your list in the `@foreach` loop, so you just need `<td>@Html.TextBoxFor(myItem.value1)</td>`
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
And another alternative using [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split): ``` var email = "[email protected]"; var sp = email.split('@'); console.log(sp[0]); // john.doe console.log(sp[1]); // email.com ```
Try it using [`substring()`](http://www.w3schools.com/jsref/jsref_substring.asp) and [`indexOf()`](http://www.w3schools.com/jsref/jsref_indexof.asp) ``` var name = email.substring(0, email.indexOf("@")); ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
And another alternative using [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split): ``` var email = "[email protected]"; var sp = email.split('@'); console.log(sp[0]); // john.doe console.log(sp[1]); // email.com ```
As shown in [How to remove or get domain name from an e-mail address in Javascript?](https://www.4codev.com/javascript/how-to-remove-or-get-domain-name-from-an-e-mail-address-in-javascript-idpx2198110465829791878.html), you can do it using the following code: ``` const getDomainFromEmail = email => { let emailDomain = null; const pos = email.search('@'); // get position of domain if (pos > 0) { emailDomain = email.slice(pos+1); // use the slice method to get domain name, "+1" mean domain does not include "@" } return emailDomain; }; ``` ``` const yourEmail = "[email protected]" console.log(getDomainFromEmail(yourEmail)); // result : 4codev.com ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
``` var email = "[email protected]"; var name = email.substring(0, email.lastIndexOf("@")); var domain = email.substring(email.lastIndexOf("@") +1); console.log( name ); // john.doe console.log( domain ); // example.com ``` The above will also work for ***valid* names** containing `@` ([tools.ietf.org/html/rfc3696](https://www.rfc-editor.org/rfc/rfc3696)*Page 5*): > > john@doe > > "john@@".doe > > "j@hn".d@e > > > * [String.prototype.substring()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) * [String.prototype.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) Using RegExp: ------------- Given the email value is [*already* validated](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript), [String.prototype.match()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match) can be than used to retrieve the desired name, domain: #### **String match:** ```js const name = email.match(/^.+(?=@)/)[0]; const domain = email.match(/(?<=.+@)[^@]+$/)[0]; ``` #### **Capturing Group:** ```js const name = email.match(/(.+)@/)[1]; const domain = email.match(/.+@(.+)/)[1]; ``` To get **both fragments** in an Array, use [String.prototype.split(](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)) to split the string at the last `@` character: ```js const [name, domain] = email.split(/(?<=^.+)@(?=[^@]+$)/); console.log(name, domain); ``` or simply with `/@(?=[^@]*$)/`. Here's an example that uses a reusable function `getEmailFragments( String )` ```js const getEmailFragments = (email) => email.split(/@(?=[^@]*$)/); [ // LIST OF VALID EMAILS: `[email protected]`, `john@[email protected]`, `"john@@"[email protected]`, `"j@hn".d@[email protected]`, ] .forEach(email => { const [name, domain] = getEmailFragments(email); console.log("DOMAIN: %s NAME: %s ", domain, name); }); ```
Try it using [`substring()`](http://www.w3schools.com/jsref/jsref_substring.asp) and [`indexOf()`](http://www.w3schools.com/jsref/jsref_indexof.asp) ``` var name = email.substring(0, email.indexOf("@")); ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
``` var email = "[email protected]"; var name = email.substring(0, email.lastIndexOf("@")); var domain = email.substring(email.lastIndexOf("@") +1); console.log( name ); // john.doe console.log( domain ); // example.com ``` The above will also work for ***valid* names** containing `@` ([tools.ietf.org/html/rfc3696](https://www.rfc-editor.org/rfc/rfc3696)*Page 5*): > > john@doe > > "john@@".doe > > "j@hn".d@e > > > * [String.prototype.substring()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) * [String.prototype.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) Using RegExp: ------------- Given the email value is [*already* validated](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript), [String.prototype.match()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match) can be than used to retrieve the desired name, domain: #### **String match:** ```js const name = email.match(/^.+(?=@)/)[0]; const domain = email.match(/(?<=.+@)[^@]+$/)[0]; ``` #### **Capturing Group:** ```js const name = email.match(/(.+)@/)[1]; const domain = email.match(/.+@(.+)/)[1]; ``` To get **both fragments** in an Array, use [String.prototype.split(](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)) to split the string at the last `@` character: ```js const [name, domain] = email.split(/(?<=^.+)@(?=[^@]+$)/); console.log(name, domain); ``` or simply with `/@(?=[^@]*$)/`. Here's an example that uses a reusable function `getEmailFragments( String )` ```js const getEmailFragments = (email) => email.split(/@(?=[^@]*$)/); [ // LIST OF VALID EMAILS: `[email protected]`, `john@[email protected]`, `"john@@"[email protected]`, `"j@hn".d@[email protected]`, ] .forEach(email => { const [name, domain] = getEmailFragments(email); console.log("DOMAIN: %s NAME: %s ", domain, name); }); ```
This is only extract your name and remove the nos and special characters present in your name this will work only if your mail id has your name in it ``` var email = user.email; var name = email.replace(/@.*/, ""); var noNumbername=name.replace(/[0-9]/g, ''); function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } var makefirstNameCaps=capitalizeFirstLetter(noNumbername); console.log(makefirstNameCaps); ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
You can try with the replace() and regular expression. You can read more about replace() using regex [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) ``` var myEmail = '[email protected]'; var name= myEmail.replace(/@.*/, ""); console.log(name); ``` This returns the string before @
This simple regex will do the needful. `/^.*(?=@)/g`. Example: ``` "[email protected]".match(/^.*(?=@)/g); // returns Array [ "johndoe" ] ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
You should take note that a valid email address is an incredibly sophisticated object and may contain multiple `@` signs (ref. <http://cr.yp.to/im/address.html>). > > "The domain part of an address is everything after the final `@`." > > > Thus, you should do something equivalent to: ``` var email = "[email protected]"; var name = email.substring(0, email.lastIndexOf("@")); ``` or even shorter, ``` var name = email.replace(/@[^@]+$/, ''); ``` If you want both the name and the domain/hostname, then this will work: ``` var email = "[email protected]"; var lasta = email.lastIndexOf('@'); var name, host; if (lasta != -1) { name = email.substring(0, lasta); host = email.substring(lasta+1); /* automatically extends to end of string when 2nd arg omitted */ } else { /* respond to invalid email in some way */ } ```
You can try with the replace() and regular expression. You can read more about replace() using regex [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) ``` var myEmail = '[email protected]'; var name= myEmail.replace(/@.*/, ""); console.log(name); ``` This returns the string before @
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
``` var email = "[email protected]"; var name = email.substring(0, email.lastIndexOf("@")); var domain = email.substring(email.lastIndexOf("@") +1); console.log( name ); // john.doe console.log( domain ); // example.com ``` The above will also work for ***valid* names** containing `@` ([tools.ietf.org/html/rfc3696](https://www.rfc-editor.org/rfc/rfc3696)*Page 5*): > > john@doe > > "john@@".doe > > "j@hn".d@e > > > * [String.prototype.substring()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) * [String.prototype.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) Using RegExp: ------------- Given the email value is [*already* validated](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript), [String.prototype.match()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match) can be than used to retrieve the desired name, domain: #### **String match:** ```js const name = email.match(/^.+(?=@)/)[0]; const domain = email.match(/(?<=.+@)[^@]+$/)[0]; ``` #### **Capturing Group:** ```js const name = email.match(/(.+)@/)[1]; const domain = email.match(/.+@(.+)/)[1]; ``` To get **both fragments** in an Array, use [String.prototype.split(](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)) to split the string at the last `@` character: ```js const [name, domain] = email.split(/(?<=^.+)@(?=[^@]+$)/); console.log(name, domain); ``` or simply with `/@(?=[^@]*$)/`. Here's an example that uses a reusable function `getEmailFragments( String )` ```js const getEmailFragments = (email) => email.split(/@(?=[^@]*$)/); [ // LIST OF VALID EMAILS: `[email protected]`, `john@[email protected]`, `"john@@"[email protected]`, `"j@hn".d@[email protected]`, ] .forEach(email => { const [name, domain] = getEmailFragments(email); console.log("DOMAIN: %s NAME: %s ", domain, name); }); ```
You should take note that a valid email address is an incredibly sophisticated object and may contain multiple `@` signs (ref. <http://cr.yp.to/im/address.html>). > > "The domain part of an address is everything after the final `@`." > > > Thus, you should do something equivalent to: ``` var email = "[email protected]"; var name = email.substring(0, email.lastIndexOf("@")); ``` or even shorter, ``` var name = email.replace(/@[^@]+$/, ''); ``` If you want both the name and the domain/hostname, then this will work: ``` var email = "[email protected]"; var lasta = email.lastIndexOf('@'); var name, host; if (lasta != -1) { name = email.substring(0, lasta); host = email.substring(lasta+1); /* automatically extends to end of string when 2nd arg omitted */ } else { /* respond to invalid email in some way */ } ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
``` var email = "[email protected]"; var name = email.substring(0, email.lastIndexOf("@")); var domain = email.substring(email.lastIndexOf("@") +1); console.log( name ); // john.doe console.log( domain ); // example.com ``` The above will also work for ***valid* names** containing `@` ([tools.ietf.org/html/rfc3696](https://www.rfc-editor.org/rfc/rfc3696)*Page 5*): > > john@doe > > "john@@".doe > > "j@hn".d@e > > > * [String.prototype.substring()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) * [String.prototype.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) Using RegExp: ------------- Given the email value is [*already* validated](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript), [String.prototype.match()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match) can be than used to retrieve the desired name, domain: #### **String match:** ```js const name = email.match(/^.+(?=@)/)[0]; const domain = email.match(/(?<=.+@)[^@]+$/)[0]; ``` #### **Capturing Group:** ```js const name = email.match(/(.+)@/)[1]; const domain = email.match(/.+@(.+)/)[1]; ``` To get **both fragments** in an Array, use [String.prototype.split(](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)) to split the string at the last `@` character: ```js const [name, domain] = email.split(/(?<=^.+)@(?=[^@]+$)/); console.log(name, domain); ``` or simply with `/@(?=[^@]*$)/`. Here's an example that uses a reusable function `getEmailFragments( String )` ```js const getEmailFragments = (email) => email.split(/@(?=[^@]*$)/); [ // LIST OF VALID EMAILS: `[email protected]`, `john@[email protected]`, `"john@@"[email protected]`, `"j@hn".d@[email protected]`, ] .forEach(email => { const [name, domain] = getEmailFragments(email); console.log("DOMAIN: %s NAME: %s ", domain, name); }); ```
This simple regex will do the needful. `/^.*(?=@)/g`. Example: ``` "[email protected]".match(/^.*(?=@)/g); // returns Array [ "johndoe" ] ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
You should take note that a valid email address is an incredibly sophisticated object and may contain multiple `@` signs (ref. <http://cr.yp.to/im/address.html>). > > "The domain part of an address is everything after the final `@`." > > > Thus, you should do something equivalent to: ``` var email = "[email protected]"; var name = email.substring(0, email.lastIndexOf("@")); ``` or even shorter, ``` var name = email.replace(/@[^@]+$/, ''); ``` If you want both the name and the domain/hostname, then this will work: ``` var email = "[email protected]"; var lasta = email.lastIndexOf('@'); var name, host; if (lasta != -1) { name = email.substring(0, lasta); host = email.substring(lasta+1); /* automatically extends to end of string when 2nd arg omitted */ } else { /* respond to invalid email in some way */ } ```
This simple regex will do the needful. `/^.*(?=@)/g`. Example: ``` "[email protected]".match(/^.*(?=@)/g); // returns Array [ "johndoe" ] ```
18,371,339
With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? ``` var string = "[email protected]"; ``` Will be just "johdoe"? I tried with split but it did not end well. thanks.
2013/08/22
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
``` var email = "[email protected]"; email=email.replace(/@.*/,""); //returns string (the characters before @) ```
This simple regex will do the needful. `/^.*(?=@)/g`. Example: ``` "[email protected]".match(/^.*(?=@)/g); // returns Array [ "johndoe" ] ```
36,416,808
I have a sprite image I am using and have seen other websites that implement a divisor in theirs. I can't figure out what it means. For instance: ``` background: #fff url("/css/sprite.png") no-repeat scroll -107px -55px / 167px padding-box border-box; ``` What does the "167px" mean?
2016/04/05
['https://Stackoverflow.com/questions/36416808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Use below Code:- ``` WebElement element = "Your Element"; // Your element JavascriptExecutor executor = (JavascriptExecutor) driver; Object aa=executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element); System.out.println(aa.toString()); ``` Hope it will help you :)
No. There is no way in Selenium WebDriver to access any attribute whose full name you don't know. You can't even enumerate over all attributes of a `WebElement`. It doesn't look like the jsonwire protocol supports this concept. The GET\_ELEMENT\_ATTRIBUTE command takes a list of attribute names, not a list of attribute name patterns. It is probable that you could query via a `JavascriptExecutor` and either XPath or CSS query to find all the attribute names for your element, then use that to loop over `getAttribute`. But if you're going to do that, you can just construct your XPath or CSS query to give you the values directly, and leave the `WebElement` out of it completely.
36,416,808
I have a sprite image I am using and have seen other websites that implement a divisor in theirs. I can't figure out what it means. For instance: ``` background: #fff url("/css/sprite.png") no-repeat scroll -107px -55px / 167px padding-box border-box; ``` What does the "167px" mean?
2016/04/05
['https://Stackoverflow.com/questions/36416808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
No. There is no way in Selenium WebDriver to access any attribute whose full name you don't know. You can't even enumerate over all attributes of a `WebElement`. It doesn't look like the jsonwire protocol supports this concept. The GET\_ELEMENT\_ATTRIBUTE command takes a list of attribute names, not a list of attribute name patterns. It is probable that you could query via a `JavascriptExecutor` and either XPath or CSS query to find all the attribute names for your element, then use that to loop over `getAttribute`. But if you're going to do that, you can just construct your XPath or CSS query to give you the values directly, and leave the `WebElement` out of it completely.
This concept works very well. Try this! ```java WebElement element = driver.findElement(By.tagName("button")); JavascriptExecutor executor = (JavascriptExecutor) driver; Object elementAttributes = executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;",element); System.out.println(elementAttributes.toString()); ```
36,416,808
I have a sprite image I am using and have seen other websites that implement a divisor in theirs. I can't figure out what it means. For instance: ``` background: #fff url("/css/sprite.png") no-repeat scroll -107px -55px / 167px padding-box border-box; ``` What does the "167px" mean?
2016/04/05
['https://Stackoverflow.com/questions/36416808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Use below Code:- ``` WebElement element = "Your Element"; // Your element JavascriptExecutor executor = (JavascriptExecutor) driver; Object aa=executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element); System.out.println(aa.toString()); ``` Hope it will help you :)
This concept works very well. Try this! ```java WebElement element = driver.findElement(By.tagName("button")); JavascriptExecutor executor = (JavascriptExecutor) driver; Object elementAttributes = executor.executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;",element); System.out.println(elementAttributes.toString()); ```
2,070,933
Ok i have sinned, i wrote too much code like this ``` try { // my code } catch (Exception ex) { // doesn't matter } ``` Now i'm going to cleanup/refactor this. I'm using NB 6.7 and code completion works fine on first writing, adding all Exception types, etc. Once i have done the above code NB do not give more help. Do you know a way to say NB look again for all Exception types and make the proposal for handling them and do code completion again ?
2010/01/15
['https://Stackoverflow.com/questions/2070933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114226/']
The problem is, that your catch-all handler "handles" all the exceptions, so there's not need for Netbeans to show any more hints. If your exception handlers are already empty and you are planning to refactor them anyway, you can just temporarily remove them. Tip: Auto-format your code, search for `try` and use bracket highlighting to find the matching `catch` blocks. Then remove all the handling code. After that Netbeans will again propose various actions to handle the possible exceptions. PS: Be careful, the default handling of Netbeans (i.e. just logging) is not always the best choice, either.
I just can provide the eclipse approach and hope that it's somewhat similiar with netbeans: 1. remove the try/catch statements -> eclipse will show compiler errors 2. use eclipse's quick tip to refactor the correct try/catch (or throw) statements You may save your existing exception handling code to paste it in after the refactoring. **Edit** Tom had a very good comment regarding RuntimeException. So the procedure should better look like this: 1. copy the existing catch clause and paste to a notepad/text editor 2. remove the try/catch statements -> eclipse will show compiler errors 3. use eclipse's quick tip to refactor the correct try/catch (or throw) statements 4. paste the stored catch clause at the end of sequence of catch statements This will preserve your exception handling of RuntimeExceptions (and subtypes!). So from ``` try { Integer.parseInt("Force a RuntimeException"); myInputStream.close(); } catch (Exception oops) { // catch both IOException and NumberFormatException } ``` you go to ``` try { Integer.parseInt("Force a RuntimeException"); myInputStream.close(); } catch (IOException oops) { // catch IOException } catch (Exception oops) { // catch NumberFormatException } ``` (although you could manually replace Exception by NumberFormatException in this case, but it's just an example)
2,070,933
Ok i have sinned, i wrote too much code like this ``` try { // my code } catch (Exception ex) { // doesn't matter } ``` Now i'm going to cleanup/refactor this. I'm using NB 6.7 and code completion works fine on first writing, adding all Exception types, etc. Once i have done the above code NB do not give more help. Do you know a way to say NB look again for all Exception types and make the proposal for handling them and do code completion again ?
2010/01/15
['https://Stackoverflow.com/questions/2070933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114226/']
[PMD](http://pmd.sourceforge.net/) identifies all these places where you have empty `catch` blocks (PMD does much more actually). It has NetBeans integration, so give it a try. After identifying all the places with empty `catch` blocks you will have to consider each one by itself: * sometimes just log the message * sometimes restructure nearby code. I.e. if you are catching a `NullPointerException`, add a `null` check instead. * sometimes you will have to consider rethrowing (and declaring checked) exceptions.
I just can provide the eclipse approach and hope that it's somewhat similiar with netbeans: 1. remove the try/catch statements -> eclipse will show compiler errors 2. use eclipse's quick tip to refactor the correct try/catch (or throw) statements You may save your existing exception handling code to paste it in after the refactoring. **Edit** Tom had a very good comment regarding RuntimeException. So the procedure should better look like this: 1. copy the existing catch clause and paste to a notepad/text editor 2. remove the try/catch statements -> eclipse will show compiler errors 3. use eclipse's quick tip to refactor the correct try/catch (or throw) statements 4. paste the stored catch clause at the end of sequence of catch statements This will preserve your exception handling of RuntimeExceptions (and subtypes!). So from ``` try { Integer.parseInt("Force a RuntimeException"); myInputStream.close(); } catch (Exception oops) { // catch both IOException and NumberFormatException } ``` you go to ``` try { Integer.parseInt("Force a RuntimeException"); myInputStream.close(); } catch (IOException oops) { // catch IOException } catch (Exception oops) { // catch NumberFormatException } ``` (although you could manually replace Exception by NumberFormatException in this case, but it's just an example)
2,070,933
Ok i have sinned, i wrote too much code like this ``` try { // my code } catch (Exception ex) { // doesn't matter } ``` Now i'm going to cleanup/refactor this. I'm using NB 6.7 and code completion works fine on first writing, adding all Exception types, etc. Once i have done the above code NB do not give more help. Do you know a way to say NB look again for all Exception types and make the proposal for handling them and do code completion again ?
2010/01/15
['https://Stackoverflow.com/questions/2070933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114226/']
> > When you ask for a proposal on how to handle the exceptions ... > > > There is no generally accepted way to handle them. Otherwise, you bet the java language would have implicitly that behavior. * Exceptions are not a low-level constraint that one must deal with until the compiler is smart-enough. * Exceptions are a high-level language construct, used to express the semantic "something exceptional happened, whose treatment you don't want to mix with the regular code ; you prefer it to be handle in specific codes". --- Exceptions exist in two forms, by design: * Checked Exceptions must be made explicit in each method that can throw them. * Unchecked Exceptions (subclasses of RuntimeException or Error) are usually implicit. At each level of code (method or block), the code has to choose what to do, in the event of any exception (except unchecked exceptions that can omit the treatment altogether). This is a choice of responsibility that varies, there is no decision valid for all cases : * **PROCESS** : Catch it and fully process it (calling codes typically don't to know something happened). The current method need to have the responsibility. Logging the stack-trace for the developper might be useful. * **STEP** : Catch it, do a step of the processing that is related to the local code, and rethrow it (or rethrow another exception with the original one as a cause). * **IGNORE** : just let it to the responsibility of the calling code. The java language lets you have specific syntaxes making easier to handle exceptions, like the catch of specific exceptions followed more general ones... --- Typically, you consider Exceptions in your architecture, and make some design decisions. Some examples (mixed in unique ways): * choose to have one layer process all exceptions thrown in lower layers (ex : transactional services) : logging for the developper, positionning some global information for the user ... * let some exceptions go up a few method calls until you arrive in a code where it is meaningful to process it (for example, depending on your exceptions, you can retry a full operation, or notify the user ... ) * etc.
I just can provide the eclipse approach and hope that it's somewhat similiar with netbeans: 1. remove the try/catch statements -> eclipse will show compiler errors 2. use eclipse's quick tip to refactor the correct try/catch (or throw) statements You may save your existing exception handling code to paste it in after the refactoring. **Edit** Tom had a very good comment regarding RuntimeException. So the procedure should better look like this: 1. copy the existing catch clause and paste to a notepad/text editor 2. remove the try/catch statements -> eclipse will show compiler errors 3. use eclipse's quick tip to refactor the correct try/catch (or throw) statements 4. paste the stored catch clause at the end of sequence of catch statements This will preserve your exception handling of RuntimeExceptions (and subtypes!). So from ``` try { Integer.parseInt("Force a RuntimeException"); myInputStream.close(); } catch (Exception oops) { // catch both IOException and NumberFormatException } ``` you go to ``` try { Integer.parseInt("Force a RuntimeException"); myInputStream.close(); } catch (IOException oops) { // catch IOException } catch (Exception oops) { // catch NumberFormatException } ``` (although you could manually replace Exception by NumberFormatException in this case, but it's just an example)
16,947,535
I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this. Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users. ``` SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName = ????? usernames????? ", con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["text"].ToString()); } ``` How can I fix this code?
2013/06/05
['https://Stackoverflow.com/questions/16947535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2456977/']
``` "SELECT FName FROM Users WHERE FName = @paramUsername" ``` and then you insert the parameter into the cmd like so: ``` cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar); cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor"; ```
Check this out: ``` SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); string validationQuery = "SELECT * FROM Users WHERE FName = @name"; SqlCommand validationCommand = new SqlCommand(validationQuery, connection); validationCommand.Parameters.Add("@name", SqlDbType.VarChar).Value = loginUserSelected; connection.Open(); SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection); if (!validationReader.Read()) { string insertQuery = "INSERT INTO Users (FName) VALUES (@name)"; SqlCommand insertCommand = new SqlCommand(insertQuery, connection); insertCommand.Parameters.Add("@name", SqlDbType.VarChar).Value = loginUserSelected; connection.Open(); insertCommand.ExecuteNonQuery(); insertCommand.Dispose(); connection.Close(); } else { //Uh oh, username already taken } validationReader.Close(); validationCommand.Dispose(); ``` Things to note: * Use **parameters**, avoid concatenating strings because it's a security vulnerability * Always `Close` and `Dispose` your ADO objects
40,455,726
I have two data sets of xy coordinates. The first one has xy coordinates plus a tag column with my factor levels. I called the `data.frame` `qq` and it looks like this: ``` structure(list(x = c(5109, 5128, 5137, 5185, 5258, 5324, 5387, 5343, 5331, 5347, 5300, 5180, 4109, 4082, 4091, 4139, 4212, 4279, 4291, 4297, 4285, 4301, 4254, 4181), y = c(1692, 1881, 2070, 2119, 2144, 2065, 1987, 1813, 1705, 1649, 1631, 1654, 1847, 2015, 2204, 2253, 2278, 2282, 2166, 1947, 1839, 1783, 1765, 1783), tag = c("MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left" )), .Names = c("x", "y", "tag"), row.names = c(NA, -24L), class = "data.frame") ``` I generated random data for the other one using `qq` `xy` means with a large `sd`. ``` set.seed(123) my_points=data.frame(x=rnorm(n =1000,mean=mean(qq$x),sd=1000), y=rnorm(n=1000,mean=mean(qq$y),sd=1000)) ``` if I use the `in.out` function from `mgcv` package, I obtain somewhat what I want. The main issues with this approach is that my 'Polygon' is not closed nor will be interpreted as 2 polygons by factor. The package advises to use one NA row in between but I'd rather use my tag column since I will be trying to use more than 2 levels in my tag factor, namely, more than 2 polygons). My final goal is to produce a table of the number of points within each one.
2016/11/06
['https://Stackoverflow.com/questions/40455726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3215940/']
what about this: ``` mysppoint <- SpatialPoints(coords = my_points) # create spatial points qq$tag <- as.factor(qq$tag) polys = list() # create one polygon for each factor level for (lev in levels(qq$tag)){ first_x <- qq$x[qq$tag == lev][1] first_y <- qq$y[qq$tag == lev][1] qq <- rbind(qq, data.frame(x = first_x, y = first_y, tag = lev)) # "close" the polygon by replicating the first row polys[[lev]] <- Polygons(list(Polygon(matrix(data = cbind(qq$x[qq$tag == lev], # transform to polygon qq$y[qq$tag == lev]), ncol = 2))), lev) } mypolys <- SpatialPolygons(polys) # convert to spatial polygons inters <- factor(over(mysppoint, mypolys), labels = names(mypolys)) # intersect points with polygons table(inters) ``` , which gives: ``` inters MPN_left MPN_right 10 17 ``` advantage of this is that it gives you proper spatial objects to work with. For example: ``` plotd <- fortify(mypolys ) p <- ggplot() p <- p + geom_point(data = my_points, aes(x = x , y = y), size = 0.2) p <- p + geom_polygon(data = plotd, aes(x = long, y = lat, fill = id), alpha = 0.7) p ``` [![Plot of polygons and points](https://i.stack.imgur.com/1n5OM.jpg)](https://i.stack.imgur.com/1n5OM.jpg)
`lapply()` and `sapply()` help you to use function par level. ``` ## a bit edited to make output clear library(dplyr); library(mgcv) TAG <- unique(qq$tag) IN.OUT <- lapply(TAG, function(x) as.matrix(qq[qq$tag==x, 1:2])) %>% # make a matrix par level sapply(function(x) in.out(x, as.matrix(my_points))) # use in.out() with each matrix colnames(IN.OUT) <- TAG head(IN.OUT, n = 3) # MPN_right MPN_left # [1,] FALSE FALSE # [2,] FALSE FALSE # [3,] FALSE FALSE apply(IN.OUT, 2, table) # MPN_right MPN_left # FALSE 983 990 # TRUE 17 10 ```
40,455,726
I have two data sets of xy coordinates. The first one has xy coordinates plus a tag column with my factor levels. I called the `data.frame` `qq` and it looks like this: ``` structure(list(x = c(5109, 5128, 5137, 5185, 5258, 5324, 5387, 5343, 5331, 5347, 5300, 5180, 4109, 4082, 4091, 4139, 4212, 4279, 4291, 4297, 4285, 4301, 4254, 4181), y = c(1692, 1881, 2070, 2119, 2144, 2065, 1987, 1813, 1705, 1649, 1631, 1654, 1847, 2015, 2204, 2253, 2278, 2282, 2166, 1947, 1839, 1783, 1765, 1783), tag = c("MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_right", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left", "MPN_left" )), .Names = c("x", "y", "tag"), row.names = c(NA, -24L), class = "data.frame") ``` I generated random data for the other one using `qq` `xy` means with a large `sd`. ``` set.seed(123) my_points=data.frame(x=rnorm(n =1000,mean=mean(qq$x),sd=1000), y=rnorm(n=1000,mean=mean(qq$y),sd=1000)) ``` if I use the `in.out` function from `mgcv` package, I obtain somewhat what I want. The main issues with this approach is that my 'Polygon' is not closed nor will be interpreted as 2 polygons by factor. The package advises to use one NA row in between but I'd rather use my tag column since I will be trying to use more than 2 levels in my tag factor, namely, more than 2 polygons). My final goal is to produce a table of the number of points within each one.
2016/11/06
['https://Stackoverflow.com/questions/40455726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3215940/']
what about this: ``` mysppoint <- SpatialPoints(coords = my_points) # create spatial points qq$tag <- as.factor(qq$tag) polys = list() # create one polygon for each factor level for (lev in levels(qq$tag)){ first_x <- qq$x[qq$tag == lev][1] first_y <- qq$y[qq$tag == lev][1] qq <- rbind(qq, data.frame(x = first_x, y = first_y, tag = lev)) # "close" the polygon by replicating the first row polys[[lev]] <- Polygons(list(Polygon(matrix(data = cbind(qq$x[qq$tag == lev], # transform to polygon qq$y[qq$tag == lev]), ncol = 2))), lev) } mypolys <- SpatialPolygons(polys) # convert to spatial polygons inters <- factor(over(mysppoint, mypolys), labels = names(mypolys)) # intersect points with polygons table(inters) ``` , which gives: ``` inters MPN_left MPN_right 10 17 ``` advantage of this is that it gives you proper spatial objects to work with. For example: ``` plotd <- fortify(mypolys ) p <- ggplot() p <- p + geom_point(data = my_points, aes(x = x , y = y), size = 0.2) p <- p + geom_polygon(data = plotd, aes(x = long, y = lat, fill = id), alpha = 0.7) p ``` [![Plot of polygons and points](https://i.stack.imgur.com/1n5OM.jpg)](https://i.stack.imgur.com/1n5OM.jpg)
I ended up using `lapply` and a combination of `split` and more `lapply`. So here is the code, please ignore the `extract_coords` helper function, it basically gives me a `dataframe` with the `x`,`y` and tag columns. I also managed to subset the points from the original `your_coords` and count them (returning them as a vector instead of a table). ``` inside_ROI = function(your_ROI_zip,your_coords){ # Helper function will take list from zip ROIs and merge them into a df qq=extract_coords(your_ROI_zip) # We use tag for splitting by the region lista=split(qq,qq$tag) # We check if they are in or out who_is_in = lapply(lista,function(t) in.out(cbind(t$x,t$y),x=cbind(your_coords$x,your_coords$y))) # We sum to get the by area countings region_sums = unlist(lapply(who_is_in,function(t) sum(as.numeric(t)))) # obtain indices for subset of TRUE values aa=lapply(who_is_in,function(p) which(p==T)) whos_coords=list() for (i in aa){ whos_coords = append(whos_coords,values=list(your_coords[i,])) # whos_coords[[i]] = your_coords[i,] } # Change names names(whos_coords) = names(aa) # Put into list for more than one output out=list(region_sums,aa,whos_coords) return(out) } ```
125,659
Can you give me the load limit on a 4x6 pine board 18' long used for a swing set? Thank you
2017/10/23
['https://diy.stackexchange.com/questions/125659', 'https://diy.stackexchange.com', 'https://diy.stackexchange.com/users/76916/']
Assuming it’s “Lodgepole Pine” (Idaho Pine and Ponderosa Pine is slightly less) and it’s grade is a No. 2 and better (no loose or missing knotholes), then a 4x6 spanning 18’ will support about 105 lbs. loaded at the mid-span (slightly higher if it’s loaded at third points or further from the center point).
Better idea instead of the 4x6 use 2 2x8 boards bolted of nailed together. Ive done this on a 18 foot span and it holds 3 large adults (over 200 lbs each) on swings without any flex or bowing. Outdoors i would use a good grade of treated lumber to prevent decay from the elements and longer life.
19,315,725
I'm using [SimpleCaptcha](http://simplecaptcha.sourceforge.net/) My web.xml looks like the one [here](http://simplecaptcha.sourceforge.net/installing.html): ``` <servlet> <servlet-name>StickyCaptcha</servlet-name> <servlet-class>nl.captcha.servlet.StickyCaptchaServlet</servlet-class> <init-param> <param-name>width</param-name> <param-value>250</param-value> </init-param> <init-param> <param-name>height</param-name> <param-value>75</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>StickyCaptcha</servlet-name> <url-pattern>/captcha</url-pattern> </servlet-mapping> ``` And i added a refresh but to my view like described in [this SO-answer](https://stackoverflow.com/questions/10151920/refresh-simple-captcha): ``` <script type="text/javascript"> function reloadCaptcha(){ var d = new Date(); $("#captcha_image").attr("src", "/captcha?"+d.getTime()); } </script> ... <img id="captcha_image" src="/captcha_generator.jsp" alt="captcha image" width="200" height="50"/> <img src="reload.jpg" onclick="reloadCaptcha()" alt="reload"width="40" height="40"/> ``` But when i press the refresh button, nothing happens. Also when i try to call `.../captcha?4324321` it still prints the same captcha (based on the user session as i understood it) I'm also using spring-mvc and spring-webflow.
2013/10/11
['https://Stackoverflow.com/questions/19315725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2316112/']
Using `nl.captcha.servlet.SimpleCaptchaServlet` instead of `nl.captcha.servlet.StickyCaptchaServlet` solved the problem because `StickyCaptchaServlet` uses the SessionId to create the image and `SimpleCaptchaServlet` doesn't
I think you may try: $("#captcha\_image").attr("src", "/captcha\_generator.jsp"); instead of: $("#captcha\_image").attr("src", "/captcha?"+d.getTime());
104,445
I see people posted stuff on facebook telling their friends and family to stay safe. My question is shouldnt it be friends and families. Not friends and family.? or are they indicating one family as of their own family? what if the person is married and has kids? wouldnt that be 2 families?
2016/09/23
['https://ell.stackexchange.com/questions/104445', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/42134/']
A family is a group noun and in the expression "friends and family" the speaker is referring to their own family (meaning the people related to them). Depending on exact context or intent, that could be only people more closely related to them or may include more distant relations. "Family" can occur in the plural, but that would be when you are referring to more than one group of people where each group consists of members related to each other. > > My three brothers and I are taking our families on a trip this summer > > > In this case, each brother has a family (usually wife and kids).
As @P. E. Dant commented, "friends and family" has become idiomatic, largely (in my view) to the advertising of cellphone carrier service plans. So it is natural to say, whether grammatical or not. Otherwise, your question could have two meanings: > > 1) **friends and family** - your friends and *your* family > > > In this case there is only one family (yours) so "family" singular is correct. > > 2) **friends and (their) families** - your friends and *their* families. > > > Now "families" plural is OK, but it doesn't make a lot of sense. Because: 1) Your family is not included 2) It would likely be an indeterminate number of people. And if you leave out "their", it could include all families in the world.
104,445
I see people posted stuff on facebook telling their friends and family to stay safe. My question is shouldnt it be friends and families. Not friends and family.? or are they indicating one family as of their own family? what if the person is married and has kids? wouldnt that be 2 families?
2016/09/23
['https://ell.stackexchange.com/questions/104445', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/42134/']
A family is a group noun and in the expression "friends and family" the speaker is referring to their own family (meaning the people related to them). Depending on exact context or intent, that could be only people more closely related to them or may include more distant relations. "Family" can occur in the plural, but that would be when you are referring to more than one group of people where each group consists of members related to each other. > > My three brothers and I are taking our families on a trip this summer > > > In this case, each brother has a family (usually wife and kids).
> > Family > > > is used to describe a group of people who are closely related, usually genetically. The singular also has the underlying meaning of having the speaker's affection > > I consider them family. > > > My family includes my uncles, aunties and cousins. > > > When used this way, "family" can mean several generations > > a family gathering > > > and a "family gathering" may consist of several individual families. > > Each of my cousins brought their families to the family gathering. > > > "Families" (plural) here means the individual units whereas "family" (singular) refers to the overarching connection of everyone.
20,657,710
I've seen examples using XAML and writing some code in C# - is it possible just using Javascript?
2013/12/18
['https://Stackoverflow.com/questions/20657710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1129799/']
Yes. Here is a blog showing how to: <http://blogs.msdn.com/b/davrous/archive/2012/09/05/tutorial-series-using-winjs-amp-winrt-to-build-a-fun-html5-camera-application.aspx>
You can write following method for launch camera ``` function capturePhoto() { var capture = new Windows.Media.Capture.CameraCaptureUI(); capture.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo) .then(function (file) { if (file) { return file.openAsync(Windows.Storage.FileAccessMode.readWrite); } }); ```
12,100,977
So I can't seem to get an else if to work right. What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one ` ``` else if (type == "cups") { Console.WriteLine("Enter a number of liters to be converted into cups."); amount = Convert.ToDouble(Console.ReadLine()); Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters."); }` ``` I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats. Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
2012/08/23
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
I ran your code and (after fixing a simple error) it correctly enters the *else if* that you reference. You may want to echo back what you type in to make sure you are not mistyping your input. The error was that you have > > done > > > on a line by itself. Presumably you meant to assign a value.
My suggestion: use Nunit and write an unit test for it. Nunit will give expected and actual value and you'll see why this isn't working.