qid
int64
1
74.7M
question
stringlengths
25
64.6k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
3
61.5k
400,605
It is already decided by the [community](https://meta.stackoverflow.com/a/357437/) that * Downvotes are, first and foremost, a content rating system. Rather than being a way of communicating with the poster, they are a way of communicating to future readers that a question or answer is not interesting or useful. Following the agreed upon interpretation, downvotes are just noise to the asker as they show nothing other than "What the community thinks is different from what you think about the quality of your post". This feedback is mostly useless to the asker as it doesn't show what is wrong except that something may be wrong. Should this feedback be shown to the question asker at all? Could we weigh the pros and cons of showing this metric to the asker? Is this feedback that valuable or valuable at all to the "asker" that showing it to them is warranted against all the backlash received so far? Or *Is it because people here are curmudgeonly trolls who just hate people and don't want new users to feel welcome?*
2020/08/24
[ "https://meta.stackoverflow.com/questions/400605", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/8404453/" ]
*No*, votes are valuable to question askers. Votes are a collective rating by the community. They express the opinion of a silent majority, which does not comment for a variety of reasons. In contrast, any *specific* explanation of question quality is inherently an individual rating. It is one person's opinion, and that may well be wrong. It is the *combination* of votes and comments that should be the most useful to a question asker. At +5, there is no pressure to satisfy every pedantic comment. At -5, better listen to what people say. --- Of course there are situations when there are only votes, not comments – after all, there is no requirement to comment. However, in this case votes are literally the only feedback to a poster that their content is lacking. Not letting a poster know in any way that their content is lacking seems much worse than providing only fuzzy feedback. --- So *what if* votes were not shown? Posters with positive score are not shown that they did a good job. Votes are the primary gamification of "posting well", and this would be removed. *Hiding votes would remove the main gratification of contributing good content.* Posters with negative score *who can take it* are not shown that they should improve. Posters must actively check whether they need to take action. *Hiding votes would artificially delay posters from improving their content.* Posters with negative score *who feel offended* are protected from the negative message. However, that negative message is not gone, it is just not shown. *Hiding votes means the negativity happens behind the poster's back.* (IMO that is bad, but it probably depends on the individual.) --- Let us assume that protecting posters from negativity of downvoting would work. What does that mean *for voters*? Honestly, *I would downvote more*. When I *currently* see a -3, or -2, or sometimes even a -1 *that means the poster already got the message*. Not to be an evil prick, I try to give the poster their share of time to improve. Perhaps I follow the question and check in after some time. I try to only downvote if there is no sign of honest effort, if they are ignoring the message. If there is no message to the poster, then it is just about the content. And the content which needs protecting the poster usually deserves to be downvoted.
Sometimes, yes; a problem is posed, code presented, along attempted resolutions - and still a downvote. Then editing "Why the downvotes?", and a desert echo. The quoted "definition" of downvotes is meaningless; users don't sit around a table and jointly agree "Yes, this is, indeed, what we shall mean by 'downvote'". It varies by the user - and those on the receiving end of (perceived) unwarranted and unexplained downvotes form a negative assosciation, potentially [discouraging](https://meta.stackoverflow.com/q/398537/10133797) them from downvoting. A remedy, one that'd at least encourage me to downvote more, would be a menu of explanations followed by "submit" (downvote), just as in review queues/close votes. I often see questions with clear problems, but *don't* downvote as I rather not invest time crafting up a sentence. --- **Update**: anonymous feedback was suggested in comments; I agree. The *option* would help; then I can convey the same idea but not necessarily in same quality wording / sentence structure, thus reducing effort. Further, it can be a combination of "predefined reasons" (unclear, etc) PLUS a custom comment; the comment can now be two words instead of a sentence. It may seem like "what's your beef with typing a sentence", but when you have to do it for many questions when you have no incentive to do so at all, it matters.
400,605
It is already decided by the [community](https://meta.stackoverflow.com/a/357437/) that * Downvotes are, first and foremost, a content rating system. Rather than being a way of communicating with the poster, they are a way of communicating to future readers that a question or answer is not interesting or useful. Following the agreed upon interpretation, downvotes are just noise to the asker as they show nothing other than "What the community thinks is different from what you think about the quality of your post". This feedback is mostly useless to the asker as it doesn't show what is wrong except that something may be wrong. Should this feedback be shown to the question asker at all? Could we weigh the pros and cons of showing this metric to the asker? Is this feedback that valuable or valuable at all to the "asker" that showing it to them is warranted against all the backlash received so far? Or *Is it because people here are curmudgeonly trolls who just hate people and don't want new users to feel welcome?*
2020/08/24
[ "https://meta.stackoverflow.com/questions/400605", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/8404453/" ]
**Votes on your own questions are valuable feedback.** It can tell you, just as it would anyone else, how well-received your post was. If the question you asked has a negative score, it should be a sign to you that you need to improve your question-asking skills. If your question has a positive score, it means that the community found it to be a valuable contribution, one which could help others in the future with the same problem. Downvotes are even more important on questions because they could persuade you to consider editing or even deletion of your post. If your post is disliked by others then you should try to understand if there's anything you could do to improve it. **Ideally, you should do your best to make a perfect question before posting it**, but we all know that we make mistakes, English might not be our native language and Markdown formatting can be intimidating at first. Of course, no matter how much you try to ask a perfect question **there is no way to correctly predict whether it is going to be successful or not**. I have asked in the past questions which I believed to be very good, but they have been severely downvoted. Asking questions is hard and it is a gamble. --- In terms of the proposal to hide score from question asker, it would make sense to do so only temporarily. Let the score be easily found if they really want to know, but don't show it prominently to them. The score can be useful, but the emotional fallout resulting from misunderstanding them is not. Rude and impolite comments under the question demanding written feedback from voters is something that this proposal should aim to avoid. I don't want to see comments in the style of *"Why the downvote?"* or get revenge downvoted because I provided useful comment when downvoting. If we want to take away one feedback from people (question's score) then we should give something in return. Something that would tell OP that their post is not appreciated here without overtly hurting their feelings or irritating them to the point where they forget about their problem and focus on users.
Sometimes, yes; a problem is posed, code presented, along attempted resolutions - and still a downvote. Then editing "Why the downvotes?", and a desert echo. The quoted "definition" of downvotes is meaningless; users don't sit around a table and jointly agree "Yes, this is, indeed, what we shall mean by 'downvote'". It varies by the user - and those on the receiving end of (perceived) unwarranted and unexplained downvotes form a negative assosciation, potentially [discouraging](https://meta.stackoverflow.com/q/398537/10133797) them from downvoting. A remedy, one that'd at least encourage me to downvote more, would be a menu of explanations followed by "submit" (downvote), just as in review queues/close votes. I often see questions with clear problems, but *don't* downvote as I rather not invest time crafting up a sentence. --- **Update**: anonymous feedback was suggested in comments; I agree. The *option* would help; then I can convey the same idea but not necessarily in same quality wording / sentence structure, thus reducing effort. Further, it can be a combination of "predefined reasons" (unclear, etc) PLUS a custom comment; the comment can now be two words instead of a sentence. It may seem like "what's your beef with typing a sentence", but when you have to do it for many questions when you have no incentive to do so at all, it matters.
400,605
It is already decided by the [community](https://meta.stackoverflow.com/a/357437/) that * Downvotes are, first and foremost, a content rating system. Rather than being a way of communicating with the poster, they are a way of communicating to future readers that a question or answer is not interesting or useful. Following the agreed upon interpretation, downvotes are just noise to the asker as they show nothing other than "What the community thinks is different from what you think about the quality of your post". This feedback is mostly useless to the asker as it doesn't show what is wrong except that something may be wrong. Should this feedback be shown to the question asker at all? Could we weigh the pros and cons of showing this metric to the asker? Is this feedback that valuable or valuable at all to the "asker" that showing it to them is warranted against all the backlash received so far? Or *Is it because people here are curmudgeonly trolls who just hate people and don't want new users to feel welcome?*
2020/08/24
[ "https://meta.stackoverflow.com/questions/400605", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/8404453/" ]
*No*, votes are valuable to question askers. Votes are a collective rating by the community. They express the opinion of a silent majority, which does not comment for a variety of reasons. In contrast, any *specific* explanation of question quality is inherently an individual rating. It is one person's opinion, and that may well be wrong. It is the *combination* of votes and comments that should be the most useful to a question asker. At +5, there is no pressure to satisfy every pedantic comment. At -5, better listen to what people say. --- Of course there are situations when there are only votes, not comments – after all, there is no requirement to comment. However, in this case votes are literally the only feedback to a poster that their content is lacking. Not letting a poster know in any way that their content is lacking seems much worse than providing only fuzzy feedback. --- So *what if* votes were not shown? Posters with positive score are not shown that they did a good job. Votes are the primary gamification of "posting well", and this would be removed. *Hiding votes would remove the main gratification of contributing good content.* Posters with negative score *who can take it* are not shown that they should improve. Posters must actively check whether they need to take action. *Hiding votes would artificially delay posters from improving their content.* Posters with negative score *who feel offended* are protected from the negative message. However, that negative message is not gone, it is just not shown. *Hiding votes means the negativity happens behind the poster's back.* (IMO that is bad, but it probably depends on the individual.) --- Let us assume that protecting posters from negativity of downvoting would work. What does that mean *for voters*? Honestly, *I would downvote more*. When I *currently* see a -3, or -2, or sometimes even a -1 *that means the poster already got the message*. Not to be an evil prick, I try to give the poster their share of time to improve. Perhaps I follow the question and check in after some time. I try to only downvote if there is no sign of honest effort, if they are ignoring the message. If there is no message to the poster, then it is just about the content. And the content which needs protecting the poster usually deserves to be downvoted.
**Votes on your own questions are valuable feedback.** It can tell you, just as it would anyone else, how well-received your post was. If the question you asked has a negative score, it should be a sign to you that you need to improve your question-asking skills. If your question has a positive score, it means that the community found it to be a valuable contribution, one which could help others in the future with the same problem. Downvotes are even more important on questions because they could persuade you to consider editing or even deletion of your post. If your post is disliked by others then you should try to understand if there's anything you could do to improve it. **Ideally, you should do your best to make a perfect question before posting it**, but we all know that we make mistakes, English might not be our native language and Markdown formatting can be intimidating at first. Of course, no matter how much you try to ask a perfect question **there is no way to correctly predict whether it is going to be successful or not**. I have asked in the past questions which I believed to be very good, but they have been severely downvoted. Asking questions is hard and it is a gamble. --- In terms of the proposal to hide score from question asker, it would make sense to do so only temporarily. Let the score be easily found if they really want to know, but don't show it prominently to them. The score can be useful, but the emotional fallout resulting from misunderstanding them is not. Rude and impolite comments under the question demanding written feedback from voters is something that this proposal should aim to avoid. I don't want to see comments in the style of *"Why the downvote?"* or get revenge downvoted because I provided useful comment when downvoting. If we want to take away one feedback from people (question's score) then we should give something in return. Something that would tell OP that their post is not appreciated here without overtly hurting their feelings or irritating them to the point where they forget about their problem and focus on users.
30,099,243
I want to get all matches of `@[SomeText]` pattern in a string. For example, for this string: here is `@[text1]` some text `@[text2]` I want `@[text1]` and `@[text2]`. I'm using Regex Hero to check my pattern matching online, and my pattern works fine when there's one expression to match, For example: ``` here is @[text1] text ``` but with more then one, I get both matches with the text in the middle. ![enter image description here](https://i.stack.imgur.com/aiNhd.png) This is my regex: ``` @\[.*\] ``` I would appreciate assistance in isolating the occurrences.
2015/05/07
[ "https://Stackoverflow.com/questions/30099243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517782/" ]
The problem here is that you are using greedy quantifier (`*`). To capture all you need, you should use lazy quantifier (`*?`) with a global modifier: ``` /(@\[.*?\])/g ``` Take a look here <https://regex101.com/r/pH0gA5/1>
This should work : ``` @\[(.*?)\] ``` **Details :** **(.\*?)** : match everything in a non-greedy way and capture it. Because the \*? quantifier is lazy (non-greedy), it matches as few characters as possible to allow the overall match attempt to succeed, i.e. `text1`. For the match attempt that starts at a given position, a lazy quantifier gives you the shortest match.
30,099,243
I want to get all matches of `@[SomeText]` pattern in a string. For example, for this string: here is `@[text1]` some text `@[text2]` I want `@[text1]` and `@[text2]`. I'm using Regex Hero to check my pattern matching online, and my pattern works fine when there's one expression to match, For example: ``` here is @[text1] text ``` but with more then one, I get both matches with the text in the middle. ![enter image description here](https://i.stack.imgur.com/aiNhd.png) This is my regex: ``` @\[.*\] ``` I would appreciate assistance in isolating the occurrences.
2015/05/07
[ "https://Stackoverflow.com/questions/30099243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517782/" ]
This should work : ``` @\[(.*?)\] ``` **Details :** **(.\*?)** : match everything in a non-greedy way and capture it. Because the \*? quantifier is lazy (non-greedy), it matches as few characters as possible to allow the overall match attempt to succeed, i.e. `text1`. For the match attempt that starts at a given position, a lazy quantifier gives you the shortest match.
.\* is greedy by default, so it only finds one match, treating "text1] and @[text2" as the text between the two square brackets. If you add a questions mark after the .\* then it will find the minimum number of characters before reaching a ]. So the regex \@[.\*?] do what you want.
30,099,243
I want to get all matches of `@[SomeText]` pattern in a string. For example, for this string: here is `@[text1]` some text `@[text2]` I want `@[text1]` and `@[text2]`. I'm using Regex Hero to check my pattern matching online, and my pattern works fine when there's one expression to match, For example: ``` here is @[text1] text ``` but with more then one, I get both matches with the text in the middle. ![enter image description here](https://i.stack.imgur.com/aiNhd.png) This is my regex: ``` @\[.*\] ``` I would appreciate assistance in isolating the occurrences.
2015/05/07
[ "https://Stackoverflow.com/questions/30099243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517782/" ]
The problem here is that you are using greedy quantifier (`*`). To capture all you need, you should use lazy quantifier (`*?`) with a global modifier: ``` /(@\[.*?\])/g ``` Take a look here <https://regex101.com/r/pH0gA5/1>
.\* is greedy by default, so it only finds one match, treating "text1] and @[text2" as the text between the two square brackets. If you add a questions mark after the .\* then it will find the minimum number of characters before reaching a ]. So the regex \@[.\*?] do what you want.
65,983,747
Please is there a manner to create user if not exit. ``` CREATE USER sup_ WITH PASSWORD 'postgres'; ``` When i executed two times got error saying that sup\_ exist. How should i do please to correct my query ? Thank you?
2021/01/31
[ "https://Stackoverflow.com/questions/65983747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14110758/" ]
What makes your `tailrec` version slow is ``` isCompleted(succeed.size, notApplicable.size, failed.size) ``` taking the size of a linked list in Scala is linear in the size, and you're computing the size of all three lists (at least two of which you're never using (and you don't use any of them by `Default`)). On the `n`th iteration of the `tailrec`, you're going to walk `n` list nodes between the size computations, so `n` iterations of `tailrec` is at least `O(n^2)`. Passing the lists themselves to `isCompleted` (as you effectively do in the `foldLeft` version) and checking `isEmpty` should dramatically speed things up (especially in the `Default` case).
Assuming we have those case classes: ``` case class InspectorReport(succeed: List[ActionRule], notApplicable: List[ActionRule], failed: List[ActionRule]) case class ActionRule() case class EvalResult(success: Boolean, missing: List[String], unmatched: List[String]) ``` And the evaluator: ``` class ActionRuleService { def eval(actionRule: ActionRule, payload: JsObject): EvalResult = EvalResult(true, List(), List()) } val actionRuleService = new ActionRuleService ``` I would try something like this: ``` def analyzePayload(payload: JsObject, actionRules: List[ActionRule]): InspectorReport = { val evaluated = actionRules.map(actionRule => (actionRule, actionRuleService.eval(actionRule, payload))) val (success, failed) = evaluated.partition(_._2.success) val (missing, unmatched) = failed.partition(_._2.missing.nonEmpty) InspectorReport(success.map(_._1), missing.map(_._1), unmatched.map(_._1)) } ``` Or: ``` def analyzePayload(payload: JsObject, actionRules: List[ActionRule]): InspectorReport = { val evaluated = actionRules.map(actionRule => (actionRule, actionRuleService.eval(actionRule, payload))) val success = evaluated.collect { case (actionRule, EvalResult(true, _, _)) => actionRule } val missing = evaluated.collect { case (actionRule, EvalResult(false, missing, _)) if missing.nonEmpty => actionRule } val unmatched = evaluated.collect { case (actionRule, EvalResult(false, missing, unmatched)) if missing.isEmpty && unmatched.nonEmpty => actionRule } InspectorReport(success, missing, unmatched) } ```
12,385,446
I am using ActionBarSherlock Tabs with Fragments in my applications: ``` public class ExampleActivity extends SherlockFragmentActivity{} ``` I have added an Options Menu in the Action Bar. The problem is while this does show the options menu on the click of virtual button in the action bar, it doesn't do so when the physical button is pressed. I would like the options menu to be displayed when the physical menu button is pressed. ``` @Override public boolean onCreateOptionsMenu(Menu menu) { //return super.onCreateOptionsMenu(menu); MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_prefs: Intent i = new Intent(this,ShowSettingsActivity.class); startActivityForResult(i, requestCode); return true; case R.id.menu_faq: startActivity(new Intent(this, AboutApp.class)); return true; case R.id.menu_contact: startActivity(new Intent(this, FeedbackApp.class)); return true; default: return super.onOptionsItemSelected(item); } } ``` And in res/menu/options\_menu.xml: ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_settings" android:title="@string/menu_settings" android:icon="@drawable/ic_settings_dark" android:orderInCategory="100" android:showAsAction="always"> <menu android:id="@+id/e"> <item android:id="@+id/menu_prefs" android:title="@string/menu_prefs"/> <item android:id="@+id/menu_faq" android:title="@string/menu_faq"/> <item android:id="@+id/menu_contact" android:title="@string/menu_contact"/> </menu> </item> </menu> ``` If I remove the sub-menu, it displays the options menu on click of physical button.
2012/09/12
[ "https://Stackoverflow.com/questions/12385446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100747/" ]
1) Their example uses ``` mVideoView.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { if (loadingDialog.isShowing()) { loadingDialog.dismiss(); mVideoView.start(); } } }); ``` 2) Are you using Vitamio Bundle as a library? If so, just open res/layout/mediacontroller.xml and edit the filename TextView to add visibility invisible (using gone breaks the ui) Here you can customize as much as you want ``` <TextView android:id="@+id/mediacontroller_file_name" style="@style/MediaController_Text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:ellipsize="marquee" android:singleLine="true" android:visibility="invisible" /> ```
``` mVideoView.setMediaController() ``` sets the MediaController widget to be displayed. Just create your own from scratch.
35,940,678
I'm trying to make a set of views (*that include several textviews and buttons - all in **different parent layouts**, but in the same activity*) invisible if a particular condition is evaluated to false. The conventional way to do that would be: ``` findViewById(R.id.myview).setVisibility(View.INVISIBLE); ``` My question is, will I have to do this for all the views one by one that I want to be invisible, And then toggle them back when I want them visible? Or, is there a way to avoid the code-repetition?
2016/03/11
[ "https://Stackoverflow.com/questions/35940678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5038993/" ]
If the `View`s are in different parents , you can't do it directly, but you can implement a method to change the visibility of a bunch of `View`s if you want to keep your code clean: ``` List<View> relatedViews = new ArrayList<>(); // ... relatedViews.add(view1); relatedViews.add(view2); relatedViews.add(view3); // ... changeVisibility(relatedViews, View.INVISIBLE); // ... private void changeVisibility(List<View> views, int visibility) { for (View view : views) { view.setVisibility(visibility); } } ``` As a side note, you may want to change the visibility to `View.GONE` instead of `View.INVISIBLE` so it doesn't take any space in the layout.
you can use something like this. It's not the most elegant solution but works. The idea is give to each view that you want to hide a same content description, because in the same layout you can not use same id for multiple view. With the same content description you can find all views in your layout and hide them. That's an example considering the first layout as Linear. You can change obviously ;) ``` public class TestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); LinearLayout rootLayout = (LinearLayout)findViewById(R.id.rootLayout); int childcount = rootLayout.getChildCount(); for (int i=0; i < childcount; i++){ View v = rootLayout.getChildAt(i); if(v.getContentDescription() != null && v.getContentDescription().equals("invisibleView")){ v.setVisibility(View.INVISIBLE); //I suggest you to use GONE instead of INVISIBLE to remove the space of the view } } } } ``` in your xml give to the object that you want to hide this property ``` android:contentDescription="invisibleView" ```
35,940,678
I'm trying to make a set of views (*that include several textviews and buttons - all in **different parent layouts**, but in the same activity*) invisible if a particular condition is evaluated to false. The conventional way to do that would be: ``` findViewById(R.id.myview).setVisibility(View.INVISIBLE); ``` My question is, will I have to do this for all the views one by one that I want to be invisible, And then toggle them back when I want them visible? Or, is there a way to avoid the code-repetition?
2016/03/11
[ "https://Stackoverflow.com/questions/35940678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5038993/" ]
If the `View`s are in different parents , you can't do it directly, but you can implement a method to change the visibility of a bunch of `View`s if you want to keep your code clean: ``` List<View> relatedViews = new ArrayList<>(); // ... relatedViews.add(view1); relatedViews.add(view2); relatedViews.add(view3); // ... changeVisibility(relatedViews, View.INVISIBLE); // ... private void changeVisibility(List<View> views, int visibility) { for (View view : views) { view.setVisibility(visibility); } } ``` As a side note, you may want to change the visibility to `View.GONE` instead of `View.INVISIBLE` so it doesn't take any space in the layout.
Use `varargs` method for show or hide multiple views. for example if you have views like view1, view2.....etc then just call `setVisibility(View.VISIBLE,view1,view2)` ``` public static void setVisibility(int visibility, View... views){ for (View view : views){ view.setVisibility(visibility); } } ```
35,940,678
I'm trying to make a set of views (*that include several textviews and buttons - all in **different parent layouts**, but in the same activity*) invisible if a particular condition is evaluated to false. The conventional way to do that would be: ``` findViewById(R.id.myview).setVisibility(View.INVISIBLE); ``` My question is, will I have to do this for all the views one by one that I want to be invisible, And then toggle them back when I want them visible? Or, is there a way to avoid the code-repetition?
2016/03/11
[ "https://Stackoverflow.com/questions/35940678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5038993/" ]
you can use something like this. It's not the most elegant solution but works. The idea is give to each view that you want to hide a same content description, because in the same layout you can not use same id for multiple view. With the same content description you can find all views in your layout and hide them. That's an example considering the first layout as Linear. You can change obviously ;) ``` public class TestActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); LinearLayout rootLayout = (LinearLayout)findViewById(R.id.rootLayout); int childcount = rootLayout.getChildCount(); for (int i=0; i < childcount; i++){ View v = rootLayout.getChildAt(i); if(v.getContentDescription() != null && v.getContentDescription().equals("invisibleView")){ v.setVisibility(View.INVISIBLE); //I suggest you to use GONE instead of INVISIBLE to remove the space of the view } } } } ``` in your xml give to the object that you want to hide this property ``` android:contentDescription="invisibleView" ```
Use `varargs` method for show or hide multiple views. for example if you have views like view1, view2.....etc then just call `setVisibility(View.VISIBLE,view1,view2)` ``` public static void setVisibility(int visibility, View... views){ for (View view : views){ view.setVisibility(visibility); } } ```
3,642,467
I'm stuck with the following problem, this is the first time I use capybara, have you an idea how I can solve this issue, thanks I use rails 3.0.0 and the following gems ``` gem 'rails', '3.0.0' gem 'capybara' gem 'database_cleaner' gem 'cucumber-rails' gem 'cucumber' gem 'rspec-rails' gem 'spork' gem 'launchy' ``` I have the following in my senario ``` When I go to the new customer page And I fill in "Email" with "john@example.com" ``` in my customer\_steps.rb I have ``` When /^I fill in "([^"]*)" with "([^"]*)"$/ do |arg1, arg2| fill_in arg1, :with => arg2 end ``` In my view ``` - form_for @customer do |f| = f.label :email, 'Email' = f.text_field :email = f.submit ``` When I run my scenario I get this error message ``` Scenario: Register new customer # features/manage_customers.feature:7 When I go to the new customer page # features/step_definitions/customer_steps.rb:1 And I fill in "Email" with "john@example.com" # features/step_definitions/customer_steps.rb:5 cannot fill in, no text field, text area or password field with id, name, or label 'Email' found (Capybara::ElementNotFound) ./features/step_definitions/customer_steps.rb:6:in `/^I fill in "([^"]*)" with "([^"]*)"$/' features/manage_customers.feature:9:in `And I fill in "Email" with "john@example.com"' ```
2010/09/04
[ "https://Stackoverflow.com/questions/3642467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255240/" ]
I found my mistake!!! ``` When I go to the new customer page ``` before the step was ``` When /^I go to (.+)$/ do |page_name| path_to page_name end ``` I forgot the visit... ``` When /^I go to (.+)$/ do |page_name| visit path_to(page_name) end ```
Use this id of the field instead, which should be like > > And I fill in "customer\_email" with "john@example.com" > > > if the @customer is a object customer model
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
alternatively this may help toconvert datagrigview to datatable. ``` Dim dt As New DataTable dt = (DirectCast(DataGridView1.DataSource, DataTable)) ``` do a direct casting on datagridview for datatable can get the final result.
What about this : ``` DataView dv = (DataView)(dataGridView1.DataSource); dt = dv.ToTable(); ``` Works for all case!
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
alternatively this may help toconvert datagrigview to datatable. ``` Dim dt As New DataTable dt = (DirectCast(DataGridView1.DataSource, DataTable)) ``` do a direct casting on datagridview for datatable can get the final result.
I wrote something like this: ``` private DataTable GetDataGridViewAsDataTable(DataGridView _DataGridView) { try { if (_DataGridView.ColumnCount == 0) return null; DataTable dtSource = new DataTable(); //////create columns foreach(DataGridViewColumn col in _DataGridView.Columns) { if (col.ValueType == null) dtSource.Columns.Add(col.Name, typeof(string)); else dtSource.Columns.Add(col.Name, col.ValueType); dtSource.Columns[col.Name].Caption = col.HeaderText; } ///////insert row data foreach(DataGridViewRow row in _DataGridView.Rows) { DataRow drNewRow = dtSource.NewRow(); foreach(DataColumn col in dtSource.Columns) { drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value; } dtSource.Rows.Add(drNewRow); } return dtSource; } catch { return null; } } ```
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
alternatively this may help toconvert datagrigview to datatable. ``` Dim dt As New DataTable dt = (DirectCast(DataGridView1.DataSource, DataTable)) ``` do a direct casting on datagridview for datatable can get the final result.
``` DataTable dt = new DataTable(); dt = ((DataTable)DataGridView1.DataSource); ```
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
If you need a reference to the actual DataTable source, try this ``` ((DataRowView)DataGridView1.Rows[0].DataBoundItem).DataView.Table ``` don't forget to process errors.
What about this : ``` DataView dv = (DataView)(dataGridView1.DataSource); dt = dv.ToTable(); ``` Works for all case!
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
I wrote something like this: ``` private DataTable GetDataGridViewAsDataTable(DataGridView _DataGridView) { try { if (_DataGridView.ColumnCount == 0) return null; DataTable dtSource = new DataTable(); //////create columns foreach(DataGridViewColumn col in _DataGridView.Columns) { if (col.ValueType == null) dtSource.Columns.Add(col.Name, typeof(string)); else dtSource.Columns.Add(col.Name, col.ValueType); dtSource.Columns[col.Name].Caption = col.HeaderText; } ///////insert row data foreach(DataGridViewRow row in _DataGridView.Rows) { DataRow drNewRow = dtSource.NewRow(); foreach(DataColumn col in dtSource.Columns) { drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value; } dtSource.Rows.Add(drNewRow); } return dtSource; } catch { return null; } } ```
What about this : ``` DataView dv = (DataView)(dataGridView1.DataSource); dt = dv.ToTable(); ``` Works for all case!
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
``` DataTable dt = new DataTable(); dt = ((DataTable)DataGridView1.DataSource); ```
What about this : ``` DataView dv = (DataView)(dataGridView1.DataSource); dt = dv.ToTable(); ``` Works for all case!
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
If you need a reference to the actual DataTable source, try this ``` ((DataRowView)DataGridView1.Rows[0].DataBoundItem).DataView.Table ``` don't forget to process errors.
I wrote something like this: ``` private DataTable GetDataGridViewAsDataTable(DataGridView _DataGridView) { try { if (_DataGridView.ColumnCount == 0) return null; DataTable dtSource = new DataTable(); //////create columns foreach(DataGridViewColumn col in _DataGridView.Columns) { if (col.ValueType == null) dtSource.Columns.Add(col.Name, typeof(string)); else dtSource.Columns.Add(col.Name, col.ValueType); dtSource.Columns[col.Name].Caption = col.HeaderText; } ///////insert row data foreach(DataGridViewRow row in _DataGridView.Rows) { DataRow drNewRow = dtSource.NewRow(); foreach(DataColumn col in dtSource.Columns) { drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value; } dtSource.Rows.Add(drNewRow); } return dtSource; } catch { return null; } } ```
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
If you need a reference to the actual DataTable source, try this ``` ((DataRowView)DataGridView1.Rows[0].DataBoundItem).DataView.Table ``` don't forget to process errors.
``` DataTable dt = new DataTable(); dt = ((DataTable)DataGridView1.DataSource); ```
5,208,114
I have one form that is a CRUD, this form can manage any data from many tables, if a table has foreign keys the CRUD found the tables and columns for respectives columns of the current table, so in the DataGridView can show columns as CheckBox, TextBox or ComboBox I do all this BEFORE the DataGridView is filled with the data, so I can't use this: ``` dataGridView1.DataSource = dtCurrent; ``` I need something like this: ``` dtCurrent = dataGridView1.DataSource; ``` But just give a null I have tried with **ExtensionMethod** to the DataGridView: ``` public static DataTable ToDataTable(this DataGridView dataGridView, string tableName) { DataGridView dgv = dataGridView; DataTable table = new DataTable(tableName); // Crea las columnas for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { table.Columns.Add(dgv.Columns[iCol].Name); } /** * THIS DOES NOT WORK */ // Agrega las filas /*for (int i = 0; i < dgv.Rows.Count; i++) { // Obtiene el DataBound de la fila y copia los valores de la fila DataRowView boundRow = (DataRowView)dgv.Rows[i].DataBoundItem; var cells = new object[boundRow.Row.ItemArray.Length]; for (int iCol = 0; iCol < boundRow.Row.ItemArray.Length; iCol++) { cells[iCol] = boundRow.Row.ItemArray[iCol]; } // Agrega la fila clonada table.Rows.Add(cells); }*/ /* THIS WORKS BUT... */ foreach (DataGridViewRow row in dgv.Rows) { DataRow datarw = table.NewRow(); for (int iCol = 0; iCol < dgv.Columns.Count; iCol++) { datarw[iCol] = row.Cells[iCol].Value; } table.Rows.Add(datarw); } return table; } ``` I use: ``` dtCurrent = dataGridView1.ToDataTable(dtCurrent.TableName); ``` The code does not works when: ``` int affectedUpdates = dAdapter.Update(dtCurrent); ``` I get an Exception about duplicated values (translated from spanish): **The changes requested to the table were not successful because they would create duplicate values in the index, primary key or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.** I just need to Update changes in the DataGridView using DataTable
2011/03/06
[ "https://Stackoverflow.com/questions/5208114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453348/" ]
I wrote something like this: ``` private DataTable GetDataGridViewAsDataTable(DataGridView _DataGridView) { try { if (_DataGridView.ColumnCount == 0) return null; DataTable dtSource = new DataTable(); //////create columns foreach(DataGridViewColumn col in _DataGridView.Columns) { if (col.ValueType == null) dtSource.Columns.Add(col.Name, typeof(string)); else dtSource.Columns.Add(col.Name, col.ValueType); dtSource.Columns[col.Name].Caption = col.HeaderText; } ///////insert row data foreach(DataGridViewRow row in _DataGridView.Rows) { DataRow drNewRow = dtSource.NewRow(); foreach(DataColumn col in dtSource.Columns) { drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value; } dtSource.Rows.Add(drNewRow); } return dtSource; } catch { return null; } } ```
``` DataTable dt = new DataTable(); dt = ((DataTable)DataGridView1.DataSource); ```
4,034,881
I have some code which re-arranges some items on a form, but only one SQL query. All my tables aren't locked before the code runs but for some reason I get an error when running: ``` DoCmd.RunSQL ("Select * Into MasterTable From Year07 Where 'ClassName' = '7A'") ``` Error: > > The database engine could not lock table because it is already in use by another person or process. (Error 3211) To complete this operation, a table currently in use by another user must be locked. Wait for the other user to finish working with the table, and then try the operation again. > > > Any ideas what I can do to stop the table being locked?
2010/10/27
[ "https://Stackoverflow.com/questions/4034881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489028/" ]
Is MasterTable included in your form's Record Source? If so, you can't replace it, or modify its structure, while the form is open. Apart from the table lock issue, there is a logic error in the SELECT statement. ``` Where 'ClassName' = '7A' ``` The string, *ClassName*, will never be equal to the string, *7A*. Therefore your SELECT can never return any records. If ClassName is the name of a field in your Year07 table, discard the quotes which surround the field name. ``` Where ClassName = '7A' ```
I have seen this when you re-open a database after Access has crashed. Typically for me a reboot has fixed this.
4,034,881
I have some code which re-arranges some items on a form, but only one SQL query. All my tables aren't locked before the code runs but for some reason I get an error when running: ``` DoCmd.RunSQL ("Select * Into MasterTable From Year07 Where 'ClassName' = '7A'") ``` Error: > > The database engine could not lock table because it is already in use by another person or process. (Error 3211) To complete this operation, a table currently in use by another user must be locked. Wait for the other user to finish working with the table, and then try the operation again. > > > Any ideas what I can do to stop the table being locked?
2010/10/27
[ "https://Stackoverflow.com/questions/4034881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489028/" ]
I'm guessing, but if you're using a form that is bound to MasterTable, you can't run a query to replace it with a new MasterTable while you've got it open in the form. I would suggest that you get rid of the MakeTable query (SELECT INTO) and instead use a plain append query (INSERT). You'll want to clean out the old data before appending the new, though. Basically, a MakeTable query is, in my opinion, something that does not belong in a production app, and any process that you've automated with a MakeTable query should be replaced instead with a persistent temp table that is cleared before the new data is appended to it.
I have seen this when you re-open a database after Access has crashed. Typically for me a reboot has fixed this.
4,034,881
I have some code which re-arranges some items on a form, but only one SQL query. All my tables aren't locked before the code runs but for some reason I get an error when running: ``` DoCmd.RunSQL ("Select * Into MasterTable From Year07 Where 'ClassName' = '7A'") ``` Error: > > The database engine could not lock table because it is already in use by another person or process. (Error 3211) To complete this operation, a table currently in use by another user must be locked. Wait for the other user to finish working with the table, and then try the operation again. > > > Any ideas what I can do to stop the table being locked?
2010/10/27
[ "https://Stackoverflow.com/questions/4034881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489028/" ]
Is MasterTable included in your form's Record Source? If so, you can't replace it, or modify its structure, while the form is open. Apart from the table lock issue, there is a logic error in the SELECT statement. ``` Where 'ClassName' = '7A' ``` The string, *ClassName*, will never be equal to the string, *7A*. Therefore your SELECT can never return any records. If ClassName is the name of a field in your Year07 table, discard the quotes which surround the field name. ``` Where ClassName = '7A' ```
What version of MSAccess? Not sure about newer ones, but for Access 2003 and previous, if you were sure nobody was in the database, you could clear up locks after a crash by deleting the .ldb file.
4,034,881
I have some code which re-arranges some items on a form, but only one SQL query. All my tables aren't locked before the code runs but for some reason I get an error when running: ``` DoCmd.RunSQL ("Select * Into MasterTable From Year07 Where 'ClassName' = '7A'") ``` Error: > > The database engine could not lock table because it is already in use by another person or process. (Error 3211) To complete this operation, a table currently in use by another user must be locked. Wait for the other user to finish working with the table, and then try the operation again. > > > Any ideas what I can do to stop the table being locked?
2010/10/27
[ "https://Stackoverflow.com/questions/4034881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489028/" ]
I'm guessing, but if you're using a form that is bound to MasterTable, you can't run a query to replace it with a new MasterTable while you've got it open in the form. I would suggest that you get rid of the MakeTable query (SELECT INTO) and instead use a plain append query (INSERT). You'll want to clean out the old data before appending the new, though. Basically, a MakeTable query is, in my opinion, something that does not belong in a production app, and any process that you've automated with a MakeTable query should be replaced instead with a persistent temp table that is cleared before the new data is appended to it.
What version of MSAccess? Not sure about newer ones, but for Access 2003 and previous, if you were sure nobody was in the database, you could clear up locks after a crash by deleting the .ldb file.
4,034,881
I have some code which re-arranges some items on a form, but only one SQL query. All my tables aren't locked before the code runs but for some reason I get an error when running: ``` DoCmd.RunSQL ("Select * Into MasterTable From Year07 Where 'ClassName' = '7A'") ``` Error: > > The database engine could not lock table because it is already in use by another person or process. (Error 3211) To complete this operation, a table currently in use by another user must be locked. Wait for the other user to finish working with the table, and then try the operation again. > > > Any ideas what I can do to stop the table being locked?
2010/10/27
[ "https://Stackoverflow.com/questions/4034881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489028/" ]
Is MasterTable included in your form's Record Source? If so, you can't replace it, or modify its structure, while the form is open. Apart from the table lock issue, there is a logic error in the SELECT statement. ``` Where 'ClassName' = '7A' ``` The string, *ClassName*, will never be equal to the string, *7A*. Therefore your SELECT can never return any records. If ClassName is the name of a field in your Year07 table, discard the quotes which surround the field name. ``` Where ClassName = '7A' ```
I'm guessing, but if you're using a form that is bound to MasterTable, you can't run a query to replace it with a new MasterTable while you've got it open in the form. I would suggest that you get rid of the MakeTable query (SELECT INTO) and instead use a plain append query (INSERT). You'll want to clean out the old data before appending the new, though. Basically, a MakeTable query is, in my opinion, something that does not belong in a production app, and any process that you've automated with a MakeTable query should be replaced instead with a persistent temp table that is cleared before the new data is appended to it.
21,803,844
I created simple Java project in IntelliJ, one class (RandomizedQueue) and generated JUnit test class for it. So it's just two files and they both are in the same directory - src. Everything compiled and all was well. For some time. Then *suddenly* - it stopped with this error: ``` java: cannot find symbol symbol: class RandomizedQueue location: class RandomizedQueueTest ``` I tried everything I could think of. Recreating a project worked for a while but the same error reappeared (without any obvious reason). I can't find any logic in this! Compilation from cmd does work. I tried deleting everything from class and test - and I still can't make an instance in test method. [here is the whole project](http://www.sendspace.com/file/tflge2)
2014/02/15
[ "https://Stackoverflow.com/questions/21803844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1823524/" ]
See those white x-es next to the class name? ![enter image description here](https://i.stack.imgur.com/jMTYz.png) Somehow you have excluded RandomizedQueue class from the compilation. ![enter image description here](https://i.stack.imgur.com/ZTMXd.png) Remove it from the excludes and everything will be back to where it was before. PS: Coursera FTW :-)
I have the same issue every once in a while in my gradle projects (I'm on IntelliJ 2018.2.4 now). The solution is to open a terminal and execute `gradlew idea`.
21,803,844
I created simple Java project in IntelliJ, one class (RandomizedQueue) and generated JUnit test class for it. So it's just two files and they both are in the same directory - src. Everything compiled and all was well. For some time. Then *suddenly* - it stopped with this error: ``` java: cannot find symbol symbol: class RandomizedQueue location: class RandomizedQueueTest ``` I tried everything I could think of. Recreating a project worked for a while but the same error reappeared (without any obvious reason). I can't find any logic in this! Compilation from cmd does work. I tried deleting everything from class and test - and I still can't make an instance in test method. [here is the whole project](http://www.sendspace.com/file/tflge2)
2014/02/15
[ "https://Stackoverflow.com/questions/21803844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1823524/" ]
See those white x-es next to the class name? ![enter image description here](https://i.stack.imgur.com/jMTYz.png) Somehow you have excluded RandomizedQueue class from the compilation. ![enter image description here](https://i.stack.imgur.com/ZTMXd.png) Remove it from the excludes and everything will be back to where it was before. PS: Coursera FTW :-)
I had the same problem. I fixed it by rebuilding the package in which the tests were located. Right click on the package and select "rebuild 'package name'".
21,803,844
I created simple Java project in IntelliJ, one class (RandomizedQueue) and generated JUnit test class for it. So it's just two files and they both are in the same directory - src. Everything compiled and all was well. For some time. Then *suddenly* - it stopped with this error: ``` java: cannot find symbol symbol: class RandomizedQueue location: class RandomizedQueueTest ``` I tried everything I could think of. Recreating a project worked for a while but the same error reappeared (without any obvious reason). I can't find any logic in this! Compilation from cmd does work. I tried deleting everything from class and test - and I still can't make an instance in test method. [here is the whole project](http://www.sendspace.com/file/tflge2)
2014/02/15
[ "https://Stackoverflow.com/questions/21803844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1823524/" ]
I had the same problem. I fixed it by rebuilding the package in which the tests were located. Right click on the package and select "rebuild 'package name'".
I have the same issue every once in a while in my gradle projects (I'm on IntelliJ 2018.2.4 now). The solution is to open a terminal and execute `gradlew idea`.
31,858,613
I need help copying and pasting an image with the path in a cell. In F2 I have my Image Path C:\Users\gaetan.affolter\Desktop\test.jpg but the path is changing all the time (I need Variable F2) I got an error "Unable to get the insert properity of the picture Class" ``` Sub Copiarimg() Dim pic As Picture With ActiveSheet Set pic = .Pictures.Insert(Range("f2").Value) With .Range("e9:g22") pic.Top = .Top pic.Left = .Left pic.Width = .Width pic.Height = .Height End With End With End Sub ```
2015/08/06
[ "https://Stackoverflow.com/questions/31858613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5008296/" ]
Your code seems to work ok. Are you missing a "." before `Range("f2").Value`? You can use the `Dir` function to test that the pic file exists. ``` Sub Copiarimg() Dim pic As Picture Dim picSource As String With ActiveSheet picSource = .Range("f2").Value If Dir$(picSource) <> "" Then Set pic = .Pictures.Insert(picSource) With .Range("e9:g22") pic.Top = .Top pic.Left = .Left pic.Width = .Width pic.Height = .Height End With Else MsgBox "Cannot find the file " & picSource End If End With End Sub ```
I see no problem with your code, check two things: 1. Does your file really exist, 2. Does the path contain an extra space at the end
104,323
I have created 3 scenes `(StartMenu, Game, Win)` and added all of them to built setting with proper arrangement. `StartMenu` Scene has a button `start` which should take game to second `Game` Scene when onClick event is called on it. The onClick event of `start` button is mapped to `LevelManager` Empty Object. That object has a script `LevelManager` whose code I have posted. I have added all those scenes to built settings.![](https://i.stack.imgur.com/y1mCx.png) but still I am getting this error: ``` Level 'name'(-1) couldn't be loaded because it has been added to the built settings. To add a level to the built settings use menu File->Built settings. UnityEngine.Application:LoadLevel(String) LevelManager:LoadLevel(String) (at Assets/Scripts/LevelManager.cs:8) // 8 line is Application.LoadLevel line) UnityEngine.EventSystems.EventSystem:Update() ``` **LevelManager.cs** ``` using UnityEngine; using System.Collections; public class LevelManager : MonoBehaviour { public void LoadLevel(string name){ Application.LoadLevel(name); } public void QuitRequest(){ Debug.Log("Quit Requested"); } } ``` Error Code snapshot(couldn't copy):![](https://i.stack.imgur.com/I5jhb.png) ![](https://i.stack.imgur.com/U3795.png)
2015/07/21
[ "https://gamedev.stackexchange.com/questions/104323", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/42870/" ]
Error message tells you exactly what is wrong. You are trying to load scene with name `name`. You have to change the string in the editor in OnClick handler to `Game` in your case.
I was having the same issue. It worked one day, and not the next. I found that for some reason, it lost the link in the picture I provided. It worked fine after I updated all of the buttons on all of the scenes. [![Screenshot](https://i.stack.imgur.com/JB5X1.jpg)](https://i.stack.imgur.com/JB5X1.jpg)
19,593,917
What's the easiest way to do a quick wildcard search on a field from the console? I don't care against guarding against SQL injection. I'm using **PostgreSQL**. Searching for `title` with strings containing "emerging' This works but is somewhat cumbersome. Curious if there was a shorthand? ``` Product.where("title @@ :q", q: "emerging") ``` Equally cumbersome but no longer appear to work for me in Rails 4: ``` Product.where("title ILIKE ?", "emerging") Product.where("title ilike :q", q: "emerging") ``` I guess I'm looking for something like `Product.where(title: "*emerging*")`
2013/10/25
[ "https://Stackoverflow.com/questions/19593917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/63761/" ]
This should do it: ``` word = 'emerging' Product.where('title ILIKE ?', "%#{word}%") ``` * The ILIKE makes the search not sensitive to the case (PostgreSQL feature!) * the "%" wildcard makes the search match every product having a title containing "word" inside with (or without) stuff before and/or after.
Use `LIKE`, like this: ``` Product.where('title LIKE ?', '%emerging%') ```
51,418,352
I have the following application error when accessing <https://..appRoot../TestJavaMongo/test/mongo/all> by following the doc: <https://medium.com/@blumareks/mongodb-for-you-a-hardcore-java-cloud-developer-f67b909834f4> I'm testing to connect the Mongo DB service from the Liberty Java CF app on IBM Cloud. How to resolve the error? > > ``` Error 500: com.mongodb.MongoTimeoutException: Timed out after > 30000 ms while waiting for a server that matches > WritableServerSelector. Client view of cluster state is {type=UNKNOWN, > servers=[{address=sl-us-south-1-portal.16.dblayer.com:50233, > type=UNKNOWN, state=CONNECTING, > exception={com.mongodb.MongoSocketWriteException: Exception sending > message}, > > > caused by {javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.h: > PKIX path building failed: > java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl > could not build a valid CertPath.; internal cause is: > java.security.cert.CertPathValidatorException: The certificate issued > by CN=\*\*\*\*\*\*\*\*\* is not trusted; internal cause is: > java.security.cert.CertPathValidatorException: Certificate chaining > error}, ... > > > $ keytool -list -v -keystore mongoKeyStore Enter keystore password: > > Keystore type: JKS Keystore provider: SUN > > > Your keystore contains 1 entry > > > Alias name: mykey Creation date: 24/06/2017 Entry type: > trustedCertEntry > > > Owner: CN=mwsadows@us.ibm.com-0b24b0ff06b390e0cc5e803aecd5ec82 Issuer: > CN=mwsadows@us.ibm.com-0b24b0ff06b390e0cc5e803aecd5ec82 Serial number: > 59491e1b Valid from: Tue Jun 20 23:07:39 AEST 2017 until: Sat Jun 20 > 23:00:00 AEST 2037 Certificate fingerprints: MD5: > A4:54:21:6A:52:E1:8B:CB:07:CC:25:A3:3B:1A:8B:05 SHA1: > BE:5D:AE:94:C3:A5:37:2D:43:B2:E7:FC:CF:39:19:EE:B8:10:29:9B SHA256: > D5:6B:EB:D6:88:36:D4:77:06:9B:8D:2B:83:39:9B:95:A5:E3:22:09:99:EF:32:89:31:E2:88:C2:86:58:83:62 > Signature algorithm name: SHA512withRSA Version: 3 > > > Extensions: > > > 1: ObjectId: 2.5.29.35 Criticality=false AuthorityKeyIdentifier [ KeyIdentifier [ 0000: 65 2C 47 37 D6 4C B7 24 E9 A1 AA 14 01 4A 12 > AD e,G7.L.$.....J.. 0010: 63 E0 7C 56 > > c..V ] ] > > > 2: ObjectId: 2.5.29.19 Criticality=false BasicConstraints:[ CA:true PathLen:2147483647 ] > > > 3: ObjectId: 2.5.29.37 Criticality=false ExtendedKeyUsages [ serverAuth clientAuth ] > > > 4: ObjectId: 2.5.29.15 Criticality=true KeyUsage [ Key\_CertSign ] > > > 5: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: 65 2C 47 37 D6 4C B7 24 E9 A1 AA 14 01 4A 12 > AD e,G7.L.$.....J.. 0010: 63 E0 7C 56 > > c..V ] ] > > >
2018/07/19
[ "https://Stackoverflow.com/questions/51418352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7238981/" ]
I recently had this same issue with our db provider, they sent me their .crt file and I had to create a keystore with it. ``` keytool -import -alias "name" -file "/path/to/file" -keystore "/path/to/keystore/file" -storetype pkcs12 -storepass "keystorepass" ``` then at my main class I defined truststore and truststore pass: ``` System.setProperty("javax.net.ssl.trustStore", "/path/to/keystore/file"); System.setProperty("javax.net.ssl.trustStorePassword", "keystorepass"); ``` Hope it helps.
As the error says, the certificate isn't trusted. I see that tutorial has a pretty substantial section on importing the certificate from the Mongo service into a keystore and setting it as the trustStore for Liberty. Double check those steps to make sure that you: 1. Correctly obtained and saved the certificate from the Mongo service, ie that it is not incomplete or corrupted or anything. 2. Check that you created a keystore using the `keytool` command in the correct location, and that you replaced the one from the repository if you checked that out, and that it includes the certificate you saved for the Mongo server. You can use `keytool -list -v -keystore <path_to_keystore.jks>` on your keystore to see what's inside. 3. Check that you configured Liberty correctly to use this keystore as your trust store. I think the tutorial is a little misleading, as it says > > A typical application will also need to set several JVM system > properties to ensure that the client presents an TLS/SSL certificate > to the MongoDB server: javax.net.ssl.keyStore The path to a key store > containing the client’s TLS/SSL certificates > javax.net.ssl.keyStorePassword The password to access this key store > > > However, I think you actually need to set this keystore you created as the value for the `javax.net.ssl.trustStore` property (and set the `trustStorePassword` property accordingly) because the JVM uses the trustStore to check the public keys of hosts it is connecting to for trust. Either way, make sure those properties are set appropriately and that Liberty is not throwing up any errors in the logs related to it on server start. Once you have verified the whole chain (that you have exported the correct certificate, that you have created a keystore that contains that certificate, and that you have set that keystore as the truststore for the server,) you should have security set up to talk to the Mongo server correctly. If you have changed the existing truststore while the server is running you have to restart the server for it to pick up those changes.
387,752
* Why do the compile times not vary significantly between different era CPUs, even though disk (NVMe vs. HDD) and CPU benchmarks vary significantly in performance? * Why does disabling hyperthreading affect performance significantly with the Ryzen CPU? Over the past few months I have seen some different machines all running Linux with CPUs that varied from about 9 years since release and some recently released. The newer CPUs received much higher benchmark numbers from [cpubenchmark.net](https://www.cpubenchmark.net/). Details below including compile times for the Linux 4.4.176 kernel using Ubuntu 18.04. To put it simply, CPUs that scored multiple times faster at [cpubenchmark.net](https://www.cpubenchmark.net/) most certainly did not decrease compile times by the same factor. In fact, sometimes meager improvements were seen. What would be the bottleneck to change or fix? The Ryzen machine has all the latest hardware gadgets. Or is this a case of synthetic benchmarks vs. reality? [This question](https://softwareengineering.stackexchange.com/q/59692/47826) touches on the topic of benchmarking by compile time comparison, but does not explore the (lack of) variability in build times seen. > > * Recent Ryzen 2950X system > + Single Thread Rating: 2208 > + Disk: NVMe > + Source: Linux kernel, 4.4.176, compiled with .config from Ubuntu Xenial > + Invocation: make -j32 > + Compile time: 25997u 4910s **17:25** wall time > * Same system, with hyperthreading (or whatever AMD calls it) turned **off** > + Source: Linux kernel 4.4.176, same .config file > + Invocation: make -j16 > + Compile time: 10561u 1796s **13:44** wall time > > > That is an over 20% reduction in compile time amounting to a difference of 3 minutes 41 seconds, from 17:25 to 13:44. Just by disabling the hyperthreading feature. **New Data**, 2019-03-08 Compile time actually decreased monotonically, but not linearly, until `make -j12`, taking **12:46** with a dozen processes. The compile time then increased slowly and monotonically out to the last run of `make -j24`. Hyperthreading was *off* for these tests. Whatever the bottleneck is, is hit after 12 parallel threads. **New Data** - 2019-03-27 After tuning the X.M.P. memory profile, but still with single channel access, the times decreased until a minimum was reached of **10:08.5** at 16 threads; as many threads as cores (no HT enabled). With one exception the compile times increased slowly to 10:41 at 32 threads. Once dual channel memory was enabled, times decreased to **6:47.5** at 17 threads. After this point, the timings wobbled up and down with another minimum of 6:46.6 at 20 threads. This is probably a fluke and likely not a definitive point at which a minimum point is reached. Only a maximum of 24 threads was tested in this case. It seems that memory is a huge factor and the bottleneck for this processor. Tossing more processing threads at the problem once memory is configured optimally does not seem to help or hinder much. **Conclusion** * Memory is a major potential bottleneck for this CPU and must be configured properly to take advantage of the processor. * The old rule of as many threads as processors seems to hold. * Hyperthreading was not tested beyond the first tests, so no conclusions can be drawn in that area, other than that the default configuration with single channel memory probably starves the hyperthreaded cores for memory accesses.
2019/02/27
[ "https://softwareengineering.stackexchange.com/questions/387752", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/47826/" ]
Just off the top of my head: 1. CPU performance is not the only thing that affects compile times. 2. Benchmarks do not always take into account performance factors that affect real programs. 3. Cache affinity can be a larger factor than CPU speed. 4. Compilers don't always exploit concurrency mechanisms effectively. 5. In general, programs like compilers can be written in such a way that they exploit (or fail to exploit) specific CPU characteristics. 6. Concurrency mechanisms have overhead. If the software is not getting any benefit from the concurrency offered, the result is a *net negative.* In short, it's complicated. A highly complex task like compilation is not always well-modeled by benchmarks. You have to consider other real-world factors that affect overall performance, like seek times on hard disks and the manner in which the code is written. For a simple, but rather dramatic example of this, see [here](https://stackoverflow.com/questions/54814597/confusion-about-different-running-times-of-two-algorithms-in-c).
Compiling a large project may involve reading hundreds of source files, and writing hundreds of intermediate (object) files. Then reading all those intermediate files again to compile the finished executable or library. Often, the biggest bottleneck isn't the CPU but the disk subsystem (the disk drive itself and the disk controller). Multicore or hyperthreaded CPUs can confuse the system further by sending multiple simultaneous read or write requests to the disk subsystem, each asking for different files. If the disk has a high seek time, then this could even slow down performance when compared with a single core CPU. The impact of disk performance can be particularly acute when the files are on a remote server, and mapped as a drive on the local machine.
387,752
* Why do the compile times not vary significantly between different era CPUs, even though disk (NVMe vs. HDD) and CPU benchmarks vary significantly in performance? * Why does disabling hyperthreading affect performance significantly with the Ryzen CPU? Over the past few months I have seen some different machines all running Linux with CPUs that varied from about 9 years since release and some recently released. The newer CPUs received much higher benchmark numbers from [cpubenchmark.net](https://www.cpubenchmark.net/). Details below including compile times for the Linux 4.4.176 kernel using Ubuntu 18.04. To put it simply, CPUs that scored multiple times faster at [cpubenchmark.net](https://www.cpubenchmark.net/) most certainly did not decrease compile times by the same factor. In fact, sometimes meager improvements were seen. What would be the bottleneck to change or fix? The Ryzen machine has all the latest hardware gadgets. Or is this a case of synthetic benchmarks vs. reality? [This question](https://softwareengineering.stackexchange.com/q/59692/47826) touches on the topic of benchmarking by compile time comparison, but does not explore the (lack of) variability in build times seen. > > * Recent Ryzen 2950X system > + Single Thread Rating: 2208 > + Disk: NVMe > + Source: Linux kernel, 4.4.176, compiled with .config from Ubuntu Xenial > + Invocation: make -j32 > + Compile time: 25997u 4910s **17:25** wall time > * Same system, with hyperthreading (or whatever AMD calls it) turned **off** > + Source: Linux kernel 4.4.176, same .config file > + Invocation: make -j16 > + Compile time: 10561u 1796s **13:44** wall time > > > That is an over 20% reduction in compile time amounting to a difference of 3 minutes 41 seconds, from 17:25 to 13:44. Just by disabling the hyperthreading feature. **New Data**, 2019-03-08 Compile time actually decreased monotonically, but not linearly, until `make -j12`, taking **12:46** with a dozen processes. The compile time then increased slowly and monotonically out to the last run of `make -j24`. Hyperthreading was *off* for these tests. Whatever the bottleneck is, is hit after 12 parallel threads. **New Data** - 2019-03-27 After tuning the X.M.P. memory profile, but still with single channel access, the times decreased until a minimum was reached of **10:08.5** at 16 threads; as many threads as cores (no HT enabled). With one exception the compile times increased slowly to 10:41 at 32 threads. Once dual channel memory was enabled, times decreased to **6:47.5** at 17 threads. After this point, the timings wobbled up and down with another minimum of 6:46.6 at 20 threads. This is probably a fluke and likely not a definitive point at which a minimum point is reached. Only a maximum of 24 threads was tested in this case. It seems that memory is a huge factor and the bottleneck for this processor. Tossing more processing threads at the problem once memory is configured optimally does not seem to help or hinder much. **Conclusion** * Memory is a major potential bottleneck for this CPU and must be configured properly to take advantage of the processor. * The old rule of as many threads as processors seems to hold. * Hyperthreading was not tested beyond the first tests, so no conclusions can be drawn in that area, other than that the default configuration with single channel memory probably starves the hyperthreaded cores for memory accesses.
2019/02/27
[ "https://softwareengineering.stackexchange.com/questions/387752", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/47826/" ]
This turns out to be more of a hardware problem than a software engineering issue, perhaps. There is a memory setting in modern BIOS' called **X.M.P.** This setting is by default at the lowest common denominator for what memory the mainboard supports. To take full advantage of the memory installed, one has to go into the BIOS and set the X.M.P. profile. There seems to be only one profile available in this case besides the default setting. The other issue is setting *dual channel* memory access vs. single channel memory access. That will take a moment with the manual to determine how to install the memory to enable this setting. A test build with some different software took more than 20% off the build time with the better X.M.P. setting vs. the previous default setting. So there is some hope for better performance to come. Once tuned, I will report back with the final numbers for comparison. **2019-03-27** Conclusions Memory was the major bottleneck for this CPU. See question for more details and conclusions. This question has not garnered much interest, so this will likely be the last entry unless someone specifically asks a question.
Compiling a large project may involve reading hundreds of source files, and writing hundreds of intermediate (object) files. Then reading all those intermediate files again to compile the finished executable or library. Often, the biggest bottleneck isn't the CPU but the disk subsystem (the disk drive itself and the disk controller). Multicore or hyperthreaded CPUs can confuse the system further by sending multiple simultaneous read or write requests to the disk subsystem, each asking for different files. If the disk has a high seek time, then this could even slow down performance when compared with a single core CPU. The impact of disk performance can be particularly acute when the files are on a remote server, and mapped as a drive on the local machine.
195,175
I am new to this community, but I am working on a site that requires implementation of a user/password/register check upon entry, which would check against a database, or write to the database, in the case of registration. I have experience with XHTML and CSS, and just discovered RoR. I honestly have very little insight into how to achieve my goal using just XHTML, so I decided to learn Ruby, taking a shot in the dark. I'm wondering if there's an easier language, or more direct fix that I should be implementing instead. Any thoughts?
2008/10/12
[ "https://Stackoverflow.com/questions/195175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27171/" ]
I would recommend looking at [Restful Authentication](http://github.com/technoweenie/restful-authentication/tree/master). Also, for good code examples in general, have a look at [Altered Beast](http://github.com/technoweenie/altered_beast/tree). It's a forum built in Ruby on Rails and it uses Restful Authentication.
Are you looking for information on how to implement user authentication in Rails? You could try [`acts_as_authenticated`](http://wiki.rubyonrails.org/rails/pages/Acts_as_authenticated).
195,175
I am new to this community, but I am working on a site that requires implementation of a user/password/register check upon entry, which would check against a database, or write to the database, in the case of registration. I have experience with XHTML and CSS, and just discovered RoR. I honestly have very little insight into how to achieve my goal using just XHTML, so I decided to learn Ruby, taking a shot in the dark. I'm wondering if there's an easier language, or more direct fix that I should be implementing instead. Any thoughts?
2008/10/12
[ "https://Stackoverflow.com/questions/195175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27171/" ]
I would recommend looking at [Restful Authentication](http://github.com/technoweenie/restful-authentication/tree/master). Also, for good code examples in general, have a look at [Altered Beast](http://github.com/technoweenie/altered_beast/tree). It's a forum built in Ruby on Rails and it uses Restful Authentication.
Check out the book called [Agile Web Development with rails](http://pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition). It has two parts, a step-by-step walkthrough of creating an application, and a reference section on rails. I recently started a contract job where I chose RoR as my framework without any experience in it. This book has been an immense resource to teach me Ruby on Rails. It also specifically teaches how to implement the authorization you are talking about.
39,841,339
I can call compile this fortran code 'test.f90' ``` subroutine test(g,o) double precision, intent(in):: g double precision, intent(out):: o o=g*g end subroutine ``` with ``` gfortran -shared -fPIC test.f90 -o test.so ``` and create this wraper function test.jl for Julia: ``` function test(s) res=Float64[1] ccall((:test_, "./test.so"), Ptr{Float64}, (Ptr{Float64}, Ptr{Float64}), &s,res); return res[1] end ``` and run these command with the sought for output: ``` julia> include("./test.jl") julia> test(3.4) 11.559999999999999 ``` But I want to return an array instead of a scalar. I think I have tried everyting, including using the iso\_c\_binding, in [this](https://stackoverflow.com/questions/28373693/calling-a-fortran-function-from-julia-returning-an-array-unknown-function-seg) answer. But everything I try throws errors at me looking like this: ``` ERROR: MethodError: `convert` has no method matching convert(::Type{Ptr{Array{Int32,2}}}, ::Array{Int32,2}) This may have arisen from a call to the constructor Ptr{Array{Int32,2}}(...), since type constructors fall back to convert methods. Closest candidates are: call{T}(::Type{T}, ::Any) convert{T}(::Type{Ptr{T}}, ::UInt64) convert{T}(::Type{Ptr{T}}, ::Int64) ... [inlined code] from ./deprecated.jl:417 in unsafe_convert at ./no file:429496729 ``` As an example, I'd like to call the following code from julia: ``` subroutine arr(array) ! or arr(n,array) implicit none integer*8, intent(inout) :: array(:,:) !integer*8, intent(in) :: n !integer*8, intent(out) :: array(n,n) integer :: i, j do i=1,size(array,2) !n do j=1,size(array,1) !n array(i,j)= j+i enddo enddo end subroutine ``` Using the commented out variant is also an alternative as only changing the argument doesn't seem to be useful when calling from julia. So how do I call fortran subroutines with arrays from Julia?
2016/10/03
[ "https://Stackoverflow.com/questions/39841339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4483861/" ]
When using `ccall`, Julia arrays should be passed as pointers of the element type, along with an extra argument describing the size. Your example `test.f90` should be: ``` subroutine arr(n,array) implicit none integer*8, intent(in) :: n integer*8, intent(out) :: array(n,n) integer :: i, j do i=1,size(array,2) !n do j=1,size(array,1) !n array(i,j)= j+i enddo enddo end subroutine ``` Compiled as before with ``` gfortran -shared -fPIC test.f90 -o test.so ``` Then in Julia: ``` n = 10 X = zeros(Int64,n,n) # 8-byte integers ccall((:arr_, "./test.so"), Void, (Ptr{Int64}, Ptr{Int64}), &n, X) ```
Suggestion: '&n' will cause invalid syntax error for newer versions. And, using Ref is safer than Ptr. You may try: ``` ccall((:arr_, "./test.so"), Cvoid, (Ref{Int64}, Ref{Int64}), Ref(n), X) ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
Actually, this... ``` slides.css('width', w); ``` ... should be sufficient. As `.css` is used as a setter, quoting [**the doc**](http://api.jquery.com/css/): > > ...set one or more CSS properties for **every matched element**. > > > [**Demo**](http://jsfiddle.net/aNDWS/).
`slides.get(j)` returns the DOM object for each `<li>`, rather than the jQuery object. This should work: ``` $( slides.get(j) ).css('width',w); ``` Or, instead of the `for` loop: ``` slides.each(function () { $(this).css('width', w); }); ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
Actually, this... ``` slides.css('width', w); ``` ... should be sufficient. As `.css` is used as a setter, quoting [**the doc**](http://api.jquery.com/css/): > > ...set one or more CSS properties for **every matched element**. > > > [**Demo**](http://jsfiddle.net/aNDWS/).
Try replacing ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` with ``` slides.each(function () { $(this).css('width', w + 'px'); }); ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
I'd change: ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` to: ``` $('#slideshow li').each(function(){ $(this).width(w); }); ```
You're creating an array of those elements, but you actually have to change them on the view, use an `each` and modify `this` ``` var w=$('#slideshow').width(); $("#slideshow ul li").each(function() { $(this).css("width", w); }); ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
Actually, this... ``` slides.css('width', w); ``` ... should be sufficient. As `.css` is used as a setter, quoting [**the doc**](http://api.jquery.com/css/): > > ...set one or more CSS properties for **every matched element**. > > > [**Demo**](http://jsfiddle.net/aNDWS/).
I'd change: ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` to: ``` $('#slideshow li').each(function(){ $(this).width(w); }); ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
I'd change: ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` to: ``` $('#slideshow li').each(function(){ $(this).width(w); }); ```
`slides.get(j)` returns the DOM object for each `<li>`, rather than the jQuery object. This should work: ``` $( slides.get(j) ).css('width',w); ``` Or, instead of the `for` loop: ``` slides.each(function () { $(this).css('width', w); }); ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
Actually, this... ``` slides.css('width', w); ``` ... should be sufficient. As `.css` is used as a setter, quoting [**the doc**](http://api.jquery.com/css/): > > ...set one or more CSS properties for **every matched element**. > > > [**Demo**](http://jsfiddle.net/aNDWS/).
Change ``` slides.eq(j).css('width',w); ``` To ``` slides.eq(j).css('width',w+'px'); ``` `x.width() return 80` While in `css` it should be with `unit` : ``` x.css('width','80px') ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
I'd change: ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` to: ``` $('#slideshow li').each(function(){ $(this).width(w); }); ```
jQuery Solution (slower, easier to implement) ============================================= If jQuery is required for other things in your site, and speed is not really a concern to you, here's the jQuery way to achieve the same result: ``` $("#slideshow li").width(w); ``` Non-jQuery solution (faster) ============================ jQuery is *significantly* slower than simple javascript dom manipulation. Create a simple library for javascript you need - reuse is good. ---------------------------------------------------------------- jQuery is a very large library for doing something so straightforward. *Note: Example uses namespacing. Encapsulation is better, but namespacing is a good start.* ``` var myNS = { elById: document.getElementById, elsByParentId: function (id, optionalTagName) { var tag = optionalTagName || "*"; return myNS.elByID(id).getElementsByTagName(tag); } setWidthForEls: function (els, w) { for (var i=0, c=els.length; i < c; i++){ els[i].style.width = w; }, getWidthOfEl: function (el){ return el.style.width; } setWidthForElsFromEl: function (els, el) { myNS.setWidthForEls(els, myNS.getWidthOfEl(el)); } } ``` ### Then, in the code section you are referring to, you just do: ``` myNS.setWidthForElsFromEl( myNS.elsByParentID("slideshow","li"), myN.elByID("content") ); ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
I'd change: ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` to: ``` $('#slideshow li').each(function(){ $(this).width(w); }); ```
Change ``` slides.eq(j).css('width',w); ``` To ``` slides.eq(j).css('width',w+'px'); ``` `x.width() return 80` While in `css` it should be with `unit` : ``` x.css('width','80px') ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
I'd change: ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` to: ``` $('#slideshow li').each(function(){ $(this).width(w); }); ```
Try replacing ``` for(var j=0;j<slides.length;j++){ slides.get(j).css('width',w); } ``` with ``` slides.each(function () { $(this).css('width', w + 'px'); }); ```
19,815,706
In my little program, I try to unshorten an URL and then check if the link matches my pattern. If it does I want to further process it. But I also need to apply 3 parameter previously known. My code feels very clunky dragging along all 3 parameters to each function. How can I streamline this without promises? ``` var request = require("request"); function expandUrl(shortUrl, a,b,c, callback) { request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { callback(response.request.href, a,b,c); }); } function checklink(unshortenedLink, a, b, c){ matches = unshortenedLink.match(/twitter\.com\/\w+/g); if(matches){ matches.forEach(function(result){ process_twitter_link(result, a, b, c); }); } } function process_twitter_link(link, a, b ,c ){ console.log(link + " " + a + " " + b + " " + c); // std.out: twitter.com/StackJava param_a param_b param_c } expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink); ```
2013/11/06
[ "https://Stackoverflow.com/questions/19815706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493415/" ]
Actually, this... ``` slides.css('width', w); ``` ... should be sufficient. As `.css` is used as a setter, quoting [**the doc**](http://api.jquery.com/css/): > > ...set one or more CSS properties for **every matched element**. > > > [**Demo**](http://jsfiddle.net/aNDWS/).
You're creating an array of those elements, but you actually have to change them on the view, use an `each` and modify `this` ``` var w=$('#slideshow').width(); $("#slideshow ul li").each(function() { $(this).css("width", w); }); ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
[**`np.concatenate()`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html) ``` np.concatenate(df.keyPhrases) #data courtesy vurmux ``` --- ``` array(['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'], dtype='<U5') ``` Another way: ``` import functools import operator functools.reduce(operator.iadd, df.keyPhrases, []) #['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'] ```
``` keyPhrases = df.keyPhrases.tolist() reduce(lambda x, y: x+y, keyPhrases) ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
[**`np.concatenate()`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html) ``` np.concatenate(df.keyPhrases) #data courtesy vurmux ``` --- ``` array(['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'], dtype='<U5') ``` Another way: ``` import functools import operator functools.reduce(operator.iadd, df.keyPhrases, []) #['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'] ```
Found another way to do: ``` df['keyPhrases'] = df['keyPhrases'].str.split(',') #to make arrays df['keyPhrases'] = df['keyPhrases'].astype(str) #back to strings s=''.join(df.keyPhrases).replace('[','').replace(']','\n').replace(',','\n') #replace magic print(s) ``` --- ``` word1 word2 word4 word 5 and 6 word7 word8 etc etc ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
You can use [itertools.chain](https://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.chain.from_iterable) in combination with dataframe column selection: ``` import itertools df = pd.DataFrame({ 'keyPhrases': [ ['word1', 'word2'], ['word4', 'word5', 'word7'], ['word8', 'word9'] ], 'id': [1,2,3] }) for elem in itertools.chain.from_iterable(df['keyPhrases'].values): print(elem) ``` will print: ``` word1 word2 word4 word5 word7 word8 word9 ```
The answer given above for the numpy library really is very good, but I participate by putting a code trellis, not performatic, but in the simplest way to understand. ``` import pandas as pd lista = [[['word1', 'word2']], [['word4', 'word5', 'word6', 'word7']], [['word8', 'word9', 'word10']]] df = pd.DataFrame(lista, columns=['keyPhrases']) list = [] for key in df.keyPhrases: for element in key: list.append(element) list ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
You can use [itertools.chain](https://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.chain.from_iterable) in combination with dataframe column selection: ``` import itertools df = pd.DataFrame({ 'keyPhrases': [ ['word1', 'word2'], ['word4', 'word5', 'word7'], ['word8', 'word9'] ], 'id': [1,2,3] }) for elem in itertools.chain.from_iterable(df['keyPhrases'].values): print(elem) ``` will print: ``` word1 word2 word4 word5 word7 word8 word9 ```
``` keyPhrases = df.keyPhrases.tolist() reduce(lambda x, y: x+y, keyPhrases) ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
A fun way but not recommended ``` df.keyPhrases.sum() Out[520]: ['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'] ```
``` keyPhrases = df.keyPhrases.tolist() reduce(lambda x, y: x+y, keyPhrases) ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
[**`np.concatenate()`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html) ``` np.concatenate(df.keyPhrases) #data courtesy vurmux ``` --- ``` array(['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'], dtype='<U5') ``` Another way: ``` import functools import operator functools.reduce(operator.iadd, df.keyPhrases, []) #['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'] ```
The answer given above for the numpy library really is very good, but I participate by putting a code trellis, not performatic, but in the simplest way to understand. ``` import pandas as pd lista = [[['word1', 'word2']], [['word4', 'word5', 'word6', 'word7']], [['word8', 'word9', 'word10']]] df = pd.DataFrame(lista, columns=['keyPhrases']) list = [] for key in df.keyPhrases: for element in key: list.append(element) list ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
A fun way but not recommended ``` df.keyPhrases.sum() Out[520]: ['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'] ```
Found another way to do: ``` df['keyPhrases'] = df['keyPhrases'].str.split(',') #to make arrays df['keyPhrases'] = df['keyPhrases'].astype(str) #back to strings s=''.join(df.keyPhrases).replace('[','').replace(']','\n').replace(',','\n') #replace magic print(s) ``` --- ``` word1 word2 word4 word 5 and 6 word7 word8 etc etc ```
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
A fun way but not recommended ``` df.keyPhrases.sum() Out[520]: ['word1', 'word2', 'word4', 'word5', 'word7', 'word8', 'word9'] ```
I am not sure about any existing functions which could do this in single line of code. The work around code below can solve your requirement. If there are any other built-in functions that can get this done without struggle, I will be glad to know. ``` import pandas as pd #Existing DF where the data is in the form of list df = pd.DataFrame(columns=['ID', 'value_list']) #New DF where the data should be atomic df_new = pd.DataFrame(columns=['ID', 'value_single']) #Sample Data row_1 = ['A', 'B', 'C', 'D'] row_2 = ['D', 'E', 'F'] row_3 = ['F', 'G'] row_4 = ['H', 'I'] row_5 = ['J'] #Data Push to existing DF row_ = "row_" for i in range(5): df.loc[i, 'ID'] = i df.loc[i, 'value_list'] = eval(row_+str(i+1)) #Data Push to new DF where list is pushed as atomic data counter = 0 i=0 while(i<len(df)): j=0 while(j<len(df['value_list'][i])): df_new.loc[counter, 'ID'] = df['ID'][i] df_new.loc[counter, 'value_single'] = df['value_list'][i][j] counter = counter + 1 j = j+1 i = i+1 print(df_new) ``` [This link](https://mikulskibartosz.name/how-to-split-a-list-inside-a-dataframe-cell-into-rows-in-pandas-9849d8ff2401) could help with your requirement.
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
You can use [itertools.chain](https://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.chain.from_iterable) in combination with dataframe column selection: ``` import itertools df = pd.DataFrame({ 'keyPhrases': [ ['word1', 'word2'], ['word4', 'word5', 'word7'], ['word8', 'word9'] ], 'id': [1,2,3] }) for elem in itertools.chain.from_iterable(df['keyPhrases'].values): print(elem) ``` will print: ``` word1 word2 word4 word5 word7 word8 word9 ```
I am not sure about any existing functions which could do this in single line of code. The work around code below can solve your requirement. If there are any other built-in functions that can get this done without struggle, I will be glad to know. ``` import pandas as pd #Existing DF where the data is in the form of list df = pd.DataFrame(columns=['ID', 'value_list']) #New DF where the data should be atomic df_new = pd.DataFrame(columns=['ID', 'value_single']) #Sample Data row_1 = ['A', 'B', 'C', 'D'] row_2 = ['D', 'E', 'F'] row_3 = ['F', 'G'] row_4 = ['H', 'I'] row_5 = ['J'] #Data Push to existing DF row_ = "row_" for i in range(5): df.loc[i, 'ID'] = i df.loc[i, 'value_list'] = eval(row_+str(i+1)) #Data Push to new DF where list is pushed as atomic data counter = 0 i=0 while(i<len(df)): j=0 while(j<len(df['value_list'][i])): df_new.loc[counter, 'ID'] = df['ID'][i] df_new.loc[counter, 'value_single'] = df['value_list'][i][j] counter = counter + 1 j = j+1 i = i+1 print(df_new) ``` [This link](https://mikulskibartosz.name/how-to-split-a-list-inside-a-dataframe-cell-into-rows-in-pandas-9849d8ff2401) could help with your requirement.
56,240,713
I'v been looking through a LOT of websites and i did not find any awnser, So let's say I have a DataGridView with a Column and the Rows are (assuming today's date is `21/05/2019` (`dd/mm/yyyy`)) * 22/05/2019 * 22/04/2019 * 21/01/2019 So I want the first one to be in red (because its 1 day off today's date) I want the second one to be in orange (because it entered the -1 month mark) And the last one should be normal because its far from -1 month. I've tryed this: ``` var dateminusonemonth = DateTime.Today.AddMonths(-1); foreach (DataGridViewRow row in dgproduit.Rows) if (Convert.ToString(dateminusonemonth) = txtboxdatecontrole.Text) { row.DefaultCellStyle.BackColor = Color.Red; } ``` But it doesn't work at all and I dont know where to look at... EDIT : This is what i want, but i cant get it to work [Change row color in DataGridView based on column date](https://stackoverflow.com/questions/40749012/change-row-color-in-datagridview-based-on-column-date) EDIT : It worked ! with this code : ``` DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; foreach (DataGridViewRow row in dgproduit.Rows) { string cellText = row.Cells["datecontrole"].Value + ""; if (DateTime.TryParse(cellText, out expirationDate)) { if (expirationDate < now) row.DefaultCellStyle.BackColor = Color.OrangeRed; else if (expirationDate > thirtyDaysAgo) row.DefaultCellStyle.BackColor = Color.LightBlue; } } ```
2019/05/21
[ "https://Stackoverflow.com/questions/56240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491471/" ]
You can use [itertools.chain](https://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.chain.from_iterable) in combination with dataframe column selection: ``` import itertools df = pd.DataFrame({ 'keyPhrases': [ ['word1', 'word2'], ['word4', 'word5', 'word7'], ['word8', 'word9'] ], 'id': [1,2,3] }) for elem in itertools.chain.from_iterable(df['keyPhrases'].values): print(elem) ``` will print: ``` word1 word2 word4 word5 word7 word8 word9 ```
Found another way to do: ``` df['keyPhrases'] = df['keyPhrases'].str.split(',') #to make arrays df['keyPhrases'] = df['keyPhrases'].astype(str) #back to strings s=''.join(df.keyPhrases).replace('[','').replace(']','\n').replace(',','\n') #replace magic print(s) ``` --- ``` word1 word2 word4 word 5 and 6 word7 word8 etc etc ```
20,444,479
Is it possible to reliably replace mobile phone with some testing tool as not to test with mobile? I 've tried Resizer and Responsive Design Bookmarklet, however I am not satisfied... Thank you
2013/12/07
[ "https://Stackoverflow.com/questions/20444479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642344/" ]
What LinkinTED said and Chrome also has options in their developer tools. If you press F12 and click in the settings icon, bottom right... Then go to Overrides. There you can choose different sizes and user agents. Very handy. Even BETTER than that is using Chrome Canary. They have a new feature called Emulation. I would recommend this the most. Just gotta download Chrome Canary. <https://developers.google.com/chrome-developer-tools/docs/mobile-emulation> What's also really cool about this Canary feature is you can even test device pixel density. So that way if you ever do something to support "retina" displays, you can test it with that. I've used it when I made a website with a JavaScript plugin that would swap my images with @2x ones. So I didn't have to always upload it to a server and test it on a phone.
I have added the [web developer addon for Firefox](https://addons.mozilla.org/nl/firefox/addon/web-developer/). Via resize > view responsive you can see the page in the following screen sizes: * Mobile portrait (320x480) * Mobile landscape (480x320) * Small tablet portrait (600x800) * Small tablet landscape (800x600) * Tablet portrait (768x1024) * Tablet landscape (1024x768)
59,187,754
I have a pandas DataFrame of the form: ``` id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3 1 71 2018-10-17 20:12:43+00:00 114429 3 2 71 2018-10-17 20:12:43+00:00 114431 79 3 71 2019-11-06 00:51:14+00:00 216009 100 4 71 2019-11-06 00:51:14+00:00 216011 150 5 71 2019-11-06 00:51:14+00:00 216013 180 6 92 2019-12-01 00:51:14+00:00 114430 19 7 92 2019-12-01 00:51:14+00:00 114433 79 8 92 2019-12-01 00:51:14+00:00 114434 100 ``` What I'm trying to do is fill in the missing `sequence_no` **per** `id`/`start_time` combo. For example, the `id`/`start_time` pairing of `71` and `2018-10-17 20:12:43+00:00`, is missing sequence\_no 114430. For each added missing sequence\_no, I also need average/interpolate the missing `value` column value. So, the final processing of the above data would end up looking like: ``` id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3 1 71 2018-10-17 20:12:43+00:00 114429 3 2 71 2018-10-17 20:12:43+00:00 114430 41 ** 3 71 2018-10-17 20:12:43+00:00 114431 79 4 71 2019-11-06 00:51:14+00:00 216009 100 5 71 2019-11-06 00:51:14+00:00 216010 125 ** 6 71 2019-11-06 00:51:14+00:00 216011 150 7 71 2019-11-06 00:51:14+00:00 216012 165 ** 8 71 2019-11-06 00:51:14+00:00 216013 180 9 92 2019-12-01 00:51:14+00:00 114430 19 10 92 2019-12-01 00:51:14+00:00 114431 39 ** 11 92 2019-12-01 00:51:14+00:00 114432 59 ** 12 92 2019-12-01 00:51:14+00:00 114433 79 13 92 2019-12-01 00:51:14+00:00 114434 100 ``` (`**` added to the right of newly inserted rows for easier readability) My original solution for doing this relied heavily on Python loops over a large table of data, so it seemed like the ideal place for numpy and pandas to shine. Leaning on SO answers like [Pandas: create rows to fill numeric gaps](https://stackoverflow.com/a/44578607/3362468), I came up with: ``` import pandas as pd import numpy as np # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a new DataFrame with the min/max `sequence_no` values for each `id`/`start_time` pairing by_start = df.groupby(['start_time', 'id']) ranges = by_start.agg( sequence_min=('sequence_no', np.min), sequence_max=('sequence_no', np.max) ) reset = ranges.reset_index() mins = reset['sequence_min'] maxes = reset['sequence_max'] # Use those min/max values to generate a sequence with ALL values in that range expanded = pd.DataFrame(dict( start_time=reset['start_time'].repeat(maxes - mins + 1), id=reset['id'].repeat(maxes - mins + 1), sequence_no=np.concatenate([np.arange(mins, maxes + 1) for mins, maxes in zip(mins, maxes)]) )) # Use the above generated DataFrame as an index to generate the missing rows, then interpolate expanded_index = pd.MultiIndex.from_frame(expanded) df.set_index( ['start_time', 'id', 'sequence_no'] ).reindex(expanded_index).interpolate() ``` The output is correct, but it runs at almost exactly the same speed as my lots-of-python-loops solution. I'm sure there are places I could cut out a few steps, but the slowest part in my testing appears to be the `reindex`. Given that the real world data consists of almost a million rows (operated on frequently), are there any obvious ways to gain some performance advantage over what I've already written? Any ways I can speed up this transformation? Update 9/12/2019 ================ Combining the merge solution from [this answer](https://stackoverflow.com/a/59279322/3362468) with the original construction of the expanded dataframe yields that fastest results so far, when tested on a sufficiently large dataset: ``` import pandas as pd import numpy as np # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a ranges df with groupby and agg ranges = df.groupby(['start_time', 'id'])['sequence_no'].agg([ ('sequence_min', np.min), ('sequence_max', np.max) ]) reset = ranges.reset_index() mins = reset['sequence_min'] maxes = reset['sequence_max'] # Use those min/max values to generate a sequence with ALL values in that range expanded = pd.DataFrame(dict( start_time=reset['start_time'].repeat(maxes - mins + 1), id=reset['id'].repeat(maxes - mins + 1), sequence_no=np.concatenate([np.arange(mins, maxes + 1) for mins, maxes in zip(mins, maxes)]) )) # merge expanded and df merge = expanded.merge(df, on=['start_time', 'id', 'sequence_no'], how='left') # interpolate and assign values merge['value'] = merge['value'].interpolate() ```
2019/12/05
[ "https://Stackoverflow.com/questions/59187754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362468/" ]
using `merge` instead of `reindex` may speed things up. Also, using map instead of the list comprehension may as well. ``` # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a ranges df with groupby and agg ranges = df.groupby(['start_time', 'id'])['sequence_no'].agg([('sequence_min', np.min), ('sequence_max', np.max)]) # map with range to create the sequence number rnage ranges['sequence_no'] = list(map(lambda x,y: range(x,y), ranges.pop('sequence_min'), ranges.pop('sequence_max')+1)) # explode you DataFrame new_df = ranges.explode('sequence_no') # merge new_df and df merge = new_df.reset_index().merge(df, on=['start_time', 'id', 'sequence_no'], how='left') # interpolate and assign values merge['value'] = merge['value'].interpolate() start_time id sequence_no value 0 2018-10-17 20:12:43+00:00 71 114428 3.0 1 2018-10-17 20:12:43+00:00 71 114429 3.0 2 2018-10-17 20:12:43+00:00 71 114430 41.0 3 2018-10-17 20:12:43+00:00 71 114431 79.0 4 2019-11-06 00:51:14+00:00 71 216009 100.0 5 2019-11-06 00:51:14+00:00 71 216010 125.0 6 2019-11-06 00:51:14+00:00 71 216011 150.0 7 2019-11-06 00:51:14+00:00 71 216012 165.0 8 2019-11-06 00:51:14+00:00 71 216013 180.0 9 2019-12-01 00:51:14+00:00 92 114430 19.0 10 2019-12-01 00:51:14+00:00 92 114431 39.0 11 2019-12-01 00:51:14+00:00 92 114432 59.0 12 2019-12-01 00:51:14+00:00 92 114433 79.0 13 2019-12-01 00:51:14+00:00 92 114434 100.0 ```
A shorter version of the `merge` solution: ``` df.groupby(['start_time', 'id'])['sequence_no']\ .apply(lambda x: np.arange(x.min(), x.max() + 1))\ .explode().reset_index()\ .merge(df, on=['start_time', 'id', 'sequence_no'], how='left')\ .interpolate() ``` Output: ``` start_time id sequence_no value 0 2018-10-17 20:12:43+00:00 71 114428 3.0 1 2018-10-17 20:12:43+00:00 71 114429 3.0 2 2018-10-17 20:12:43+00:00 71 114430 41.0 3 2018-10-17 20:12:43+00:00 71 114431 79.0 4 2019-11-06 00:51:14+00:00 71 216009 100.0 5 2019-11-06 00:51:14+00:00 71 216010 125.0 6 2019-11-06 00:51:14+00:00 71 216011 150.0 7 2019-11-06 00:51:14+00:00 71 216012 165.0 8 2019-11-06 00:51:14+00:00 71 216013 180.0 9 2019-12-01 00:51:14+00:00 92 114430 19.0 10 2019-12-01 00:51:14+00:00 92 114431 39.0 11 2019-12-01 00:51:14+00:00 92 114432 59.0 12 2019-12-01 00:51:14+00:00 92 114433 79.0 13 2019-12-01 00:51:14+00:00 92 114434 100.0 ```
59,187,754
I have a pandas DataFrame of the form: ``` id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3 1 71 2018-10-17 20:12:43+00:00 114429 3 2 71 2018-10-17 20:12:43+00:00 114431 79 3 71 2019-11-06 00:51:14+00:00 216009 100 4 71 2019-11-06 00:51:14+00:00 216011 150 5 71 2019-11-06 00:51:14+00:00 216013 180 6 92 2019-12-01 00:51:14+00:00 114430 19 7 92 2019-12-01 00:51:14+00:00 114433 79 8 92 2019-12-01 00:51:14+00:00 114434 100 ``` What I'm trying to do is fill in the missing `sequence_no` **per** `id`/`start_time` combo. For example, the `id`/`start_time` pairing of `71` and `2018-10-17 20:12:43+00:00`, is missing sequence\_no 114430. For each added missing sequence\_no, I also need average/interpolate the missing `value` column value. So, the final processing of the above data would end up looking like: ``` id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3 1 71 2018-10-17 20:12:43+00:00 114429 3 2 71 2018-10-17 20:12:43+00:00 114430 41 ** 3 71 2018-10-17 20:12:43+00:00 114431 79 4 71 2019-11-06 00:51:14+00:00 216009 100 5 71 2019-11-06 00:51:14+00:00 216010 125 ** 6 71 2019-11-06 00:51:14+00:00 216011 150 7 71 2019-11-06 00:51:14+00:00 216012 165 ** 8 71 2019-11-06 00:51:14+00:00 216013 180 9 92 2019-12-01 00:51:14+00:00 114430 19 10 92 2019-12-01 00:51:14+00:00 114431 39 ** 11 92 2019-12-01 00:51:14+00:00 114432 59 ** 12 92 2019-12-01 00:51:14+00:00 114433 79 13 92 2019-12-01 00:51:14+00:00 114434 100 ``` (`**` added to the right of newly inserted rows for easier readability) My original solution for doing this relied heavily on Python loops over a large table of data, so it seemed like the ideal place for numpy and pandas to shine. Leaning on SO answers like [Pandas: create rows to fill numeric gaps](https://stackoverflow.com/a/44578607/3362468), I came up with: ``` import pandas as pd import numpy as np # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a new DataFrame with the min/max `sequence_no` values for each `id`/`start_time` pairing by_start = df.groupby(['start_time', 'id']) ranges = by_start.agg( sequence_min=('sequence_no', np.min), sequence_max=('sequence_no', np.max) ) reset = ranges.reset_index() mins = reset['sequence_min'] maxes = reset['sequence_max'] # Use those min/max values to generate a sequence with ALL values in that range expanded = pd.DataFrame(dict( start_time=reset['start_time'].repeat(maxes - mins + 1), id=reset['id'].repeat(maxes - mins + 1), sequence_no=np.concatenate([np.arange(mins, maxes + 1) for mins, maxes in zip(mins, maxes)]) )) # Use the above generated DataFrame as an index to generate the missing rows, then interpolate expanded_index = pd.MultiIndex.from_frame(expanded) df.set_index( ['start_time', 'id', 'sequence_no'] ).reindex(expanded_index).interpolate() ``` The output is correct, but it runs at almost exactly the same speed as my lots-of-python-loops solution. I'm sure there are places I could cut out a few steps, but the slowest part in my testing appears to be the `reindex`. Given that the real world data consists of almost a million rows (operated on frequently), are there any obvious ways to gain some performance advantage over what I've already written? Any ways I can speed up this transformation? Update 9/12/2019 ================ Combining the merge solution from [this answer](https://stackoverflow.com/a/59279322/3362468) with the original construction of the expanded dataframe yields that fastest results so far, when tested on a sufficiently large dataset: ``` import pandas as pd import numpy as np # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a ranges df with groupby and agg ranges = df.groupby(['start_time', 'id'])['sequence_no'].agg([ ('sequence_min', np.min), ('sequence_max', np.max) ]) reset = ranges.reset_index() mins = reset['sequence_min'] maxes = reset['sequence_max'] # Use those min/max values to generate a sequence with ALL values in that range expanded = pd.DataFrame(dict( start_time=reset['start_time'].repeat(maxes - mins + 1), id=reset['id'].repeat(maxes - mins + 1), sequence_no=np.concatenate([np.arange(mins, maxes + 1) for mins, maxes in zip(mins, maxes)]) )) # merge expanded and df merge = expanded.merge(df, on=['start_time', 'id', 'sequence_no'], how='left') # interpolate and assign values merge['value'] = merge['value'].interpolate() ```
2019/12/05
[ "https://Stackoverflow.com/questions/59187754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362468/" ]
using `merge` instead of `reindex` may speed things up. Also, using map instead of the list comprehension may as well. ``` # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a ranges df with groupby and agg ranges = df.groupby(['start_time', 'id'])['sequence_no'].agg([('sequence_min', np.min), ('sequence_max', np.max)]) # map with range to create the sequence number rnage ranges['sequence_no'] = list(map(lambda x,y: range(x,y), ranges.pop('sequence_min'), ranges.pop('sequence_max')+1)) # explode you DataFrame new_df = ranges.explode('sequence_no') # merge new_df and df merge = new_df.reset_index().merge(df, on=['start_time', 'id', 'sequence_no'], how='left') # interpolate and assign values merge['value'] = merge['value'].interpolate() start_time id sequence_no value 0 2018-10-17 20:12:43+00:00 71 114428 3.0 1 2018-10-17 20:12:43+00:00 71 114429 3.0 2 2018-10-17 20:12:43+00:00 71 114430 41.0 3 2018-10-17 20:12:43+00:00 71 114431 79.0 4 2019-11-06 00:51:14+00:00 71 216009 100.0 5 2019-11-06 00:51:14+00:00 71 216010 125.0 6 2019-11-06 00:51:14+00:00 71 216011 150.0 7 2019-11-06 00:51:14+00:00 71 216012 165.0 8 2019-11-06 00:51:14+00:00 71 216013 180.0 9 2019-12-01 00:51:14+00:00 92 114430 19.0 10 2019-12-01 00:51:14+00:00 92 114431 39.0 11 2019-12-01 00:51:14+00:00 92 114432 59.0 12 2019-12-01 00:51:14+00:00 92 114433 79.0 13 2019-12-01 00:51:14+00:00 92 114434 100.0 ```
Another solution with `reindex` without using `explode`: ``` result = (df.groupby(["id","start_time"]) .apply(lambda d: d.set_index("sequence_no") .reindex(range(min(d["sequence_no"]),max(d["sequence_no"])+1))) .drop(["id","start_time"],axis=1).reset_index() .interpolate()) print (result) # id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3.0 1 71 2018-10-17 20:12:43+00:00 114429 3.0 2 71 2018-10-17 20:12:43+00:00 114430 41.0 3 71 2018-10-17 20:12:43+00:00 114431 79.0 4 71 2019-11-06 00:51:14+00:00 216009 100.0 5 71 2019-11-06 00:51:14+00:00 216010 125.0 6 71 2019-11-06 00:51:14+00:00 216011 150.0 7 71 2019-11-06 00:51:14+00:00 216012 165.0 8 71 2019-11-06 00:51:14+00:00 216013 180.0 9 92 2019-12-01 00:51:14+00:00 114430 19.0 10 92 2019-12-01 00:51:14+00:00 114431 39.0 11 92 2019-12-01 00:51:14+00:00 114432 59.0 12 92 2019-12-01 00:51:14+00:00 114433 79.0 13 92 2019-12-01 00:51:14+00:00 114434 100.0 ```
59,187,754
I have a pandas DataFrame of the form: ``` id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3 1 71 2018-10-17 20:12:43+00:00 114429 3 2 71 2018-10-17 20:12:43+00:00 114431 79 3 71 2019-11-06 00:51:14+00:00 216009 100 4 71 2019-11-06 00:51:14+00:00 216011 150 5 71 2019-11-06 00:51:14+00:00 216013 180 6 92 2019-12-01 00:51:14+00:00 114430 19 7 92 2019-12-01 00:51:14+00:00 114433 79 8 92 2019-12-01 00:51:14+00:00 114434 100 ``` What I'm trying to do is fill in the missing `sequence_no` **per** `id`/`start_time` combo. For example, the `id`/`start_time` pairing of `71` and `2018-10-17 20:12:43+00:00`, is missing sequence\_no 114430. For each added missing sequence\_no, I also need average/interpolate the missing `value` column value. So, the final processing of the above data would end up looking like: ``` id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3 1 71 2018-10-17 20:12:43+00:00 114429 3 2 71 2018-10-17 20:12:43+00:00 114430 41 ** 3 71 2018-10-17 20:12:43+00:00 114431 79 4 71 2019-11-06 00:51:14+00:00 216009 100 5 71 2019-11-06 00:51:14+00:00 216010 125 ** 6 71 2019-11-06 00:51:14+00:00 216011 150 7 71 2019-11-06 00:51:14+00:00 216012 165 ** 8 71 2019-11-06 00:51:14+00:00 216013 180 9 92 2019-12-01 00:51:14+00:00 114430 19 10 92 2019-12-01 00:51:14+00:00 114431 39 ** 11 92 2019-12-01 00:51:14+00:00 114432 59 ** 12 92 2019-12-01 00:51:14+00:00 114433 79 13 92 2019-12-01 00:51:14+00:00 114434 100 ``` (`**` added to the right of newly inserted rows for easier readability) My original solution for doing this relied heavily on Python loops over a large table of data, so it seemed like the ideal place for numpy and pandas to shine. Leaning on SO answers like [Pandas: create rows to fill numeric gaps](https://stackoverflow.com/a/44578607/3362468), I came up with: ``` import pandas as pd import numpy as np # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a new DataFrame with the min/max `sequence_no` values for each `id`/`start_time` pairing by_start = df.groupby(['start_time', 'id']) ranges = by_start.agg( sequence_min=('sequence_no', np.min), sequence_max=('sequence_no', np.max) ) reset = ranges.reset_index() mins = reset['sequence_min'] maxes = reset['sequence_max'] # Use those min/max values to generate a sequence with ALL values in that range expanded = pd.DataFrame(dict( start_time=reset['start_time'].repeat(maxes - mins + 1), id=reset['id'].repeat(maxes - mins + 1), sequence_no=np.concatenate([np.arange(mins, maxes + 1) for mins, maxes in zip(mins, maxes)]) )) # Use the above generated DataFrame as an index to generate the missing rows, then interpolate expanded_index = pd.MultiIndex.from_frame(expanded) df.set_index( ['start_time', 'id', 'sequence_no'] ).reindex(expanded_index).interpolate() ``` The output is correct, but it runs at almost exactly the same speed as my lots-of-python-loops solution. I'm sure there are places I could cut out a few steps, but the slowest part in my testing appears to be the `reindex`. Given that the real world data consists of almost a million rows (operated on frequently), are there any obvious ways to gain some performance advantage over what I've already written? Any ways I can speed up this transformation? Update 9/12/2019 ================ Combining the merge solution from [this answer](https://stackoverflow.com/a/59279322/3362468) with the original construction of the expanded dataframe yields that fastest results so far, when tested on a sufficiently large dataset: ``` import pandas as pd import numpy as np # Generate dummy data df = pd.DataFrame([ (71, '2018-10-17 20:12:43+00:00', 114428, 3), (71, '2018-10-17 20:12:43+00:00', 114429, 3), (71, '2018-10-17 20:12:43+00:00', 114431, 79), (71, '2019-11-06 00:51:14+00:00', 216009, 100), (71, '2019-11-06 00:51:14+00:00', 216011, 150), (71, '2019-11-06 00:51:14+00:00', 216013, 180), (92, '2019-12-01 00:51:14+00:00', 114430, 19), (92, '2019-12-01 00:51:14+00:00', 114433, 79), (92, '2019-12-01 00:51:14+00:00', 114434, 100), ], columns=['id', 'start_time', 'sequence_no', 'value']) # create a ranges df with groupby and agg ranges = df.groupby(['start_time', 'id'])['sequence_no'].agg([ ('sequence_min', np.min), ('sequence_max', np.max) ]) reset = ranges.reset_index() mins = reset['sequence_min'] maxes = reset['sequence_max'] # Use those min/max values to generate a sequence with ALL values in that range expanded = pd.DataFrame(dict( start_time=reset['start_time'].repeat(maxes - mins + 1), id=reset['id'].repeat(maxes - mins + 1), sequence_no=np.concatenate([np.arange(mins, maxes + 1) for mins, maxes in zip(mins, maxes)]) )) # merge expanded and df merge = expanded.merge(df, on=['start_time', 'id', 'sequence_no'], how='left') # interpolate and assign values merge['value'] = merge['value'].interpolate() ```
2019/12/05
[ "https://Stackoverflow.com/questions/59187754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362468/" ]
A shorter version of the `merge` solution: ``` df.groupby(['start_time', 'id'])['sequence_no']\ .apply(lambda x: np.arange(x.min(), x.max() + 1))\ .explode().reset_index()\ .merge(df, on=['start_time', 'id', 'sequence_no'], how='left')\ .interpolate() ``` Output: ``` start_time id sequence_no value 0 2018-10-17 20:12:43+00:00 71 114428 3.0 1 2018-10-17 20:12:43+00:00 71 114429 3.0 2 2018-10-17 20:12:43+00:00 71 114430 41.0 3 2018-10-17 20:12:43+00:00 71 114431 79.0 4 2019-11-06 00:51:14+00:00 71 216009 100.0 5 2019-11-06 00:51:14+00:00 71 216010 125.0 6 2019-11-06 00:51:14+00:00 71 216011 150.0 7 2019-11-06 00:51:14+00:00 71 216012 165.0 8 2019-11-06 00:51:14+00:00 71 216013 180.0 9 2019-12-01 00:51:14+00:00 92 114430 19.0 10 2019-12-01 00:51:14+00:00 92 114431 39.0 11 2019-12-01 00:51:14+00:00 92 114432 59.0 12 2019-12-01 00:51:14+00:00 92 114433 79.0 13 2019-12-01 00:51:14+00:00 92 114434 100.0 ```
Another solution with `reindex` without using `explode`: ``` result = (df.groupby(["id","start_time"]) .apply(lambda d: d.set_index("sequence_no") .reindex(range(min(d["sequence_no"]),max(d["sequence_no"])+1))) .drop(["id","start_time"],axis=1).reset_index() .interpolate()) print (result) # id start_time sequence_no value 0 71 2018-10-17 20:12:43+00:00 114428 3.0 1 71 2018-10-17 20:12:43+00:00 114429 3.0 2 71 2018-10-17 20:12:43+00:00 114430 41.0 3 71 2018-10-17 20:12:43+00:00 114431 79.0 4 71 2019-11-06 00:51:14+00:00 216009 100.0 5 71 2019-11-06 00:51:14+00:00 216010 125.0 6 71 2019-11-06 00:51:14+00:00 216011 150.0 7 71 2019-11-06 00:51:14+00:00 216012 165.0 8 71 2019-11-06 00:51:14+00:00 216013 180.0 9 92 2019-12-01 00:51:14+00:00 114430 19.0 10 92 2019-12-01 00:51:14+00:00 114431 39.0 11 92 2019-12-01 00:51:14+00:00 114432 59.0 12 92 2019-12-01 00:51:14+00:00 114433 79.0 13 92 2019-12-01 00:51:14+00:00 114434 100.0 ```
34,944,349
How do I get Stack's Maximum memory during runtime. My understanding is that Runtime.getRuntime().maxMemory() will give heap memory. I want to know the stack memory. p.s: I've set -xss as 1m, I wanna test this, so I'm open to suggestions if there is a better way to find that than getting it from the running instance itself.
2016/01/22
[ "https://Stackoverflow.com/questions/34944349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3687170/" ]
You can use JConsole available in JDK\_HOME/bin/jconsole.exe to check the statistics about your program. It will show both Heap/Non-Heap and detailed heap memory usage with graphs.
This is not something you usually care about as typically you want to avoid recursion in Java as using a loop is usually more efficient (Java doesn't have tail call optimisation for example) On Linux you can work this out by reading `/proc/self/maps` which has all the memory mapping the program is using and there is an entry for each stack. e.g. in this example you can see the stack area for thread 669 and 668 ``` 7ff4617ee000-7ff4617f1000 ---p 00000000 00:00 0 7ff4617f1000-7ff4618ef000 rw-p 00000000 00:00 0 [stack:669] 7ff4618ef000-7ff4618f2000 ---p 00000000 00:00 0 7ff4618f2000-7ff461bf0000 rw-p 00000000 00:00 0 [stack:668] ``` The size of this range in hex is `0xFE000` or 1040384 which is almost 1 MB.
930,335
I started refining my sieve rules recently and became a bit unsure about how `:contains` actually works. I checked out <http://sieve.mozdev.org/reference.html> but it still didn't clear up the question I had. Say I have the following rule: ``` if header :contains ["List-Id", "X-Mailinglist", "X-Mailing-List"] [ "ros-dev.reactos.org", "ros-general.reactos.org" ] { fileinto "Lists/ReactOS"; stop; } ``` does this mean (and that **would be** my idea of how I want it to work) automatically that *any of* the listed header fields `["List-Id", "X-Mailinglist", "X-Mailing-List"]` should contain *any of* the given values `["ros-dev.reactos.org", "ros-general.reactos.org"]` or need I say explicitly `if anyof (...)` like this?: ``` if anyof ( header :contains ["List-Id", "X-Mailinglist", "X-Mailing-List"] [ "ros-dev.reactos.org", "ros-general.reactos.org" ] ) { fileinto "Lists/ReactOS"; stop; } ``` ... for this desired outcome? Or do the two lists not match **each element of the first against each element of the second list** *anyway*? **NB:** I know that the comma-separated conditions are affected by `anyof` and `allof` respectively. So `if anyof (condition1, condition2)` means (pseudo-code) `if (condition1 or condition2)` and `if allof (condition1, condition2)` means `if (condition1 and condition2)`. Understanding this aspect is *not* my problem. What I fail to understand, though, is whether `anyof` and `allof` respectively influence either or both **of the lists in a `:contains` clause**. In the above example there is a list for the header fields and a list of values to match against. --- Essentially the question boils down to whether or not there is a semantic difference between the two above snippets. And if not, then whether the first one *means* this: ``` if anyof ( header :contains ["List-Id", "X-Mailinglist", "X-Mailing-List"] "ros-dev.reactos.org", header :contains ["List-Id", "X-Mailinglist", "X-Mailing-List"] "ros-general.reactos.org" ) { fileinto "Lists/ReactOS"; stop; } ``` ... or this: ``` if allof ( header :contains ["List-Id", "X-Mailinglist", "X-Mailing-List"] "ros-dev.reactos.org", header :contains ["List-Id", "X-Mailinglist", "X-Mailing-List"] "ros-general.reactos.org" ) { fileinto "Lists/ReactOS"; stop; } ``` ... or something else altogether.
2015/06/20
[ "https://superuser.com/questions/930335", "https://superuser.com", "https://superuser.com/users/68747/" ]
`anyof` means that if any single header contains one of the alternative values, then the whole condition become `true`, nevertheless the rest headers contains something else. `anyof` ALSO becomes `true` when all the headers contains the predefined values. This is the relaxed condition. `allof` ONLY becomes `true` when all the headers contains the predefined values. This is the strict condition.
As the [reference you indicated](https://thsmi.github.io/sieve-reference/en/test/core/header.html) as well as the [RFC 3028 specification](https://www.rfc-editor.org/rfc/rfc3028#section-5.7) says for the `header` test, > > The "header" test evaluates to true if any header name matches any key. > > > That is, each header name is compared to each value, and if any of the cross-product is a match, then the test passes. The comparator specified (`:contains` in your case) is used for each individual comparison. Basically, your first re-write into `anyof` is correct. The use of `anyof` and `allof` is when there are multiple tests that you want to use, but sometimes you can pack a lot of logic into one "test", as you have here.
69,959
I am trying to understand the order in the following text. > > In einem Laufwettbewerb beendete Gabi das Rennen in 1 Stunde. Fabian kam in 13 Minuten mehr, Gregor in 8 Minuten weniger an. > > > It is not clear to me if Gregor finished 8 minutes less than Fabian or 8 minutes less than Gabi. Shouldn't we use "als" to be more precise or is there something I am missing in the text?
2022/03/15
[ "https://german.stackexchange.com/questions/69959", "https://german.stackexchange.com", "https://german.stackexchange.com/users/16409/" ]
Nein, die Aussage ist auch so eindeutig: Es sind 8 Minuten weniger als Gabi. Die einzige Begründung die ich geben kann, ist, dass das der Sprachgebrauch ist. Bezöge sich die Zeit auf den zweiten Genannten, würde die Aussage mehr zu einem Matherätsel, als zu einer Meldung. > > In einem Laufwettbewerb beendete Gabi das Rennen in 1 Stunde. Fabian kam in 13 Minuten mehr, Gregor in 8 Minuten weniger als jener an. > > > Wenn, dann würde man die Zeiten ja in der Reihenfolge des Eintreffens melden. > > In einem Laufwettbewerb beendete Gabi das Rennen in 1 Stunde. Gregor kam in 5 Minuten mehr an, Fabian noch einmal 8 Minuten später. > > >
you are absolutely right. From the context one can only guess who finished first, who came in second and who was the last. In einem Laufwettbewerb beendete Gabi das Rennen in 1 Stunde. Fabian kam in 13 Minuten mehr, Gregor in 8 Minuten weniger an. Tis is because there is no connection or relation bewtween the three competitors. To be sure about the relationship between the three of them you would fill in something like: In einem Laufwettbewerb beendete Gabi das Rennen in 1 Stunde. Fabian kam in 13 Minuten mehr als sie, Gregor in 8 Minuten weniger als sie an or In einem Laufwettbewerb beendete Gabi das Rennen in 1 Stunde. Fabian kam in 13 Minuten mehr als sie, Gregor in 8 Minuten weniger als er an.
12,147,273
I have a Market stored in a user session in Rails, set via `session[:current_market]` in my `application_controller.rb`. I have my front-end interface served with Backbone.js, and I have a little market selector widget that calls ``` BackboneApp.data.currentMarket = market.toJSON() Backbone.history.navigate market.homeUrl(), trigger: true ``` ... when a user selects a market. This works except that if a user hard-navigates to another page, the market reverts to whatever it was set on the initial page load (whatever was originally loaded in `session[:current_market]` in Rails. How can I update the user's market in session when a Backbone.js navigation event occurs? I tried manually doing this by triggering a silent GET: ``` $.get '/api/v1/reset_current_market', { market_id: market.toJSON().id } ``` ... but that doesn't seem to work.
2012/08/27
[ "https://Stackoverflow.com/questions/12147273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
I assume that when the user switches market then some ajax request will be fired to hit your rails api and fetch the data for that market. What you could do is make the controller action for that route update the current users session to whatever market got requested.
how about wrap this market info to new Model and handling change with that? This is just a pseudo code examlpe. ``` var marketModel = Backbone.Model.extend({ urlRoot:"/you/url/market", defaults:{ marker: "" }, initialize:function () { } }); BackboneApp.data.currentMarket = new marketModel(market.toJSON()) ``` Set selected market to this new model, and call save(). At rails change session info at your /your/url/marget POST method. If this object have id property then impelent also PUT method.
568,454
I know this is kind of a philosophical question in the risk to be opinion-based, but I would like to know what the people that know a lot more than me, think about this. I'm asking myself about this since a lot of time now. I think everything started noticing that the maximum velocity for the propagation of an "information" is the speed of light and astonished me the fact that a gravitational wave moves at $c$. In fact eletromagnetic field is usually considered "inside" the spacetime, not part of it and it's simple to imagine a Universe with just gravity and mass; in this sense "spacetime comes first" and $c$ should be called the "gravitation velocity" or something like this. Electromagnetic field has different properties anyway, first of all the fact that its "quantum" has no mass and no *charge*, while the "graviton" has mass and interacts with other gravitons. At the same time it's strange that cannot exists an electric charge without mass, while the opposite is perfectly possible (relating to the previous "spacetime comes first"), so that, in a way, electric charge is constrained to follow the movement of the mass to which is associated and cannot detach from it. But trying to imagine it, it's very hard, it's like several dimensions are interacting one with the other, such as a zip unifies the two sides of a (multidimensional) jumper. So I'm asking myself, is it possible that originally spacetime has something like $8$ or more dimensions, but "doesn't know where to put all of them" and for some unknown reasons, make some of them "collapsing" immersed into others; and in this case, why spacetime seems to be the master space, above the others? Sorry if I was so qualitative, I don't really know how to express myself better. Anyway I don't want it to be only a philosophical question, but also a physical one, with a formalism I didn't put (because of my limits), but that is more than well accepted. Thanks, Rob.
2020/07/27
[ "https://physics.stackexchange.com/questions/568454", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/267112/" ]
Think about what the electric potential at a point means. It is the amount of work done in bringing a unit positive charge from infinity to that point without acceleration. A potential of $0$ means that you do *net zero work* in doing so. This emphatically *does not* mean that the force at that point is zero, or that it was zero everywhere along the path, or even that the work done was zero *everywhere.* To get an intuitive idea of how the net work can be zero, think of how the potential affects work. Broadly speaking, if the potential is negative at a point, the force is *attractive* at that point; if it is positive, the force is *repulsive.* You do positive work against a repulsive force and negative work against an attractive one. In the case of a dipole, there will be points where you do *some* positive work while transporting a positive charge part of the way, and negative work the rest of the way, such that they cancel each other out perfectly. Those points correspond to zero potential. To answer your last point, if you leave a charge at a point with $V = 0$, it will move to a point with a lower potential, $V<0$.
The potential being zero at a point is irrelevant. What really matters is the potential difference between two points, that is, suppose you have two points A and B separated by a distance of $\Delta r$, and the potential of B is greater than A by $ \Delta V$ volts ( say), and both are separated by a distance of $\Delta r$. Then, $$ \vec{E} \approx - \frac{ \Delta V}{\Delta r} \vec{r}$$ where $r$ is the unit vector pointing from A to B, now observe that the rise over run slope of the voltage difference is what causes the electric field. To illustrate this idea further, suppose whole space had a voltage of a $10000000V$, then there still would be no electric field in this space because we need a 'potential' difference for electric field. Now, suppose you have a space where this is a very large potential and a small region of space with low potential, if you have a 'positive charge' then this charge would be sucked into the region of low potential, while the electrons would be pushed away into infinity. Now, for equilibrium condition (for + charge), we just need to find the point where the 'rise over run slope' or in a calculus way, where the derivative is zero. I.e $$ 0 = \nabla U(x,y,z)$$ Or, in a single variable case, $$ 0 = \frac{dU(x)}{dx}$$ This derivative would be a function of 'x', finding the value of 'x' for where the function is zero, we get the equilibrium point. For example, $$ U(x) = 3x^2 -x +C$$ $$ \frac{dU}{dx} = 6x - 1$$ (notice here that derivative was independent of C, the constant, another way to say it only depends on potential difference) Now, institute the condition that derivative must be zero $$ 0 = 6x -1$$ $$ x= \frac16$$ So, for a positive charge, $ x =\frac{1}{6}$$ is where it would be pushed towards for the system to acquire least energy state. However a negative charge particle, the story is opposite, it would be pushed away from this point because the force on a negative particle is opposite to that of positive one.
61,085,885
The Message component contains an anchor element and a paragraph below the anchor. Rendering of the paragraph should be toggled by clicking on the anchor element using the following logic: At the start, the paragraph should not be rendered. After a click, the paragraph should be rendered. After another click, the paragraph should not be rendered.
2020/04/07
[ "https://Stackoverflow.com/questions/61085885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7404858/" ]
Your solution could be simplified a bit by only hiding the paragraph when the state is false and not changing the entire return value. ``` class Message extends React.Component { constructor(props) { super(props); this.state = { visible: 0 }; } clickHandler = e => { e.preventDefault(); this.setState({ visible: !this.state.visible }); }; render() { return ( <React.Fragment> <a href="#" onClick={this.clickHandler}> Want to buy a new car? </a> {this.state.visible && <p>Call +11 22 33 44 now!</p>} </React.Fragment> ); } } document.body.innerHTML = "<div id='root'> </div>"; const rootElement = document.getElementById("root"); ReactDOM.render(<Message />, rootElement); ```
The solution that I used to pass the test cases ``` class Message extends React.Component { constructor(props) { super(props); this.state = { visible: 1 }; } clickHandler = e => { e.preventDefault(); this.setState({ visible: !this.state.visible }); }; render() { return this.state.visible ? ( <React.Fragment> <a href="#" onClick={this.clickHandler}> Want to buy a new car? </a> </React.Fragment> ) : ( <React.Fragment> <a href="#" onClick={this.clickHandler}> Want to buy a new car? </a> <p>Call +11 22 33 44 now!</p> </React.Fragment> ); } } document.body.innerHTML = "<div id='root'> </div>"; const rootElement = document.getElementById("root"); ReactDOM.render(<Message />, rootElement); ```
55,633,457
I have two different dataset which has a common value placed in two different Tablix in Report Builder tool. I want to achieve a SUM of `ELEC_DATA` in the second Tablix. I have already tried using this expression. ``` =LOOKUP(Field!COMP_ID.value,Field!COMP_ID.value,Field!ELEC_DATA.value,"DATASET2") ``` The result shows nothing at all -- no errors as well. Then I tried with custom code. ``` =code.sumlookup(LOOKUPSET(Field!COMP_ID.value,Field!COMP_ID.value,Field!ELEC_DATA.value,"DATASET2")) ``` The Result I am getting is "0". The expected result would be the addition of `ELEC_DATA` like shown in the pic attached [![enter image description here](https://i.stack.imgur.com/m3sx2.png)](https://i.stack.imgur.com/m3sx2.png)
2019/04/11
[ "https://Stackoverflow.com/questions/55633457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10657824/" ]
As [the Icons in Labels documentation says](https://code.visualstudio.com/api/references/icons-in-labels), you can apply a spinning animation to any icon by appending `~spin` to the icon name: `$(globe~spin)`
[Documentation](https://code.visualstudio.com/api/references/icons-in-labels#animation) says you can set spinning animation only to * sync * loading * gear icons.
12,850,689
i've a table like: ``` | ID | value | | 0 | 5 | | 1 | 2 | | 0 | 1 | | 1 | 6 | | 2 | 3 | | 2 | 8 | | 1 | 2 | | 0 | 1 | | 2 | 4 | ``` I'm trying to take in my result only one row for id where value is the min of all the column, something like: ``` SELECT DISTINCT * FROM table WHERE MIN(table.value) = table.value ``` how can i solve? thanks! EDIT: My desired output is: ``` | ID | value | | 0 | 1 | -> is the min of all the rows with id = 0 | 1 | 2 | | 2 | 3 | ``` EDIT 2: Something like: ``` SELECT DISTINCT * FROM tableName AS A WHERE value = (SELECT MIN(value) From tableName AS B WHERE A.ID=B.ID) ``` But tableName is `(SELECT * FROM ...........)`.. how can i perform?
2012/10/12
[ "https://Stackoverflow.com/questions/12850689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938350/" ]
``` SELECT DISTINCT ID, Value FROM tableName WHERE value = (SELECT MIN(value) From tableName) ``` [SQLFiddle Demo](http://sqlfiddle.com/#!2/f174e3/1) =================================================== follow-up question, what happens if there are same lowest `value` with different `ID`, what record will be shown?
This is what you want ``` select id,min(value) from tableName group by id ```
12,850,689
i've a table like: ``` | ID | value | | 0 | 5 | | 1 | 2 | | 0 | 1 | | 1 | 6 | | 2 | 3 | | 2 | 8 | | 1 | 2 | | 0 | 1 | | 2 | 4 | ``` I'm trying to take in my result only one row for id where value is the min of all the column, something like: ``` SELECT DISTINCT * FROM table WHERE MIN(table.value) = table.value ``` how can i solve? thanks! EDIT: My desired output is: ``` | ID | value | | 0 | 1 | -> is the min of all the rows with id = 0 | 1 | 2 | | 2 | 3 | ``` EDIT 2: Something like: ``` SELECT DISTINCT * FROM tableName AS A WHERE value = (SELECT MIN(value) From tableName AS B WHERE A.ID=B.ID) ``` But tableName is `(SELECT * FROM ...........)`.. how can i perform?
2012/10/12
[ "https://Stackoverflow.com/questions/12850689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938350/" ]
How about this: ``` SELECT DISTINCT a.ID, a.value FROM tableName AS a WHERE a.value = (SELECT MIN(b.value) FROM tableName AS b WHERE a.id = b.id) ```
This is what you want ``` select id,min(value) from tableName group by id ```
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
ASPX ``` <asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="fileUpload" ClientValidationFunction="setUploadButtonState();" /> <asp:Button ID="button_fileUpload" runat="server" Text="Upload File" OnClick="button_fileUpload_Click" Enabled="false" /> <asp:Label ID="lbl_uploadMessage" runat="server" Text="" /> ``` jQuery ``` function setUploadButtonState() { var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024 var fileUpload = $('#fileUpload'); if (fileUpload.val() == '') { return false; } else { if (fileUpload[0].files[0].size < maxFileSize) { $('#button_fileUpload').prop('disabled', false); return true; }else{ $('#lbl_uploadMessage').text('File too big !') return false; } } } ```
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: <http://blueimp.github.io/jQuery-File-Upload/> It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: <http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx>
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
To validate **multiple** files with jQuery + `asp:CustomValidator` a size up to 10MB **jQuery:** ``` function upload(sender, args) { args.IsValid = true; var maxFileSize = 10 * 1024 * 1024; // 10MB var CurrentSize = 0; var fileUpload = $("[id$='fuUpload']"); for (var i = 0; i < fileUpload[0].files.length; i++) { CurrentSize = CurrentSize + fileUpload[0].files[i].size; } args.IsValid = CurrentSize < maxFileSize; } ``` **ASP:** ``` <asp:FileUpload runat="server" AllowMultiple="true" ID="fuUpload" /> <asp:LinkButton runat="server" Text="Upload" OnClick="btnUpload_Click" CausesValidation="true" ValidationGroup="vgFileUpload"></asp:LinkButton> <asp:CustomValidator ControlToValidate="fuUpload" ClientValidationFunction="upload" runat="server" ErrorMessage="Error!" ValidationGroup="vgFileUpload"/> ```
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: <http://blueimp.github.io/jQuery-File-Upload/> It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: <http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx>
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
ASPX ``` <asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="fileUpload" ClientValidationFunction="setUploadButtonState();" /> <asp:Button ID="button_fileUpload" runat="server" Text="Upload File" OnClick="button_fileUpload_Click" Enabled="false" /> <asp:Label ID="lbl_uploadMessage" runat="server" Text="" /> ``` jQuery ``` function setUploadButtonState() { var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024 var fileUpload = $('#fileUpload'); if (fileUpload.val() == '') { return false; } else { if (fileUpload[0].files[0].size < maxFileSize) { $('#button_fileUpload').prop('disabled', false); return true; }else{ $('#lbl_uploadMessage').text('File too big !') return false; } } } ```
``` $(document).ready(function () { "use strict"; //This is the CssClass of the FileUpload control var fileUploadClass = ".attachmentFileUploader", //this is the CssClass of my save button saveButtonClass = ".saveButton", //this is the CssClass of the label which displays a error if any isTheFileSizeTooBigClass = ".isTheFileSizeTooBig"; /** * @desc This function checks to see what size of file the user is attempting to upload. * It will also display a error and disable/enable the "submit/save" button. */ function checkFileSizeBeforeServerAttemptToUpload() { //my max file size, more exact than 10240000 var maxFileSize = 10485760 // 10MB -> 10000 * 1024 //If the file upload does not exist, lets get outta this function if ($(fileUploadClass).val() === "") { //break out of this function because no FileUpload control was found return false; } else { if ($(fileUploadClass)[0].files[0].size <= maxFileSize) { //no errors, hide the label that holds the error $(isTheFileSizeTooBigClass).hide(); //remove the disabled attribute and show the save button $(saveButtonClass).removeAttr("disabled"); $(saveButtonClass).attr("enabled", "enabled"); } else { //this sets the error message to a label on the page $(isTheFileSizeTooBigClass).text("Please upload a file less than 10MB."); //file size error, show the label that holds the error $(isTheFileSizeTooBigClass).show(); //remove the enabled attribute and disable the save button $(saveButtonClass).removeAttr("enabled"); $(saveButtonClass).attr("disabled", "disabled"); } } } //When the file upload control changes, lets execute the function that checks the file size. $(fileUploadClass).change(function () { //call our function checkFileSizeBeforeServerAttemptToUpload(); }); }); ``` dont forget you probably need to change the web.config to limit uploads of certain sizes as well since the default is 4MB <https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.85%29.aspx> ``` <httpRuntime targetFramework="4.5" maxRequestLength="11264" /> ```
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
I am in the same boat and found a working solution IF your expected upload file is an image. In short I updated the ASP.NET FileUpload control to call a javascript function to display a thumbnail of the selected file, and then before calling the form submit then checking the image to check the file size. Enough talk, let's get to the code. **Javascript, include in page header** ``` function ShowThumbnail() { var aspFileUpload = document.getElementById("FileUpload1"); var errorLabel = document.getElementById("ErrorLabel"); var img = document.getElementById("imgUploadThumbnail"); var fileName = aspFileUpload.value; var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase(); if (ext == "jpeg" || ext == "jpg" || ext == "png") { img.src = fileName; } else { img.src = "../Images/blank.gif"; errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file."; } img.focus(); } function CheckImageSize() { var aspFileUpload = document.getElementById("FileUpload1"); var errorLabel = document.getElementById("ErrorLabel"); var img = document.getElementById("imgUploadThumbnail"); var fileName = aspFileUpload.value; var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase(); if (!(ext == "jpeg" || ext == "jpg" || ext == "png")) { errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file."; return false; } if (img.fileSize == -1) { errorLabel.innerHTML = "Couldn't load image file size. Please try to save again."; return false; } else if (img.fileSize <= 3145728) { errorLabel.innerHTML = ""; return true; } else { var fileSize = (img.fileSize / 1048576); errorLabel.innerHTML = "File is too large, must select file under 3 Mb. File Size: " + fileSize.toFixed(1) + " Mb"; return false; } } ``` The CheckImageSize is looking for a file less than 3 Mb (3145728), update this to whatever value you need. **ASP HTML Code** ``` <!-- Insert into existing ASP page --> <div style="float: right; width: 100px; height: 100px;"><img id="imgUploadThumbnail" alt="Uploaded Thumbnail" src="../Images/blank.gif" style="width: 100px; height: 100px" /></div> <asp:FileUpload ID="FileUpload1" runat="server" onchange="Javascript: ShowThumbnail();"/> <br /> <asp:Label ID="ErrorLabel" runat="server" Text=""></asp:Label> <br /> <asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click" Width="70px" OnClientClick="Javascript: return CheckImageSize()" /> ``` Note the browser does take a second to update the page with the thumbnail and if the user is able to click the Save before the image gets loaded it will get a -1 for the file size and display the error to click save again. If you don't want to display the image you can make the image control invisible and this should work. You will also need to get a copy of blank.gif so the page doesn't load with a broken image link. Hope you find this quick and easy to drop in and helpful. I'm not sure if there is a similar HTML control that could be used for just general files.
I think you cannot do that. Your question is similar to this one : [Obtain filesize without using FileSystemObject in JavaScript](https://stackoverflow.com/questions/2014250/obtain-filesize-without-using-filesystemobject-in-javascript) The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server. So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
To validate **multiple** files with jQuery + `asp:CustomValidator` a size up to 10MB **jQuery:** ``` function upload(sender, args) { args.IsValid = true; var maxFileSize = 10 * 1024 * 1024; // 10MB var CurrentSize = 0; var fileUpload = $("[id$='fuUpload']"); for (var i = 0; i < fileUpload[0].files.length; i++) { CurrentSize = CurrentSize + fileUpload[0].files[i].size; } args.IsValid = CurrentSize < maxFileSize; } ``` **ASP:** ``` <asp:FileUpload runat="server" AllowMultiple="true" ID="fuUpload" /> <asp:LinkButton runat="server" Text="Upload" OnClick="btnUpload_Click" CausesValidation="true" ValidationGroup="vgFileUpload"></asp:LinkButton> <asp:CustomValidator ControlToValidate="fuUpload" ClientValidationFunction="upload" runat="server" ErrorMessage="Error!" ValidationGroup="vgFileUpload"/> ```
Why not to use RegularExpressionValidator for file type validation. Regular expression for File type validation is: ``` ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$" ```
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
I am in the same boat and found a working solution IF your expected upload file is an image. In short I updated the ASP.NET FileUpload control to call a javascript function to display a thumbnail of the selected file, and then before calling the form submit then checking the image to check the file size. Enough talk, let's get to the code. **Javascript, include in page header** ``` function ShowThumbnail() { var aspFileUpload = document.getElementById("FileUpload1"); var errorLabel = document.getElementById("ErrorLabel"); var img = document.getElementById("imgUploadThumbnail"); var fileName = aspFileUpload.value; var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase(); if (ext == "jpeg" || ext == "jpg" || ext == "png") { img.src = fileName; } else { img.src = "../Images/blank.gif"; errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file."; } img.focus(); } function CheckImageSize() { var aspFileUpload = document.getElementById("FileUpload1"); var errorLabel = document.getElementById("ErrorLabel"); var img = document.getElementById("imgUploadThumbnail"); var fileName = aspFileUpload.value; var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase(); if (!(ext == "jpeg" || ext == "jpg" || ext == "png")) { errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file."; return false; } if (img.fileSize == -1) { errorLabel.innerHTML = "Couldn't load image file size. Please try to save again."; return false; } else if (img.fileSize <= 3145728) { errorLabel.innerHTML = ""; return true; } else { var fileSize = (img.fileSize / 1048576); errorLabel.innerHTML = "File is too large, must select file under 3 Mb. File Size: " + fileSize.toFixed(1) + " Mb"; return false; } } ``` The CheckImageSize is looking for a file less than 3 Mb (3145728), update this to whatever value you need. **ASP HTML Code** ``` <!-- Insert into existing ASP page --> <div style="float: right; width: 100px; height: 100px;"><img id="imgUploadThumbnail" alt="Uploaded Thumbnail" src="../Images/blank.gif" style="width: 100px; height: 100px" /></div> <asp:FileUpload ID="FileUpload1" runat="server" onchange="Javascript: ShowThumbnail();"/> <br /> <asp:Label ID="ErrorLabel" runat="server" Text=""></asp:Label> <br /> <asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click" Width="70px" OnClientClick="Javascript: return CheckImageSize()" /> ``` Note the browser does take a second to update the page with the thumbnail and if the user is able to click the Save before the image gets loaded it will get a -1 for the file size and display the error to click save again. If you don't want to display the image you can make the image control invisible and this should work. You will also need to get a copy of blank.gif so the page doesn't load with a broken image link. Hope you find this quick and easy to drop in and helpful. I'm not sure if there is a similar HTML control that could be used for just general files.
Why not to use RegularExpressionValidator for file type validation. Regular expression for File type validation is: ``` ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$" ```
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
You can do that by using javascript. Example: ``` <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <title>Show File Data</title> <style type='text/css'> body { font-family: sans-serif; } </style> <script type='text/javascript'> function showFileSize() { var input, file; if (typeof window.FileReader !== 'function') { bodyAppend("p", "The file API isn't supported on this browser yet."); return; } input = document.getElementById('fileinput'); if (!input) { bodyAppend("p", "Um, couldn't find the fileinput element."); } else if (!input.files) { bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs."); } else if (!input.files[0]) { bodyAppend("p", "Please select a file before clicking 'Load'"); } else { file = input.files[0]; bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size"); } } function bodyAppend(tagName, innerHTML) { var elm; elm = document.createElement(tagName); elm.innerHTML = innerHTML; document.body.appendChild(elm); } </script> </head> <body> <form action='#' onsubmit="return false;"> <input type='file' id='fileinput'> <input type='button' id='btnLoad' value='Load' onclick='showFileSize();'> </form> </body> </html> ```
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: <http://blueimp.github.io/jQuery-File-Upload/> It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: <http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx>
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
I think you cannot do that. Your question is similar to this one : [Obtain filesize without using FileSystemObject in JavaScript](https://stackoverflow.com/questions/2014250/obtain-filesize-without-using-filesystemobject-in-javascript) The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server. So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: <http://blueimp.github.io/jQuery-File-Upload/> It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: <http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx>
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
I think you cannot do that. Your question is similar to this one : [Obtain filesize without using FileSystemObject in JavaScript](https://stackoverflow.com/questions/2014250/obtain-filesize-without-using-filesystemobject-in-javascript) The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server. So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
Why not to use RegularExpressionValidator for file type validation. Regular expression for File type validation is: ``` ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$" ```
3,094,748
I want to check the selected file size **BEFORE** uploading a file with the asp fileupload component. I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..) How can I do that ? Thanks for your answers..
2010/06/22
[ "https://Stackoverflow.com/questions/3094748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155622/" ]
I think you cannot do that. Your question is similar to this one : [Obtain filesize without using FileSystemObject in JavaScript](https://stackoverflow.com/questions/2014250/obtain-filesize-without-using-filesystemobject-in-javascript) The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server. So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
``` $(document).ready(function () { "use strict"; //This is the CssClass of the FileUpload control var fileUploadClass = ".attachmentFileUploader", //this is the CssClass of my save button saveButtonClass = ".saveButton", //this is the CssClass of the label which displays a error if any isTheFileSizeTooBigClass = ".isTheFileSizeTooBig"; /** * @desc This function checks to see what size of file the user is attempting to upload. * It will also display a error and disable/enable the "submit/save" button. */ function checkFileSizeBeforeServerAttemptToUpload() { //my max file size, more exact than 10240000 var maxFileSize = 10485760 // 10MB -> 10000 * 1024 //If the file upload does not exist, lets get outta this function if ($(fileUploadClass).val() === "") { //break out of this function because no FileUpload control was found return false; } else { if ($(fileUploadClass)[0].files[0].size <= maxFileSize) { //no errors, hide the label that holds the error $(isTheFileSizeTooBigClass).hide(); //remove the disabled attribute and show the save button $(saveButtonClass).removeAttr("disabled"); $(saveButtonClass).attr("enabled", "enabled"); } else { //this sets the error message to a label on the page $(isTheFileSizeTooBigClass).text("Please upload a file less than 10MB."); //file size error, show the label that holds the error $(isTheFileSizeTooBigClass).show(); //remove the enabled attribute and disable the save button $(saveButtonClass).removeAttr("enabled"); $(saveButtonClass).attr("disabled", "disabled"); } } } //When the file upload control changes, lets execute the function that checks the file size. $(fileUploadClass).change(function () { //call our function checkFileSizeBeforeServerAttemptToUpload(); }); }); ``` dont forget you probably need to change the web.config to limit uploads of certain sizes as well since the default is 4MB <https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.85%29.aspx> ``` <httpRuntime targetFramework="4.5" maxRequestLength="11264" /> ```
15,997,379
Can I achieve my Desired Output(given below) or something similar with the following Datasets using pivot\_table in pandas. I am trying to do something like: ``` pivot_table(df, rows=['region'], cols=['area','distributor','salesrep'], aggfunc=np.sum, margins=True).stack(['area','distributor','salesrep']) ``` but I am only getting subtotals per region, if I move area from cols to rows then I will only get subtotals per area. Datasets: ``` region area distributor salesrep sales invoice_count Central Butterworth HIN MARKETING TLS 500 25 Central Butterworth HIN MARKETING TLS 500 25 Central Butterworth HIN MARKETING OSE 500 25 Central Butterworth HIN MARKETING OSE 500 25 Central Butterworth KWANG HENGG TCS 500 25 Central Butterworth KWANG HENGG TCS 500 25 Central Butterworth KWANG HENG LBH 500 25 Central Butterworth KWANG HENG LBH 500 25 Central Ipoh SGH EDERAN CHAN 500 25 Central Ipoh SGH EDERAN CHAN 500 25 Central Ipoh SGH EDERAN KAMACHI 500 25 Central Ipoh SGH EDERAN KAMACHI 500 25 Central Ipoh CORE SYN LILIAN 500 25 Central Ipoh CORE SYN LILIAN 500 25 Central Ipoh CORE SYN TEOH 500 25 Central Ipoh CORE SYN TEOH 500 25 East JB LEI WAH NF05 500 25 East JB LEI WAH NF05 500 25 East JB LEI WAH NF06 500 25 East JB LEI WAH NF06 500 25 East JB WONDER F&B SEREN 500 25 East JB WONDER F&B SEREN 500 25 East JB WONDER F&B MONC 500 25 East JB WONDER F&B MONC 500 25 East PJ PENGEDAR NORM 500 25 East PJ PENGEDAR NORM 500 25 East PJ PENGEDAR SIMON 500 25 East PJ PENGEDAR SIMON 500 25 East PJ HEBAT OGI 500 25 East PJ HEBAT OGI 500 25 East PJ HEBAT MIGI 500 25 East PJ HEBAT MIGI 500 25 ``` Desired Output: ``` region area distributor salesrep invoice_count sales Grand Total 800 16000 Central Central Total 400 8000 Central Butterworth Butterworth Total 200 4000 Central Butterworth HIN MARKETING HIN MARKETING Total 100 2000 Central Butterworth HIN MARKETING OSE 50 1000 Central Butterworth HIN MARKETING TLS 50 1000 Central Butterworth KWANG HENG KWANG HENG Total 100 2000 Central Butterworth KWANG HENG LBH 50 1000 Central Butterworth KWANG HENG TCS 50 1000 Central Ipoh Ipoh Total 200 4000 Central Ipoh CORE SYN CORE SYN Total 100 2000 Central Ipoh CORE SYN LILIAN 50 1000 Central Ipoh CORE SYN TEOH 50 1000 Central Ipoh SGH EDERAN SGH EDERAN Total 100 2000 Central Ipoh SGH EDERAN CHAN 50 1000 Central Ipoh SGH EDERAN KAMACHI 50 1000 East East Total 400 8000 East JB JB Total 200 4000 East JB LEI WAH LEI WAH Total 100 2000 East JB LEI WAH NF05 50 1000 East JB LEI WAH NF06 50 1000 East JB WONDER F&B WONDER F&B Total 100 2000 East JB WONDER F&B MONC 50 1000 East JB WONDER F&B SEREN 50 1000 East PJ PJ Total 200 4000 East PJ HEBAT HEBAT Total 100 2000 East PJ HEBAT MIGI 50 1000 East PJ HEBAT OGI 50 1000 East PJ PENGEDAR PENDEGAR Total 100 2000 East PJ PENGEDAR NORM 50 1000 East PJ PENGEDAR SIMON 50 1000 ```
2013/04/14
[ "https://Stackoverflow.com/questions/15997379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2101790/" ]
We could use `groupby` instead of `pivot_table`: ``` import numpy as np import pandas as pd def label(ser): return '{s} Total'.format(s=ser) filename = 'data.txt' df = pd.read_table(filename, delimiter='\t') total = pd.DataFrame({'region': ['Grand Total'], 'invoice_count': df['invoice_count'].sum(), 'sales': df['sales'].sum()}) total['total_rank'] = 1 region_total = df.groupby(['region'], as_index=False).sum() region_total['area'] = region_total['region'].apply(label) region_total['region_rank'] = 1 area_total = df.groupby(['region', 'area'], as_index=False).sum() area_total['distributor'] = area_total['area'].apply(label) area_total['area_rank'] = 1 dist_total = df.groupby( ['region', 'area', 'distributor'], as_index=False).sum() dist_total['salesrep'] = dist_total['distributor'].apply(label) rep_total = df.groupby( ['region', 'area', 'distributor', 'salesrep'], as_index=False).sum() # UNION the DataFrames into one DataFrame result = pd.concat([total, region_total, area_total, dist_total, rep_total]) # Replace NaNs with empty strings result.fillna({'region': '', 'area': '', 'distributor': '', 'salesrep': ''}, inplace=True) # Reorder the rows sorter = np.lexsort(( result['distributor'].rank(), result['area_rank'].rank(), result['area'].rank(), result['region_rank'].rank(), result['region'].rank(), result['total_rank'].rank())) result = result.take(sorter) result = result.reindex( columns=['region', 'area', 'distributor', 'salesrep', 'invoice_count', 'sales']) print(result.to_string(index=False)) ``` yields ``` region area distributor salesrep invoice_count sales Grand Total 800 16000 Central Central Total 400 8000 Central Butterworth Butterworth Total 200 4000 Central Butterworth HIN MARKETING HIN MARKETING Total 100 2000 Central Butterworth HIN MARKETING OSE 50 1000 Central Butterworth HIN MARKETING TLS 50 1000 Central Butterworth KWANG HENG KWANG HENG Total 100 2000 Central Butterworth KWANG HENG LBH 50 1000 Central Butterworth KWANG HENG TCS 50 1000 Central Ipoh Ipoh Total 200 4000 Central Ipoh CORE SYN CORE SYN Total 100 2000 Central Ipoh CORE SYN LILIAN 50 1000 Central Ipoh CORE SYN TEOH 50 1000 Central Ipoh SGH EDERAN SGH EDERAN Total 100 2000 Central Ipoh SGH EDERAN CHAN 50 1000 Central Ipoh SGH EDERAN KAMACHI 50 1000 East East Total 400 8000 East JB JB Total 200 4000 East JB LEI WAH LEI WAH Total 100 2000 East JB LEI WAH NF05 50 1000 East JB LEI WAH NF06 50 1000 East JB WONDER F&B WONDER F&B Total 100 2000 East JB WONDER F&B MONC 50 1000 East JB WONDER F&B SEREN 50 1000 East PJ PJ Total 200 4000 East PJ HEBAT HEBAT Total 100 2000 East PJ HEBAT MIGI 50 1000 East PJ HEBAT OGI 50 1000 East PJ PENGEDAR PENGEDAR Total 100 2000 East PJ PENGEDAR NORM 50 1000 East PJ PENGEDAR SIMON 50 1000 ```
I do not know how to get subtotals inside the table, but if you run ``` df.pivot_table(rows=['region','area','distributor','salesrep'], aggfunc=np.sum, margins=True) ``` you will get ``` invoice_count sales region area distributor salesrep Central Butterworth HIN MARKETING OSE 50 1000 TLS 50 1000 KWANG HENG LBH 50 1000 KWANG HENGG TCS 50 1000 Ipoh CORE SYN LILIAN 50 1000 TEOH 50 1000 SGH EDERAN CHAN 50 1000 KAMACHI 50 1000 East JB LEI WAH NF05 50 1000 NF06 50 1000 WONDER F&B MONC 50 1000 SEREN 50 1000 PJ HEBAT MIGI 50 1000 OGI 50 1000 PENGEDAR NORM 50 1000 SIMON 50 1000 All 800 16000 ``` If you want totals based on say `region` and `area`, you may run ``` df.pivot_table(rows=['region', 'area'], aggfunc=np.sum, margins=True) ``` which results in ``` invoice_count sales region area Central Butterworth 200 4000 Ipoh 200 4000 East JB 200 4000 PJ 200 4000 All 800 16000 ```
70,510,928
I working with Keras and TensorFlow in R. For normalizing data I wrote this function ``` df=data.frame( Column_1=seq(1,10), Column_2=seq(11,20)) normalization_data <- function(df){ data=(df$Column_1-mean(df$Column_1))/sd(df$Column_1) return(data) } ``` This function work well and give me good result but only for one column. You can see result below ``` normalized_data<- normalization_data(df) normalized_data [1] -1.4863011 -1.1560120 -0.8257228 -0.4954337 -0.1651446 0.1651446 0.4954337 0.8257228 1.1560120 [10] 1.4863011 ``` So can anybody help how to change this function in order to work with all other columns in data frame ?
2021/12/28
[ "https://Stackoverflow.com/questions/70510928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10924836/" ]
Since counts of your two-join query reflects multiples of the one-join query, you are double counting the previously distinct pairings with new join. Specifically, in first query `COMPANY` and `SENIOR_MANAGER` tables can have a one-to-many relationship where a distinct company can have multiple senior managers. However, in second query when including `LEAD_MANAGER` table which would have even more distinct pairings to `COMPANY`, you repeat `SENIOR_MANAGER` multiple times for every corresponding pairing of `COMPANY` and `LEAD_MANAGER`. --- As a solution to the double counting, consider joining aggregate subqueries (or [CTEs](https://dev.mysql.com/doc/refman/8.0/en/with.html)): ```sql SELECT agg_s.COMPANY_CODE, agg_s.FOUNDER, agg_s.SENIOR_MANAGER_COUNT. agg_l.LEAD_MANAGER_COUNT FROM (SELECT c.COMPANY_CODE, c.FOUNDER, COUNT(s.SENIOR_MANAGER_CODE) AS SENIOR_MANAGER_COUNT FROM COMPANY c INNER JOIN SENIOR_MANAGER s ON s.COMPANY_CODE = c.COMPANY_CODE GROUP BY c.COMPANY_CODE, c.FOUNDER ) AS agg_s INNER JOIN (SELECT c.COMPANY_CODE, c.FOUNDER, COUNT(l.LEAD_MANAGER_CODE) AS LEAD_MANAGER_COUNT FROM COMPANY c INNER JOIN LEAD_MANAGER l ON c.COMPANY_CODE = l.COMPANY_CODE GROUP BY c.COMPANY_CODE, c.FOUNDER ) AS agg_l ON agg_s.COMPANY_CODE = agg_l.COMPANY_CODE AND agg_s.FOUNDER = agg_l.FOUNDER ``` Even better, consider a table design change for proper normalization where you maintain a *single* `MANAGER` table with `TYPE` indicator column for `SENIOR` or `LEAD`. Then run a *single* query with conditional aggregation: ```sql SELECT c.COMPANY_CODE, c.FOUNDER, COUNT(CASE WHEN m.TYPE = 'SENIOR' THEN 1 ELSE NULL END) AS SENIOR_MANAGER_COUNT, COUNT(CASE WHEN m.TYPE = 'LEAD' THEN 1 ELSE NULL END) AS LEAD_MANAGER_COUNT FROM COMPANY c INNER JOIN MANAGER m ON c.COMPANY_CODE = m.COMPANY_CODE GROUP BY c.COMPANY_CODE, c.FOUNDER; ```
Each time you join a new table, each row in the result set is multiplied by the number of times the join condition is matched in the new table for that row. So your results show that each of C1, C100 and C12 has two LEAD\_MANAGERs.
49,325,019
I am using `AWSSDK.S3` version `3.3.17.2` and `AWSSDK.Core` version `3.3.21.16` to upload a file and then download the same file. The code below not able to download the file **if the file name has spaces ( or `#`)** ``` public class AmazonS3 { public async Task<string> UploadFileAsync(string sourceFile, string s3BucketUrl) { AmazonS3Uri s3Uri = new AmazonS3Uri(s3BucketUrl); using (var s3 = new AmazonS3Client(s3Uri.Region)) { using (TransferUtility utility = new TransferUtility(s3)) { TransferUtilityUploadRequest request = new TransferUtilityUploadRequest { BucketName = s3Uri.Bucket, ContentType = "application/pdf", FilePath = sourceFile, Key = s3Uri.Key + Path.GetFileName(sourceFile), }; await utility.UploadAsync(request).ConfigureAwait(false); } } return Path.Combine(s3BucketUrl, Path.GetFileName(sourceFile)); } public async Task DownloadFileAsync(string destinationFilePath, string s3Url) { var s3Uri = new AmazonS3Uri(s3Url); var s3Client = new AmazonS3Client(s3Uri.Region); GetObjectRequest getObjectRequest = new GetObjectRequest { BucketName = s3Uri.Bucket, Key = s3Uri.Key }; // dispose the underline stream when writing to local file system is done using (var getObjectResponse = await s3Client.GetObjectAsync(getObjectRequest).ConfigureAwait(false)) { await getObjectResponse.WriteResponseStreamToFileAsync(destinationFilePath, false, default(System.Threading.CancellationToken)).ConfigureAwait(false); } } } ``` Then for testing purpose i am uploading the file and downloading the same file again ``` AmazonS3 s3 = new AmazonS3(); var uploadedFileS3Link = await s3.UploadFileAsync("C:\\temp\\my test file.pdf", @"https://mybucket.s3-us-west-2.amazonaws.com/development/test/"); // get exception at line below await s3.DownloadFileAsync("C:\\temp\\downloaded file.pdf",uploadedFileS3Link ); ``` I am getting exception > > **Amazon.S3.AmazonS3Exception: The specified key does not exist**. ---> > Amazon.Runtime.Internal.HttpErrorResponseException: The remote server > returned an error: **(404) Not Found**. ---> System.Net.WebException: The > remote server returned an error: (404) Not Found. at > System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) > > at > System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult > iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean > requiresSynchronization) --- End of stack trace from previous > location where exception was thrown --- at > System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task > task) at ...... > > > *removed remaining exception for brevity* The file does exist inside bucket. In-fact i can copy and paste the s3url (i.e. the value of `uploadedFileS3Link` variable) and download the file via browser. (Note that in reality i am trying to download 1000+ files that are already uploaded with spaces in their name. So removing the spaces while uploading is not an option) **Update 1** i noticed S3 browser Url Encode the file name [![enter image description here](https://i.stack.imgur.com/Fpvtx.png)](https://i.stack.imgur.com/Fpvtx.png) I tried downloading the file using the encoded file path `https://mybucket.s3-us-west-2.amazonaws.com/development/test/my%20test%20file.pdf` but it still did not work
2018/03/16
[ "https://Stackoverflow.com/questions/49325019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862378/" ]
so finally i found what was the issue. I am using [AmazonS3Uri](https://github.com/aws/aws-sdk-net/edit/master/sdk/src/Services/S3/Custom/Util/AmazonS3Uri.cs) class to parse the given S3 url and get the key, bucket and region. The `AmazonS3Uri` returns my key as `development/test/my%20test%20file.pdf` Because internally `AmazonS3Uri` is using `System.Uri` to build Uri and then returns `AbsolutePath` which returns Encoded path as Key (*Should it return Local Path as Key?*) I don't know why but `AmazonS3Client` does not like it, and it throws exception if you pass Encoded key. So to fix the issue i decode the key using `System.Net.WebUtility.UrlDecode(s3Uri.Key)`. So new download method looks like ``` public async Task DownloadFileAsync(string destinationFilePath, string s3Url) { var s3Uri = new S3UrlParser(s3Url); var s3Client = new AmazonS3Client(s3Uri.Region); GetObjectRequest getObjectRequest = new GetObjectRequest { BucketName = s3Uri.Bucket, Key = System.Net.WebUtility.UrlDecode(s3Uri.Key) }; // dispose the underline stream when writing to local file system is done using (var getObjectResponse = await s3Client.GetObjectAsync(getObjectRequest).ConfigureAwait(false)) { await getObjectResponse.WriteResponseStreamToFileAsync(destinationFilePath, false, default(System.Threading.CancellationToken)).ConfigureAwait(false); } } ```
I had this same issue parsing filename with space and forward slashes in the name. The problem with unescaped forward slashes is most tools treat each forward slash as a directory delimiter within S3. So a simple name like myfilename = "file/name.pdf" appended to a virtual path would turn into; "directory/subdirectory/myfile/name.pdf" (here it will now have a directory called myfile where it was not intended) It can be mitigated by escaping the filename "directory/subdirectory/myfile%2fname.pdf" at the point of upload and then decoding as suggested in the answer of this post. After a experiencing errors from erroneous slashes and blank folder names in AWS Explorer caused by extra double slashes e.g. "//" (described further here: <https://webapps.stackexchange.com/a/120135>) I've come to the conclusion it's better to completely strip forward slashes altogether from any filename proportion (not the virtual directory) rather than relying on escaping on upload and unescaping it on download. Treating the forward slash as a reserved character as others have similarly experienced: <https://stackoverflow.com/a/19515741/1165173> In the case of an escaped whitespace symbol "+" it is usually safe to unescape the character and it will work as intended. Filename proportion can be encoded using ``` System.Web.HttpUtility.Encode(input); ``` List of non-acceptable filename characters can be compared at the point of file creation using Path.GetInvalidPathChars() Documentation: <https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getinvalidfilenamechars>
6,400,047
My code: dll: ``` #include "stdafx.h" #include <iostream.h> extern "C" __declspec(dllexport) void F1() { cout << "It works\n"; } extern "C" __declspec(dllexport) int F2() { return 154827; } extern "C" __declspec(dllexport) void F3(int n) { cout << "It works: "<<n<<"\n"; } extern "C" __declspec(dllexport) int F4(int n) { return n+1; } ``` console application: ``` #include "stdafx.h" #include <windows.h> #include <iostream.h> #include <stdio.h> #include <conio.h> typedef void (WINAPI*f1)(); typedef int (WINAPI*f2)(); typedef void (WINAPI*f3)(int); typedef int (WINAPI*f4)(int); #define MAXMODULE 50 f1 F1; f2 F2; f3 F3; f4 F4; void main(int argc, char* argv[]) { HINSTANCE hLib=LoadLibrary("dllll.dll"); if(hLib==NULL) { cout << "Unable to load library!" << endl; getch(); return; } char mod[MAXMODULE]; GetModuleFileName((HMODULE)hLib, (LPTSTR)mod, MAXMODULE); cout << "Library loaded: " << endl; F1=(f1)GetProcAddress((HMODULE)hLib, "F1"); F2=(f2)GetProcAddress((HMODULE)hLib, "F2"); F3=(f3)GetProcAddress((HMODULE)hLib, "F3"); F4=(f4)GetProcAddress((HMODULE)hLib, "F4"); if((F1==NULL) || (F2==NULL) || (F3==NULL) || (F4==NULL)) { cout << "Unable to load function(s)." << endl; FreeLibrary((HMODULE)hLib); return; } F1(); cout<<F2()<<endl; F3(1515); cout << F4(12) << endl; //works now :) FreeLibrary((HMODULE)hLib); getch(); return; } ``` Output: ``` Library loaded: 154827 It works It works: 1515 ``` Questions: 1. Why is F1 displayed after F2? F1 is called before F2. 2. F3 Works properly but makes a window pop up twice. I click Ignore on it. [![](https://i.stack.imgur.com/KJ98g.jpg)](https://i.stack.imgur.com/KJ98g.jpg) (source: [ifotos.pl](http://s3.ifotos.pl/img/f3_hwpwapq.jpg)) 3. Why F4 doesn't work at all? It raises an exception. EDIT: Question 2 and 3 are solved now. For 1, output now is: ``` Library loaded: 154827 13 It works It works: 1515 ``` Which is in order: F2, F4, F1, F3. I call them: F1, F2, F3, F4. Why is it happening?
2011/06/19
[ "https://Stackoverflow.com/questions/6400047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453995/" ]
This is pretty fun task, so I've decided to give it a try. First, some testing results on my laptop with 4GB RAM, 2x2.26Ghz CPU and SSD: 1,143 images, total 263.8MB. ACF9: 8 duplicates, took ~2.3 s Railo 3.3: 8 duplicates, took ~2.0 s (yay!) I've used great tip from [this SO answer](https://stackoverflow.com/questions/415953/generate-md5-hash-in-java/416829#416829) to pick the best hashing option. So, here is what I did: ``` <cfsetting enablecfoutputonly="true" /> <cfset ticks = getTickCount() /> <!--- this is great set of utils from Apache ---> <cfset digestUtils = CreateObject("java","org.apache.commons.codec.digest.DigestUtils") /> <!--- cache containers ---> <cfset checksums = {} /> <cfset duplicates = {} /> <cfdirectory action="list" name="images" directory="/home/trovich/images/" filter="*.png|*.jpg|*.jpeg|*.gif" recurse="true" /> <cfloop query="images"> <!--- change delimiter to \ if you're on windoze ---> <cfset ipath = images.directory & "/" & images.name /> <cffile action="readbinary" file="#ipath#" variable="binimage" /> <!--- This is slow as hell with any encoding! <cfset checksum = BinaryEncode(binimage, "Base64") /> ---> <cfset checksum = digestUtils.md5hex(binimage) /> <cfif StructKeyExists(checksums, checksum)> <!--- init cache using original on 1st position when duplicate found ---> <cfif NOT StructKeyExists(duplicates, checksum)> <cfset duplicates[checksum] = [] /> <cfset ArrayAppend(duplicates[checksum], checksums[checksum]) /> </cfif> <!--- append current duplicate ---> <cfset ArrayAppend(duplicates[checksum], ipath) /> <cfelse> <!--- save originals only into the cache ---> <cfset checksums[checksum] = ipath /> </cfif> </cfloop> <cfset time = NumberFormat((getTickcount()-ticks)/1000, "._") /> <!--- render duplicates without resizing (see options of cfimage for this) ---> <cfoutput> <h1>Found #StructCount(duplicates)# duplicates, took ~#time# s</h1> <cfloop collection="#duplicates#" item="checksum"> <p> <!--- display all found paths of duplicate ---> <cfloop array="#duplicates[checksum]#" index="path"> #HTMLEditFormat(path)#<br/> </cfloop> <!--- render only last duplicate, they are the same image any way ---> <cfimage action="writeToBrowser" source="#path#" /> </p> </cfloop> </cfoutput> ``` Obviously, you can easily use `duplicates` array to review the results and/or run some cleanup job. Have fun!
I would recommend split up the checking code into a function which only accepts a filename. Then use a global struct for checking for duplicates, the key would be "size" or "size\_hash" and the value could be an array which will contain all filenames that matches this key. Run the function on all jpeg files in all different directories, after that scan the struct and report all entries that have more than one file in it's array. If you want to show an image outside your webroot you can serve it via < cfcontent file="#filename#" type="image/jpeg">
66,411,436
Let's say I have a document like this: ``` <persons> <person age="14" name="John"/> <person age="23" name="Rob"/> ... </persons> ``` I want to find the youngest person in the list. It seems I could do this with an ordinary XPath expression (something like `//person[@age=min(//person/@age)]`). In XSLT 3 I could also write an accumulator like this: ``` <xsl:accumulator name="acc" initial-value="()"> <xsl:accumulator-rule match="person" select="if(@age &lt; $value/@age) then . else $value"/> </xsl:accumulator> ``` And then call `accumulator-after('acc')` when I need it. In a non-streaming context, is there a benefit in using one over the other? I would think that, at the least, using an accumulator would save me from writing potentially inefficient XPath expressions. Or would a sophisticated XPath processor (in my case, Saxon) optimize the query to the equivalent of using an accumulator and is it therefore not important how I do it?
2021/02/28
[ "https://Stackoverflow.com/questions/66411436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2704291/" ]
The cases where an accumulator might be faster than a regular XPath expression are where you need to compute some value for many nodes in a document (for example, a section number, or a year-to-date total), and the value for node N can be conveniently expressed as a function of the value for an earlier node. xsl:number is a classic case. But you could also achieve this using XSLT 3.0 memo functions. If your XPath expression uses the preceding axis, then that's a signal that accumulators might help.
The most "creative" use of an accumulator without streaming I could come up with so far is when trying to use the XPath 3.1 function `random-number-generator`, it is kind of tricky to use the `?next()` function if you want to process it for certain nodes in the tree, an accumulator makes that easy, for example: ``` <xsl:accumulator name="random-number" as="map(*)" initial-value="random-number-generator(current-dateTime())"> <xsl:accumulator-rule match="*" select="$value?next()"/> </xsl:accumulator> ``` and use it as in e.g. ``` <xsl:template match="*"> <xsl:comment select="accumulator-before('random-number')?number"/> <xsl:next-match/> </xsl:template> ``` That kind of processing where you don't need a single value but need to compute a value for certain matched nodes in a tree where the value of the next node depends on the previous one is the kind of use an accumulator without streaming where a single XPath expressions might be harder or you would need to use a tunnel parameter in XSLT 2 or 3 if not using an accumulator.
73,887,238
I would like to mutate new columns with residuals by solving an easy equation of linear regression. Let's say that I have the table below which contains more columns with the same structure. Each linear function has the same dependent variable. | Dependent\_VAR | X\_Independent | X\_Coefficient | X\_Intercept | Y\_Intependent | Y\_Coefficient | Y\_Intercept | | --- | --- | --- | --- | --- | --- | --- | | 1200 | 2000 | 3000 | 4500 | 500 | 750 | 600 | | 3100 | 3000 | 3000 | 4500 | 670 | 750 | 600 | | 52222 | 55500 | 3000 | 4500 | 700 | 750 | 600 | | 400 | 456 | 3000 | 4500 | 800 | 750 | 600 | I want to find the residual for each column name of the dataframe by creating new columns with the new name *name\_Residual* like X\_Residual = X\_Independent-(X\_Intercept+X\_Coefficient\*Dependent\_VAR). I would prefer a solution using dplyr.
2022/09/28
[ "https://Stackoverflow.com/questions/73887238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15230150/" ]
Another option would be to first reshape your data to tidy format using `tidyr::pivot_longer`. Afterwards computing the residuals is pretty straightforward: ```r library(dplyr) library(tidyr) dat |> pivot_longer(-Dependent_VAR, names_to = c("name", ".value"), names_sep = "_") |> mutate(Residual = Independent - (Intercept + Dependent_VAR * Coefficient)) #> # A tibble: 8 × 6 #> Dependent_VAR name Independent Coefficient Intercept Residual #> <int> <chr> <int> <int> <int> <int> #> 1 1200 X 2000 3000 4500 -3602500 #> 2 1200 Y 500 750 600 -900100 #> 3 3100 X 3000 3000 4500 -9301500 #> 4 3100 Y 670 750 600 -2324930 #> 5 52222 X 55500 3000 4500 -156615000 #> 6 52222 Y 700 750 600 -39166400 #> 7 400 X 456 3000 4500 -1204044 #> 8 400 Y 800 750 600 -299800 ``` And if necessary you could of course reshape back to wide afterwards: ```r dat |> pivot_longer(-Dependent_VAR, names_to = c("name", ".value"), names_sep = "_") |> mutate(Residual = Independent - (Intercept + Dependent_VAR * Coefficient)) |> pivot_wider(names_from = name, values_from = !c(Dependent_VAR, name)) #> # A tibble: 4 × 9 #> Dependent_VAR Indepe…¹ Indep…² Coeff…³ Coeff…⁴ Inter…⁵ Inter…⁶ Resid…⁷ Resid…⁸ #> <int> <int> <int> <int> <int> <int> <int> <int> <int> #> 1 1200 2000 500 3000 750 4500 600 -3.60e6 -9.00e5 #> 2 3100 3000 670 3000 750 4500 600 -9.30e6 -2.32e6 #> 3 52222 55500 700 3000 750 4500 600 -1.57e8 -3.92e7 #> 4 400 456 800 3000 750 4500 600 -1.20e6 -3.00e5 #> # … with abbreviated variable names ¹​Independent_X, ²​Independent_Y, #> # ³​Coefficient_X, ⁴​Coefficient_Y, ⁵​Intercept_X, ⁶​Intercept_Y, ⁷​Residual_X, #> # ⁸​Residual_Y ``` **DATA** ``` dat <- data.frame( Dependent_VAR = c(1200L, 3100L, 52222L, 400L), X_Independent = c(2000L, 3000L, 55500L, 456L), X_Coefficient = c(3000L, 3000L, 3000L, 3000L), X_Intercept = c(4500L, 4500L, 4500L, 4500L), Y_Independent = c(500L, 670L, 700L, 800L), Y_Coefficient = c(750L, 750L, 750L, 750L), Y_Intercept = c(600L, 600L, 600L, 600L) ) ```
Here is a possible approach, it uses `!!sym(var)` to use the text stored in `var` as a variable name. There are several other ways to do the same thing, see the [Programming with dplyr vignette](https://dplyr.tidyverse.org/articles/programming.html). ```r prefix_list = c("X_","Y_") for(prefix in prefix_list){ this_independent = paste0(prefix,"Independent") this_coefficient = paste0(prefix,"Coefficient") this_intercept = paste0(prefix,"Intercept") this_interdependent = paste0(prefix,"Interpendent") this_residual = paste0(prefix,"Residual") df = df %>% mutate(!!sym(this_residual) := !!sym(this_independent) - !!sym(this_intercept) - !!sym(this_coefficient) * !!sym(this_interdepdendent)) } ```
7,767,811
I have a view controller in Cocoa Touch that detects when the device rotates and switches between the views of the 2 view controllers it has: landscape and portrait. I want the `UIViewControllers` in it to be able to access the `FRRRotatingViewController`, in a similar way as all `UIViewControllers` can access the `UINavigationController` they're in. So I created a `UIViewController` subclass (`FRRViewController`) that will have a `rotatingViewController` property. I also modified `FRRRotatingViewController`, so it takes `FRRViewControllers` instead of plain `UIViewControllers`. Unfortunately, when I include `FRRRotatingViewController.h` in `FRRViewController.h` (and vice versa), I seem to get into a circular import issue. I don't know how to fix it. Any suggestions? Here's the code: ``` // // FRRViewController.h #import <UIKit/UIKit.h> #import "FRRRotatingViewController.h" @interface FRRViewController : UIViewController @end // // FRRRotatingViewController.h #import <UIKit/UIKit.h> #import "FRRViewController.h" @class FRRRotatingViewController; @protocol FRRRotatingViewControllerDelegate -(void) FRRRotatingViewControllerWillSwitchToLandscapeView: (FRRRotatingViewController *) sender; -(void) FRRRotatingViewControllerWillSwitchToPortraitView: (FRRRotatingViewController *) sender; @end @interface FRRRotatingViewController : FRRViewController { // This is where I get the error:Cannot find interface declaration for // 'FRRViewController', superclass of 'FRRRotatingViewController'; did you // mean 'UIViewController'? } @property (strong) UIViewController *landscapeViewController; @property (strong) UIViewController *portraitViewController; @property (unsafe_unretained) id<FRRRotatingViewControllerDelegate> delegate; -(FRRRotatingViewController *) initWithLandscapeViewController: (UIViewController *) landscape andPortraitViewController: (UIViewController *) portrait; -(void) deviceDidRotate: (NSNotification *) aNotification; @end ```
2011/10/14
[ "https://Stackoverflow.com/questions/7767811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74415/" ]
You can use forward declarations for classes and protocols in headers in most situations to avoid circular import issues, except in the case of inheritance. In `FRRViewController.h`, instead of importing `FRRRotatingViewController.h`, can you not make a forward declaration? ``` @class FRRRotatingViewController; ```
If I'm reading it right your inheritance structure is like so: UIViewController-->FRRViewController-->FRRRotatingViewController But you have made the declaration of FRRViewController dependent on importing the file from its subclass, FRRRotatingViewController. The compiler will therefore be importing and reading FRRRotatingViewController before it processes the rest of FRRViewController.h. I'm assuming you've missed out some of FRRViewController.h since there is no reference to any rotating view controllers in there, but if you are declaring a property in .h of FRRRotatingViewController, then you need to use a forward declaration in FRRViewController.h: ``` @class FRRRotatingViewController ``` instead of ``` #import "FRRRotatingViewController.h" ``` The latter line, you can put in the first line of your `FRRViewController.m` file.
19,289,176
my xml file name is product\_file.xml and i have an xslt file , i am using a xml control in my webpage by binding xml & xslt files to the control but i am not getting the output properly. It showing only header multiple times ``` <?xml version="1.0" encoding="utf-8" ?> <productlist> <product> <itemnumber>1</itemnumber> <name>Staple Superior Men’s Jacket</name> <description>The Staple Superior T-bone PU Jacket is classic hood with a drawstring fastening, long and a zip up front fastening.</description> <color>BLACK</color> <image>Staplesuperior1.gif</image> <price>$140</price> <size>69</size> <quantity>1</quantity> <category>Men</category> </product> <product> <itemnumber>2</itemnumber> <name>Afends Mens t-shirt</name> <description>The Afends Thrash For Cash Raglan Tee has a scooped hemline, a 100% cotton composition, and a regular fit.</description> <color>Beach Heather &amp; Black</color> <image>Afends1.gif</image> <price>$90</price> <size>80</size> <quantity>1</quantity> <category>Men</category> </product> <product> <itemnumber>3</itemnumber> <name>Wrangler Men Blue Vegas Skinny Fit Jeans</name> <description>Blue 5 pocket jeans, stretchable, has a zip fly with buttoned closure in front, 2 scoop pockets at sides</description> <image>Wrangler1.gif</image> <color>BLUE</color> <price>$125</price> <size>32</size> <quantity>1</quantity> <category>Men</category> </product> <product> <itemnumber>4</itemnumber> <name>Roadster Women Top</name> <description>Black top, knit, V neck, short extended sleeves, lattice like fabric manipulation detail at shoulders</description> <color>BLACK</color> <image>Roadster.gif</image> <price>$55</price> <size>Small</size> <quantity>1</quantity> <category>Women</category> </product> ``` and my xslt file is ``` <xsl:template match="product"> <html> <head> <title>Products XSLT Demo</title> </head> <body> <h2>Products Information</h2> <br/> <!--<xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy>--> <table bgcolor="#008BE7" border="1"> <xsl:for-each select="itemnumber"> <tr> <td>Item Number</td> <td> <xsl:value-of select="itemnumber"/> </td> </tr> <tr> <td>name</td> <td> <xsl:value-of select="name"/> </td> </tr> <tr> <td>description</td> <td> <xsl:value-of select="description"/> </td> </tr> <tr> <td>color</td> <td> <xsl:value-of select="color"/> </td> </tr> <tr> <td>price</td> <td> <xsl:value-of select="price"/> </td> </tr> <tr> <td>size</td> <td> <xsl:value-of select="size"/> </td> </tr> <tr> <td>quantity</td> <td> <xsl:value-of select="quantity"/> </td> </tr> <tr> <td>category</td> <td> <xsl:value-of select="category"/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> ``` now the error is the foreach expression not working so the ouput showing only heading multiple times
2013/10/10
[ "https://Stackoverflow.com/questions/19289176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2181131/" ]
This seems to be working for me. changing the `templatematch` to `productlist` and `foreach` to `product` ``` <xsl:template match="productlist"> <html> <head> <title>Products XSLT Demo</title> </head> <body> <h2>Products Information</h2> <br/> <!--<xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy>--> <table bgcolor="#008BE7" border="1"> <xsl:for-each select="product"> <tr> <td>Item Number</td> <td> <xsl:value-of select="itemnumber"/> </td> </tr> <tr> <td>name</td> <td> <xsl:value-of select="name"/> </td> </tr> <tr> <td>description</td> <td> <xsl:value-of select="description"/> </td> </tr> <tr> <td>color</td> <td> <xsl:value-of select="color"/> </td> </tr> <tr> <td>price</td> <td> <xsl:value-of select="price"/> </td> </tr> <tr> <td>size</td> <td> <xsl:value-of select="size"/> </td> </tr> <tr> <td>quantity</td> <td> <xsl:value-of select="quantity"/> </td> </tr> <tr> <td>category</td> <td> <xsl:value-of select="category"/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> ```
Change the foreach to ``` <xsl:for-each select="."> ```
69,254,469
Trying to make a card menu that is a quick link to app's main sections. I tried using TextButton.Icon ( but since the word count varies too much from 8-letter word to 19-letter word, the font size becomes too small for the shorter word, so the aesthetics looks weird. I'm thinking to make the label of the button to two lines as shown in the JPEG attached. [![](https://i.stack.imgur.com/4kQHr.jpg)](https://i.stack.imgur.com/4kQHr.jpg) Wondering if this is possible with a container inside a material button instead? ```js import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class QuickMenu extends StatelessWidget { const QuickMenu({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.white, appBar: AppBar( automaticallyImplyLeading: false, //to remove back button backgroundColor: Colors.white, flexibleSpace: Container( margin: EdgeInsets.fromLTRB(4.0, 25.0, 4.0, 3.0), height: 55.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image( image: AssetImage('images/logo.png'), ), IconButton( onPressed: () {}, icon: Icon( Icons.notifications_outlined, size: 35.0, color: Color(0xFF959DA8), ), ), ], ), ), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Card( margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 15.0), clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: const EdgeInsets.fromLTRB(10.0, 5.0, 15.0, 3.0), child: Text( 'MENU BUTTONS', style: TextStyle( fontFamily: "Roboto", fontSize: 20.0, color: Color(0xFFD4D7DA), ), ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 1', style: TextStyle( fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox( width: 10.0, ), TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 2', style: TextStyle( fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 75.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.fromLTRB(2.0, 2.0, 2.0, 8.0), child: Expanded( child: Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 3', style: TextStyle( fontFamily: 'Roboto', fontSize: 8.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox( width: 10.0, ), TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 4', style: TextStyle( fontFamily: 'Roboto', fontSize: 8.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 75.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ), ), ], ), ], ), ), ], ), ), ); } } ```
2021/09/20
[ "https://Stackoverflow.com/questions/69254469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14116691/" ]
Try with this and also if you used a list or column you can make it expanded ``` import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class QuickMenu extends StatelessWidget { const QuickMenu({Key key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.white, appBar: AppBar( automaticallyImplyLeading: false, //to remove back button backgroundColor: Colors.white, flexibleSpace: Container( margin: EdgeInsets.fromLTRB(4.0, 25.0, 4.0, 3.0), height: 55.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image( image: AssetImage('images/profile.png'), ), IconButton( onPressed: () {}, icon: Icon( Icons.notifications_outlined, size: 35.0, color: Color(0xFF959DA8), ), ), ], ), ), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Card( margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 15.0), clipBehavior: Clip.antiAlias, color: Colors.grey, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: const EdgeInsets.fromLTRB(10.0, 5.0, 15.0, 3.0), child: Text( 'MENU BUTTONS', style: TextStyle( fontFamily: "Roboto", fontSize: 20.0, color: Color(0xFFD4D7DA), ), ), ), ], ), Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home), label: Container( width: 100,// change width as you need height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "Text", textAlign: TextAlign.left, maxLines: 2, // change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox(width: 10,), TextButton.icon( onPressed: () {}, icon: Icon(Icons.payments_rounded), label: Container( width: 100, // change width as you need height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "Text Button 2", textAlign: TextAlign.left, maxLines: 2, style: TextStyle(fontSize: 24),// change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), SizedBox(height: 10,), Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.shopping_cart), label: Container( width: 100, height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "TextButton 3 ", textAlign: TextAlign.left, maxLines: 2, // change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox(width: 10,), TextButton.icon( onPressed: () {}, icon: Icon(Icons.person_outline), label: Container( width: 100, // change width as you need height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "TextButton 4", textAlign: TextAlign.left, maxLines: 2, // change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ], ), ), ), ], ), ), ); } } ``` output: [![enter image description here](https://i.stack.imgur.com/vp1NN.png)](https://i.stack.imgur.com/vp1NN.png)
Just simply use column widget in the label ``` TextButton.icon( onPressed: () {}, icon: const Icon(Icons.home, color: Colors.white, size: 30.0), label: Column( children: const [ Text( 'Text Button Title', style: TextStyle(fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), Text( 'Text Button Subtitle', style: TextStyle(fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), ], ), style: TextButton.styleFrom( padding: const EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: const Color(0xFFD4D7DA), ), ), ``` **OR** You can simply use Row widget ``` InkWell( onTap: () {}, child: Container( padding: const EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), color: const Color(0xFFD4D7DA), child: Row( children: const [ Icon(Icons.home, color: Colors.white, size: 30.0), SizedBox(width: 12), Expanded( child: Text( 'Text Button 1', softWrap: true, style: TextStyle(fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), ), ], ), ), ), ```
69,254,469
Trying to make a card menu that is a quick link to app's main sections. I tried using TextButton.Icon ( but since the word count varies too much from 8-letter word to 19-letter word, the font size becomes too small for the shorter word, so the aesthetics looks weird. I'm thinking to make the label of the button to two lines as shown in the JPEG attached. [![](https://i.stack.imgur.com/4kQHr.jpg)](https://i.stack.imgur.com/4kQHr.jpg) Wondering if this is possible with a container inside a material button instead? ```js import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class QuickMenu extends StatelessWidget { const QuickMenu({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.white, appBar: AppBar( automaticallyImplyLeading: false, //to remove back button backgroundColor: Colors.white, flexibleSpace: Container( margin: EdgeInsets.fromLTRB(4.0, 25.0, 4.0, 3.0), height: 55.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image( image: AssetImage('images/logo.png'), ), IconButton( onPressed: () {}, icon: Icon( Icons.notifications_outlined, size: 35.0, color: Color(0xFF959DA8), ), ), ], ), ), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Card( margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 15.0), clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: const EdgeInsets.fromLTRB(10.0, 5.0, 15.0, 3.0), child: Text( 'MENU BUTTONS', style: TextStyle( fontFamily: "Roboto", fontSize: 20.0, color: Color(0xFFD4D7DA), ), ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 1', style: TextStyle( fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox( width: 10.0, ), TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 2', style: TextStyle( fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 75.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.fromLTRB(2.0, 2.0, 2.0, 8.0), child: Expanded( child: Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 3', style: TextStyle( fontFamily: 'Roboto', fontSize: 8.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox( width: 10.0, ), TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 4', style: TextStyle( fontFamily: 'Roboto', fontSize: 8.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 75.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ), ), ], ), ], ), ), ], ), ), ); } } ```
2021/09/20
[ "https://Stackoverflow.com/questions/69254469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14116691/" ]
Try with this and also if you used a list or column you can make it expanded ``` import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class QuickMenu extends StatelessWidget { const QuickMenu({Key key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.white, appBar: AppBar( automaticallyImplyLeading: false, //to remove back button backgroundColor: Colors.white, flexibleSpace: Container( margin: EdgeInsets.fromLTRB(4.0, 25.0, 4.0, 3.0), height: 55.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image( image: AssetImage('images/profile.png'), ), IconButton( onPressed: () {}, icon: Icon( Icons.notifications_outlined, size: 35.0, color: Color(0xFF959DA8), ), ), ], ), ), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Card( margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 15.0), clipBehavior: Clip.antiAlias, color: Colors.grey, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: const EdgeInsets.fromLTRB(10.0, 5.0, 15.0, 3.0), child: Text( 'MENU BUTTONS', style: TextStyle( fontFamily: "Roboto", fontSize: 20.0, color: Color(0xFFD4D7DA), ), ), ), ], ), Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home), label: Container( width: 100,// change width as you need height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "Text", textAlign: TextAlign.left, maxLines: 2, // change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox(width: 10,), TextButton.icon( onPressed: () {}, icon: Icon(Icons.payments_rounded), label: Container( width: 100, // change width as you need height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "Text Button 2", textAlign: TextAlign.left, maxLines: 2, style: TextStyle(fontSize: 24),// change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), SizedBox(height: 10,), Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.shopping_cart), label: Container( width: 100, height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "TextButton 3 ", textAlign: TextAlign.left, maxLines: 2, // change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox(width: 10,), TextButton.icon( onPressed: () {}, icon: Icon(Icons.person_outline), label: Container( width: 100, // change width as you need height: 70, // change height as you need child: Align( alignment: Alignment.centerLeft, child: Text( "TextButton 4", textAlign: TextAlign.left, maxLines: 2, // change max line you need ), ), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ], ), ), ), ], ), ), ); } } ``` output: [![enter image description here](https://i.stack.imgur.com/vp1NN.png)](https://i.stack.imgur.com/vp1NN.png)
To create UI like this, you just need to follow these steps: 1. Take a Column widget. 2. Inside column, take a **Align(alignment:Alignment.left, child: Text("Menu Buttons")** ) 3. After that take two Rows ``` Row(children: [ Container( height: 60, width: 100, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [Icon(Icons.add), Text("Text")])), Container( height: 60, width: 100, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [Icon(Icons.add), Text("Text")])), ]), ```
69,254,469
Trying to make a card menu that is a quick link to app's main sections. I tried using TextButton.Icon ( but since the word count varies too much from 8-letter word to 19-letter word, the font size becomes too small for the shorter word, so the aesthetics looks weird. I'm thinking to make the label of the button to two lines as shown in the JPEG attached. [![](https://i.stack.imgur.com/4kQHr.jpg)](https://i.stack.imgur.com/4kQHr.jpg) Wondering if this is possible with a container inside a material button instead? ```js import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class QuickMenu extends StatelessWidget { const QuickMenu({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.white, appBar: AppBar( automaticallyImplyLeading: false, //to remove back button backgroundColor: Colors.white, flexibleSpace: Container( margin: EdgeInsets.fromLTRB(4.0, 25.0, 4.0, 3.0), height: 55.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image( image: AssetImage('images/logo.png'), ), IconButton( onPressed: () {}, icon: Icon( Icons.notifications_outlined, size: 35.0, color: Color(0xFF959DA8), ), ), ], ), ), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Card( margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 15.0), clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: const EdgeInsets.fromLTRB(10.0, 5.0, 15.0, 3.0), child: Text( 'MENU BUTTONS', style: TextStyle( fontFamily: "Roboto", fontSize: 20.0, color: Color(0xFFD4D7DA), ), ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 1', style: TextStyle( fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox( width: 10.0, ), TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 2', style: TextStyle( fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 75.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.fromLTRB(2.0, 2.0, 2.0, 8.0), child: Expanded( child: Row( children: [ TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 3', style: TextStyle( fontFamily: 'Roboto', fontSize: 8.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), SizedBox( width: 10.0, ), TextButton.icon( onPressed: () {}, icon: Icon(Icons.home, color: Colors.white, size: 30.0), label: Text( 'Text Button 4', style: TextStyle( fontFamily: 'Roboto', fontSize: 8.0, color: Colors.white), ), style: TextButton.styleFrom( padding: EdgeInsets.fromLTRB(10.0, 8.0, 75.0, 8.0), backgroundColor: Color(0xFFD4D7DA), ), ), ], ), ), ), ], ), ], ), ), ], ), ), ); } } ```
2021/09/20
[ "https://Stackoverflow.com/questions/69254469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14116691/" ]
Just simply use column widget in the label ``` TextButton.icon( onPressed: () {}, icon: const Icon(Icons.home, color: Colors.white, size: 30.0), label: Column( children: const [ Text( 'Text Button Title', style: TextStyle(fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), Text( 'Text Button Subtitle', style: TextStyle(fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), ], ), style: TextButton.styleFrom( padding: const EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), backgroundColor: const Color(0xFFD4D7DA), ), ), ``` **OR** You can simply use Row widget ``` InkWell( onTap: () {}, child: Container( padding: const EdgeInsets.fromLTRB(10.0, 8.0, 20.0, 8.0), color: const Color(0xFFD4D7DA), child: Row( children: const [ Icon(Icons.home, color: Colors.white, size: 30.0), SizedBox(width: 12), Expanded( child: Text( 'Text Button 1', softWrap: true, style: TextStyle(fontFamily: 'Roboto', fontSize: 15.0, color: Colors.white), ), ), ], ), ), ), ```
To create UI like this, you just need to follow these steps: 1. Take a Column widget. 2. Inside column, take a **Align(alignment:Alignment.left, child: Text("Menu Buttons")** ) 3. After that take two Rows ``` Row(children: [ Container( height: 60, width: 100, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [Icon(Icons.add), Text("Text")])), Container( height: 60, width: 100, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [Icon(Icons.add), Text("Text")])), ]), ```
66,756,062
I'm looking at the NPM package csv-parser that parses csv files to JSON. Based on the example provided, you can read a csv file row by row in the following manner: ``` fs.createReadStream('data.csv') .pipe(csv()) .on('data', (rowData) => console.log(rowData)) .on('end', () => { console.log("done reading the file") }); ``` Is there any way I can only return the header values of the CSV file instead?
2021/03/23
[ "https://Stackoverflow.com/questions/66756062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3102993/" ]
You can use headers event ``` fs.createReadStream('data.csv') .pipe(csv()) .on('headers', (headers) => { console.log(`First header: ${headers[0]}`) }) ``` **From official docs** [![enter image description here](https://i.stack.imgur.com/61r4d.png)](https://i.stack.imgur.com/61r4d.png)
<https://github.com/mafintosh/csv-parser#headers-1> > > Emitted after the header row is parsed. The first parameter of the event callback is an Array[String] containing the header names. > > > use `.on('headers', (headers)` event ``` fs.createReadStream('data.csv') .pipe(csv()) .on('headers', (headers) => { console.log(headers) }) ```
66,756,062
I'm looking at the NPM package csv-parser that parses csv files to JSON. Based on the example provided, you can read a csv file row by row in the following manner: ``` fs.createReadStream('data.csv') .pipe(csv()) .on('data', (rowData) => console.log(rowData)) .on('end', () => { console.log("done reading the file") }); ``` Is there any way I can only return the header values of the CSV file instead?
2021/03/23
[ "https://Stackoverflow.com/questions/66756062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3102993/" ]
You can use headers event ``` fs.createReadStream('data.csv') .pipe(csv()) .on('headers', (headers) => { console.log(`First header: ${headers[0]}`) }) ``` **From official docs** [![enter image description here](https://i.stack.imgur.com/61r4d.png)](https://i.stack.imgur.com/61r4d.png)
In addition to this answer <https://stackoverflow.com/a/66756097/12285424>, if you only need to read headers, you should destroy the read stream in order to stop it from parsing the entire file, e.g: ``` let myHeaders; let readStream = fs.createReadStream('data.csv'); readStream .pipe(csv()) .on('headers', (headers) => { console.log(`First header: ${headers[0]}`) myHeaders = headers; readStream.destroy(); }) ```
9,771,514
Here's my implementation of Merge Sort in java ``` import java.io.*; import java.util.Arrays; public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while(k < D.length){ D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while(k < D.length){ D[k++] = B[i++]; } } if(i<B.length && j<C.length) { if(B[i] > C[j]){ D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ``` The output I get is ``` 2 1 ``` From what I can tell there seems a problem with my division of the right sub array. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9771514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632447/" ]
If your array has 10 elements, then LeftSubArray copies elements 0..5, and RightSubArray copies elements 6..10. But if the first element is at index 0, then there is no element w/ an index 10. And if copyOfRange(a,b) gives elements indexed a..b-1, then LeftSA is yielding 0..4 and RightSA is yielding 6..9. Either way, your assumption about division seems to be accurate.
With your code [1,3,5,2,4] is split into [1,3] and [2,4]. Good luck
9,771,514
Here's my implementation of Merge Sort in java ``` import java.io.*; import java.util.Arrays; public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while(k < D.length){ D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while(k < D.length){ D[k++] = B[i++]; } } if(i<B.length && j<C.length) { if(B[i] > C[j]){ D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ``` The output I get is ``` 2 1 ``` From what I can tell there seems a problem with my division of the right sub array. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9771514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632447/" ]
Here is the javadoc of copyOfRange: ``` Parameters: original - the array from which a range is to be copied from - the initial index of the range to be copied, **inclusive** to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.) ``` I highlighted two words you should pay special attention to ;-)
If your array has 10 elements, then LeftSubArray copies elements 0..5, and RightSubArray copies elements 6..10. But if the first element is at index 0, then there is no element w/ an index 10. And if copyOfRange(a,b) gives elements indexed a..b-1, then LeftSA is yielding 0..4 and RightSA is yielding 6..9. Either way, your assumption about division seems to be accurate.
9,771,514
Here's my implementation of Merge Sort in java ``` import java.io.*; import java.util.Arrays; public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while(k < D.length){ D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while(k < D.length){ D[k++] = B[i++]; } } if(i<B.length && j<C.length) { if(B[i] > C[j]){ D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ``` The output I get is ``` 2 1 ``` From what I can tell there seems a problem with my division of the right sub array. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9771514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632447/" ]
If your array has 10 elements, then LeftSubArray copies elements 0..5, and RightSubArray copies elements 6..10. But if the first element is at index 0, then there is no element w/ an index 10. And if copyOfRange(a,b) gives elements indexed a..b-1, then LeftSA is yielding 0..4 and RightSA is yielding 6..9. Either way, your assumption about division seems to be accurate.
This piece of code works: you had couple of errors: see next diffs: * rightSubArray method * copy the remainder of B * copy the remainder of C The code that works follows: ``` public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int[] rightHalf = Arrays.copyOfRange(Array, Array.length / 2, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while (j < C.length) { D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while (i < B.length) { D[k++] = B[i++]; } } if (i < B.length && j < C.length) { if (B[i] > C[j]) { D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ```
9,771,514
Here's my implementation of Merge Sort in java ``` import java.io.*; import java.util.Arrays; public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while(k < D.length){ D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while(k < D.length){ D[k++] = B[i++]; } } if(i<B.length && j<C.length) { if(B[i] > C[j]){ D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ``` The output I get is ``` 2 1 ``` From what I can tell there seems a problem with my division of the right sub array. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9771514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632447/" ]
If your array has 10 elements, then LeftSubArray copies elements 0..5, and RightSubArray copies elements 6..10. But if the first element is at index 0, then there is no element w/ an index 10. And if copyOfRange(a,b) gives elements indexed a..b-1, then LeftSA is yielding 0..4 and RightSA is yielding 6..9. Either way, your assumption about division seems to be accurate.
I found a rigth solution in Robert Sedgewick book "Algorithms on java language" 1. Read [here about merge](http://algs4.cs.princeton.edu/22mergesort/)
9,771,514
Here's my implementation of Merge Sort in java ``` import java.io.*; import java.util.Arrays; public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while(k < D.length){ D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while(k < D.length){ D[k++] = B[i++]; } } if(i<B.length && j<C.length) { if(B[i] > C[j]){ D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ``` The output I get is ``` 2 1 ``` From what I can tell there seems a problem with my division of the right sub array. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9771514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632447/" ]
Here is the javadoc of copyOfRange: ``` Parameters: original - the array from which a range is to be copied from - the initial index of the range to be copied, **inclusive** to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.) ``` I highlighted two words you should pay special attention to ;-)
With your code [1,3,5,2,4] is split into [1,3] and [2,4]. Good luck
9,771,514
Here's my implementation of Merge Sort in java ``` import java.io.*; import java.util.Arrays; public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while(k < D.length){ D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while(k < D.length){ D[k++] = B[i++]; } } if(i<B.length && j<C.length) { if(B[i] > C[j]){ D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ``` The output I get is ``` 2 1 ``` From what I can tell there seems a problem with my division of the right sub array. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9771514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632447/" ]
Here is the javadoc of copyOfRange: ``` Parameters: original - the array from which a range is to be copied from - the initial index of the range to be copied, **inclusive** to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.) ``` I highlighted two words you should pay special attention to ;-)
This piece of code works: you had couple of errors: see next diffs: * rightSubArray method * copy the remainder of B * copy the remainder of C The code that works follows: ``` public class MergeSort { private static int [] LeftSubArray(int [] Array) { int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2); return leftHalf; } private static int [] RightSubArray(int [] Array) { int[] rightHalf = Arrays.copyOfRange(Array, Array.length / 2, Array.length); return rightHalf; } private static int [] Sort(int [] A) { if(A.length > 1) { return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) ); } else { return A; } } private static int [] Merge(int [] B, int [] C) { int [] D = new int[B.length + C.length]; int i,j,k; i = j = k = 0; while(k < D.length) { if(i == B.length) { //Copy the remainder of C into D while (j < C.length) { D[k++] = C[j++]; } } if(j == C.length) { //Copy the remainder of B into D while (i < B.length) { D[k++] = B[i++]; } } if (i < B.length && j < C.length) { if (B[i] > C[j]) { D[k++] = B[i++]; } else { D[k++] = C[j++]; } } } return D; } public static void main(String [] args) { int [] array = {1,3,5,2,4}; int [] sorted = MergeSort.Sort(array); for(int i = 0;i < sorted.length; ++i) { System.out.print(sorted[i] + " "); } } } ```