qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
33,095,072
How can I launch a new Activity to a Fragment that is not the initial fragment? For example, the following code is wrong. I want to launch the MainActivity.class AT the SecondFragment.class. Seems simple enough but cannot find an answer anywhere. All help is greatly appreciated! ``` public void LaunchSecondFragment(View view) { view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click)); Intent intent = new Intent(this, SecondFragment.class); startActivity(intent); } ```
2015/10/13
[ "https://Stackoverflow.com/questions/33095072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950598/" ]
So, before starting an activity you have to do something like: ``` Intent intent = new Intent(this, MainActivity.class); intent.putExtra("launchSecondFragment", true) startActivity(intent) ``` and in your MainActivity onCreate() ``` if(getIntent().getBooleanExtra("launchSecondFragment", false)) { //do fragment transaction to second fragment } else { //do fragment transaction to the first fragment } ``` **UPDATE** So, here is the clever way to do it. First of all create enum in your MainActivity.class ``` public enum FragmentNames { FIRST_FRAGMENT, SECOND_FRAGMENT } ``` then define a string constant for getting and putting this extra(also in MainActivity) ``` public static final String FRAGMENT_EXTRA = "fragmentExtra"; ``` So now when you start an activity you should do it like this: ``` Intent intent = new Intent(this, MainActivity.class); intent.putExtra(MainActivity.FRAGMENT_EXTRA, MainActivity.FragmentNames.SECOND_FRAGMENT); startActivity(intent); ``` And catch in your MainActivity onCreate() method: ``` FragmentNames name = getIntent().getSerializableExtra(FRAGMENT_EXTRA); switch(name) { case FIRST_FRAGMENT: //do stuff break; case SECOND_FRAGMENT: //do stuff break; default: //load default fragment(FirstFragment for example) } ``` What else is cool about enums? You mentioned that you are using this intents to define current item of your ViewPager. Well, good news, enums have ordinal(). Basically you can do something like: ``` mViewPager.setCurrentItem(name.ordinal()); ``` In this case ordinal() of the FIRST\_FRAGMENT is 0 and ordinal of SECOND\_FRAGMENT is 1. Just don't forget to check for nulls :) Cheers.
When user clicks button and your `MainActivity` opens, its `onCreate()` will be get called. You should add fragment transaction in `onCreate()` to launch `SecondFragment` : ``` FragmentTransaction ft = getFragmentManager().beginTransaction(); SecondFragment secondFragment = new SecondFragment(); ft.replace(R.id.content_frame, secondFragment); ft.commitAllowingStateLoss(); ```
33,095,072
How can I launch a new Activity to a Fragment that is not the initial fragment? For example, the following code is wrong. I want to launch the MainActivity.class AT the SecondFragment.class. Seems simple enough but cannot find an answer anywhere. All help is greatly appreciated! ``` public void LaunchSecondFragment(View view) { view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click)); Intent intent = new Intent(this, SecondFragment.class); startActivity(intent); } ```
2015/10/13
[ "https://Stackoverflow.com/questions/33095072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950598/" ]
Try this to start the activity: ``` Intent intent = new Intent(this, MainActivity.class); int fragmentIndex = 2; intent.putExtra("fragment_index", fragmentIndex); startActivity(intent); ``` and this for the MainActivity's onCreate ``` Bundle extras = getIntent().getExtras(); int fragmentIndex; if(extras != null) { fragmentIndex = extras.getInt("fragment_index",1); } switch(fragmentIndex) { case 1: //display fragment 1 break; case 2: //display fragment 2 break; case 3: //display fragment 3 break; } ```
When user clicks button and your `MainActivity` opens, its `onCreate()` will be get called. You should add fragment transaction in `onCreate()` to launch `SecondFragment` : ``` FragmentTransaction ft = getFragmentManager().beginTransaction(); SecondFragment secondFragment = new SecondFragment(); ft.replace(R.id.content_frame, secondFragment); ft.commitAllowingStateLoss(); ```
33,095,072
How can I launch a new Activity to a Fragment that is not the initial fragment? For example, the following code is wrong. I want to launch the MainActivity.class AT the SecondFragment.class. Seems simple enough but cannot find an answer anywhere. All help is greatly appreciated! ``` public void LaunchSecondFragment(View view) { view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click)); Intent intent = new Intent(this, SecondFragment.class); startActivity(intent); } ```
2015/10/13
[ "https://Stackoverflow.com/questions/33095072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950598/" ]
So, before starting an activity you have to do something like: ``` Intent intent = new Intent(this, MainActivity.class); intent.putExtra("launchSecondFragment", true) startActivity(intent) ``` and in your MainActivity onCreate() ``` if(getIntent().getBooleanExtra("launchSecondFragment", false)) { //do fragment transaction to second fragment } else { //do fragment transaction to the first fragment } ``` **UPDATE** So, here is the clever way to do it. First of all create enum in your MainActivity.class ``` public enum FragmentNames { FIRST_FRAGMENT, SECOND_FRAGMENT } ``` then define a string constant for getting and putting this extra(also in MainActivity) ``` public static final String FRAGMENT_EXTRA = "fragmentExtra"; ``` So now when you start an activity you should do it like this: ``` Intent intent = new Intent(this, MainActivity.class); intent.putExtra(MainActivity.FRAGMENT_EXTRA, MainActivity.FragmentNames.SECOND_FRAGMENT); startActivity(intent); ``` And catch in your MainActivity onCreate() method: ``` FragmentNames name = getIntent().getSerializableExtra(FRAGMENT_EXTRA); switch(name) { case FIRST_FRAGMENT: //do stuff break; case SECOND_FRAGMENT: //do stuff break; default: //load default fragment(FirstFragment for example) } ``` What else is cool about enums? You mentioned that you are using this intents to define current item of your ViewPager. Well, good news, enums have ordinal(). Basically you can do something like: ``` mViewPager.setCurrentItem(name.ordinal()); ``` In this case ordinal() of the FIRST\_FRAGMENT is 0 and ordinal of SECOND\_FRAGMENT is 1. Just don't forget to check for nulls :) Cheers.
Try this to start the activity: ``` Intent intent = new Intent(this, MainActivity.class); int fragmentIndex = 2; intent.putExtra("fragment_index", fragmentIndex); startActivity(intent); ``` and this for the MainActivity's onCreate ``` Bundle extras = getIntent().getExtras(); int fragmentIndex; if(extras != null) { fragmentIndex = extras.getInt("fragment_index",1); } switch(fragmentIndex) { case 1: //display fragment 1 break; case 2: //display fragment 2 break; case 3: //display fragment 3 break; } ```
39,787,004
``` <% if(session == null) { System.out.println("Expire"); response.sendRedirect("/login.jsp"); }else{ System.out.println("Not Expire"); } %> <% HttpSession sess = request.getSession(false); String email = sess.getAttribute("email").toString(); Connection conn = Database.getConnection(); Statement st = conn.createStatement(); String sql = "select * from login where email = '" + email + "' "; ResultSet rs = st.executeQuery(sql); %> ``` I tried to redirect the login.jsp page when session is expired. But I am geeting error in "String email = sesss.getAttribute("email").toString();". So anyone please help me to solve this error. Basically I want to redirect to login.jsp page when the session is expired.
2016/09/30
[ "https://Stackoverflow.com/questions/39787004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5533485/" ]
TimeSpan can be negative. So just substract the TimeSpan for 4PM with current [TimeOfDay](https://msdn.microsoft.com/en-us/library/system.datetime.timeofday), if you get negative value, add 24 hours. ``` var timeLeft = new TimeSpan(16, 0, 0) - DateTime.Now.TimeOfDay; if (timeLeft.Ticks<0) { timeLeft = timeLeft.Add(new TimeSpan(24,0,0)) } ```
The answer is really simple, I should have seened this earlier. The solution to these kind of problems is basically modular arithmetic. The client requirment was the popup to show 24+ time to next 4 pm (Don't ask i don't know) so if: program runs at 13:00 then the clock should display 24 +3 = 27 when 16:00 it should be 24+24 which is 48 when 22:00 it shoould be 24 + 18 which is 42 Now I noticed that: 13 + 27 = 40 16 + 24 = 40 22 + 18 = 40 40 Modulo 24 = 16 So basically if I subtract the current time from 40 then I will be left with the difference: 40 - 13 = 27 40 - 16 = 24 40 - 22 = 18 So what I did is this: ``` TimeSpan TimeToInstall; TimeSpan TimeGiven = new TimeSpan(23, 59, 59); DateTime Now = DateTime.Now; long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks; TimeToInstall = TimeSpan.FromTicks(TimeTo4); ``` EDIT The above was a trap Corrected: ``` DateTime Now = DateTime.Now; if (Now.Hour < 16) { long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks); TimeToInstall = TimeSpan.FromTicks(TimeTo4); } else { long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks; TimeToInstall = TimeSpan.FromTicks(TimeTo4); } ```
39,787,004
``` <% if(session == null) { System.out.println("Expire"); response.sendRedirect("/login.jsp"); }else{ System.out.println("Not Expire"); } %> <% HttpSession sess = request.getSession(false); String email = sess.getAttribute("email").toString(); Connection conn = Database.getConnection(); Statement st = conn.createStatement(); String sql = "select * from login where email = '" + email + "' "; ResultSet rs = st.executeQuery(sql); %> ``` I tried to redirect the login.jsp page when session is expired. But I am geeting error in "String email = sesss.getAttribute("email").toString();". So anyone please help me to solve this error. Basically I want to redirect to login.jsp page when the session is expired.
2016/09/30
[ "https://Stackoverflow.com/questions/39787004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5533485/" ]
Based on your code: ``` DateTime now = DateTime.Now; DateTime today4pmDateTime= new DateTime(now.Year, now.Month, now.Day, 16, 0, 0); //Will hold the next 4pm DateTime. DateTime next4pmDateTimeOccurrence = now.Hour >= 16 ? today4pmDateTime : today4pmDateTime.AddDays(1); //From here you can do all the calculations you need TimeSpan timeUntilNext4pm = next4pmDateTimeOccurrence - now; ```
The answer is really simple, I should have seened this earlier. The solution to these kind of problems is basically modular arithmetic. The client requirment was the popup to show 24+ time to next 4 pm (Don't ask i don't know) so if: program runs at 13:00 then the clock should display 24 +3 = 27 when 16:00 it should be 24+24 which is 48 when 22:00 it shoould be 24 + 18 which is 42 Now I noticed that: 13 + 27 = 40 16 + 24 = 40 22 + 18 = 40 40 Modulo 24 = 16 So basically if I subtract the current time from 40 then I will be left with the difference: 40 - 13 = 27 40 - 16 = 24 40 - 22 = 18 So what I did is this: ``` TimeSpan TimeToInstall; TimeSpan TimeGiven = new TimeSpan(23, 59, 59); DateTime Now = DateTime.Now; long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks; TimeToInstall = TimeSpan.FromTicks(TimeTo4); ``` EDIT The above was a trap Corrected: ``` DateTime Now = DateTime.Now; if (Now.Hour < 16) { long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks); TimeToInstall = TimeSpan.FromTicks(TimeTo4); } else { long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks; TimeToInstall = TimeSpan.FromTicks(TimeTo4); } ```
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
Try simplifying it a little bit: ``` print htmlentities(file_get_contents("http://www.arstechnica.com")); ``` The above outputs instantly on my webserver. If it doesn't on yours, there's a good chance your web host has some kind of setting in place to throttle these kind of requests. **EDIT**: Since the above happens instantly for you, try setting [this curl setting](http://www.php.net/manual/en/function.curl-setopt.php) on your original code: ``` curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true); ``` Using the tool you posted, I noticed that `http://www.arstechnica.com` has a 301 header sent for any request sent to it. It is possible that cURL is getting this and not following the new Location specified to it, thus causing your script to hang. **SECOND EDIT**: Curiously enough, trying the same code you have above was making my webserver hang too. I replaced this code: ``` curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' ``` With this: ``` curl_setopt($ch, CURLOPT_NOBODY, true); ``` Which is the way [the manual](http://www.php.net/manual/en/function.curl-setopt.php) recommends you do a HEAD request. It made it work instantly.
If my memory doesn't fails me doing a HEAD request in CURL changes the HTTP protocol version to 1.0 (which is slow and probably the guilty part here) try changing that to: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // ADD THIS $content = curl_exec ($ch); curl_close ($ch); ```
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
Try simplifying it a little bit: ``` print htmlentities(file_get_contents("http://www.arstechnica.com")); ``` The above outputs instantly on my webserver. If it doesn't on yours, there's a good chance your web host has some kind of setting in place to throttle these kind of requests. **EDIT**: Since the above happens instantly for you, try setting [this curl setting](http://www.php.net/manual/en/function.curl-setopt.php) on your original code: ``` curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true); ``` Using the tool you posted, I noticed that `http://www.arstechnica.com` has a 301 header sent for any request sent to it. It is possible that cURL is getting this and not following the new Location specified to it, thus causing your script to hang. **SECOND EDIT**: Curiously enough, trying the same code you have above was making my webserver hang too. I replaced this code: ``` curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' ``` With this: ``` curl_setopt($ch, CURLOPT_NOBODY, true); ``` Which is the way [the manual](http://www.php.net/manual/en/function.curl-setopt.php) recommends you do a HEAD request. It made it work instantly.
You have to remember that HEAD is only a suggestion to the web server. For HEAD to do the right thing it often takes some explicit effort on the part of the admins. If you HEAD a static file Apache (or whatever your webserver is) will often step in an do the right thing. If you HEAD a dynamic page, the default for most setups is to execute the GET path, collect all the results, and just send back the headers without the content. If that application is in a 3 (or more) tier setup, that call could potentially be very expensive and needless for a HEAD context. For instance, on a Java servlet, by default doHead() just calls doGet(). To do something a little smarter for the application the developer would have to explicitly implement doHead() (and more often than not, they will not). I encountered an app from a fortune 100 company that is used for downloading several hundred megabytes of pricing information. We'd check for updates to that data by executing HEAD requests fairly regularly until the modified date changed. It turns out that this request would actually make back end calls to generate this list every time we made the request which involved gigabytes of data on their back end and xfer it between several internal servers. They weren't terribly happy with us but once we explained the use case they quickly came up with an alternate solution. If they had implemented HEAD, rather than relying on their web server to fake it, it would not have been an issue.
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
Try simplifying it a little bit: ``` print htmlentities(file_get_contents("http://www.arstechnica.com")); ``` The above outputs instantly on my webserver. If it doesn't on yours, there's a good chance your web host has some kind of setting in place to throttle these kind of requests. **EDIT**: Since the above happens instantly for you, try setting [this curl setting](http://www.php.net/manual/en/function.curl-setopt.php) on your original code: ``` curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true); ``` Using the tool you posted, I noticed that `http://www.arstechnica.com` has a 301 header sent for any request sent to it. It is possible that cURL is getting this and not following the new Location specified to it, thus causing your script to hang. **SECOND EDIT**: Curiously enough, trying the same code you have above was making my webserver hang too. I replaced this code: ``` curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' ``` With this: ``` curl_setopt($ch, CURLOPT_NOBODY, true); ``` Which is the way [the manual](http://www.php.net/manual/en/function.curl-setopt.php) recommends you do a HEAD request. It made it work instantly.
This: ``` curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); ``` I wasn't trying to get headers. I was just trying to make the page load of some data not take 2 minutes similar to described above. That magical little options has dropped it down to 2 seconds.
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
Try simplifying it a little bit: ``` print htmlentities(file_get_contents("http://www.arstechnica.com")); ``` The above outputs instantly on my webserver. If it doesn't on yours, there's a good chance your web host has some kind of setting in place to throttle these kind of requests. **EDIT**: Since the above happens instantly for you, try setting [this curl setting](http://www.php.net/manual/en/function.curl-setopt.php) on your original code: ``` curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true); ``` Using the tool you posted, I noticed that `http://www.arstechnica.com` has a 301 header sent for any request sent to it. It is possible that cURL is getting this and not following the new Location specified to it, thus causing your script to hang. **SECOND EDIT**: Curiously enough, trying the same code you have above was making my webserver hang too. I replaced this code: ``` curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' ``` With this: ``` curl_setopt($ch, CURLOPT_NOBODY, true); ``` Which is the way [the manual](http://www.php.net/manual/en/function.curl-setopt.php) recommends you do a HEAD request. It made it work instantly.
I used the below function to find out the redirected URL. ``` $head = get_headers($url, 1); ``` The second argument makes it return an array with keys. For e.g. the below will give the `Location` value. ``` $head["Location"] ``` <http://php.net/manual/en/function.get-headers.php>
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
You have to remember that HEAD is only a suggestion to the web server. For HEAD to do the right thing it often takes some explicit effort on the part of the admins. If you HEAD a static file Apache (or whatever your webserver is) will often step in an do the right thing. If you HEAD a dynamic page, the default for most setups is to execute the GET path, collect all the results, and just send back the headers without the content. If that application is in a 3 (or more) tier setup, that call could potentially be very expensive and needless for a HEAD context. For instance, on a Java servlet, by default doHead() just calls doGet(). To do something a little smarter for the application the developer would have to explicitly implement doHead() (and more often than not, they will not). I encountered an app from a fortune 100 company that is used for downloading several hundred megabytes of pricing information. We'd check for updates to that data by executing HEAD requests fairly regularly until the modified date changed. It turns out that this request would actually make back end calls to generate this list every time we made the request which involved gigabytes of data on their back end and xfer it between several internal servers. They weren't terribly happy with us but once we explained the use case they quickly came up with an alternate solution. If they had implemented HEAD, rather than relying on their web server to fake it, it would not have been an issue.
If my memory doesn't fails me doing a HEAD request in CURL changes the HTTP protocol version to 1.0 (which is slow and probably the guilty part here) try changing that to: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // ADD THIS $content = curl_exec ($ch); curl_close ($ch); ```
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
If my memory doesn't fails me doing a HEAD request in CURL changes the HTTP protocol version to 1.0 (which is slow and probably the guilty part here) try changing that to: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // ADD THIS $content = curl_exec ($ch); curl_close ($ch); ```
This: ``` curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); ``` I wasn't trying to get headers. I was just trying to make the page load of some data not take 2 minutes similar to described above. That magical little options has dropped it down to 2 seconds.
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
You have to remember that HEAD is only a suggestion to the web server. For HEAD to do the right thing it often takes some explicit effort on the part of the admins. If you HEAD a static file Apache (or whatever your webserver is) will often step in an do the right thing. If you HEAD a dynamic page, the default for most setups is to execute the GET path, collect all the results, and just send back the headers without the content. If that application is in a 3 (or more) tier setup, that call could potentially be very expensive and needless for a HEAD context. For instance, on a Java servlet, by default doHead() just calls doGet(). To do something a little smarter for the application the developer would have to explicitly implement doHead() (and more often than not, they will not). I encountered an app from a fortune 100 company that is used for downloading several hundred megabytes of pricing information. We'd check for updates to that data by executing HEAD requests fairly regularly until the modified date changed. It turns out that this request would actually make back end calls to generate this list every time we made the request which involved gigabytes of data on their back end and xfer it between several internal servers. They weren't terribly happy with us but once we explained the use case they quickly came up with an alternate solution. If they had implemented HEAD, rather than relying on their web server to fake it, it would not have been an issue.
This: ``` curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); ``` I wasn't trying to get headers. I was just trying to make the page load of some data not take 2 minutes similar to described above. That magical little options has dropped it down to 2 seconds.
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
You have to remember that HEAD is only a suggestion to the web server. For HEAD to do the right thing it often takes some explicit effort on the part of the admins. If you HEAD a static file Apache (or whatever your webserver is) will often step in an do the right thing. If you HEAD a dynamic page, the default for most setups is to execute the GET path, collect all the results, and just send back the headers without the content. If that application is in a 3 (or more) tier setup, that call could potentially be very expensive and needless for a HEAD context. For instance, on a Java servlet, by default doHead() just calls doGet(). To do something a little smarter for the application the developer would have to explicitly implement doHead() (and more often than not, they will not). I encountered an app from a fortune 100 company that is used for downloading several hundred megabytes of pricing information. We'd check for updates to that data by executing HEAD requests fairly regularly until the modified date changed. It turns out that this request would actually make back end calls to generate this list every time we made the request which involved gigabytes of data on their back end and xfer it between several internal servers. They weren't terribly happy with us but once we explained the use case they quickly came up with an alternate solution. If they had implemented HEAD, rather than relying on their web server to fake it, it would not have been an issue.
I used the below function to find out the redirected URL. ``` $head = get_headers($url, 1); ``` The second argument makes it return an array with keys. For e.g. the below will give the `Location` value. ``` $head["Location"] ``` <http://php.net/manual/en/function.get-headers.php>
770,179
I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete. For example, requesting `http://www.arstechnica.com` takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay. Here's the code I have: ``` $ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); ``` Here's a link to the web site that does the same function: <http://www.seoconsultants.com/tools/headers.asp> The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away. What am I missing?
2009/04/20
[ "https://Stackoverflow.com/questions/770179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
I used the below function to find out the redirected URL. ``` $head = get_headers($url, 1); ``` The second argument makes it return an array with keys. For e.g. the below will give the `Location` value. ``` $head["Location"] ``` <http://php.net/manual/en/function.get-headers.php>
This: ``` curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); ``` I wasn't trying to get headers. I was just trying to make the page load of some data not take 2 minutes similar to described above. That magical little options has dropped it down to 2 seconds.
41,292,734
First off, this is my first post, so if I incorrectly posted this in the wrong location, please let me know. So, what we're trying to accomplish is building a powershell script that we can throw on our workstation image so that once our Windows 10 boxes are done imaging, that we can click on a powershell script, have it pull the key from the BIOS, and automagically activate it. That being said, here is the script that we've put together from various sources. --- ``` (Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey | out-file c:\license.txt $computer = gc env:computername $key = get-content c:\license.txt $service = get-wmiObject -query “select * from SoftwareLicensingService” -computername $computer $service.InstallProductKey($key) <--------THIS IS WHERE IT FAILS $service.RefreshLicenseStatus() ``` --- We start running into the issues on the line `$service.InstallProductKey($key)`. It seems, that no matter how we try to invoke that, it will consistently fail with the error "Exception calling "InstallProductKey"". I've even replaced the variable (`$key`) with the specific activation key, and it STILL fails with the same error. The reason we have it outputting to a license txt file part way through is so that we can verify that the command is indeed pulling the product key (which it is). At this point, I'm not sure where to go. It seems that people have tried to do this before, however, nobody has really wrapped up their posting with what worked and/or what didn't. I can't imagine that this is impossible, but I'm also not fond of wasting anymore time than needed, so anybody that has any insight into this issue, I'd be very grateful. We've gotten it to work on two machines that were previously activated, and later deactivated, but on new machines that have been freshly imaged, and have yet to be activated, it will fail every time.
2016/12/22
[ "https://Stackoverflow.com/questions/41292734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7332516/" ]
Two things as per my observation: ``` (Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey | out-file c:\license.txt ``` I don't think that it is returning any value to your license.txt. If yes, then I would like you to see if there is any space before and after the license key. You can use *trim* during getting the content from the file. Second thing, when you are getting the content from the file make sure it is not separating into multiple lines. In that case, you have to cast it as string like **[String]$key** or you can call **toString()** method for this. One more important thing is to refresh after the installation. ``` $service.RefreshLicenseStatus() ``` **Note:** Make sure you are running the shell in elevated mode. **Alternative: Try Hardcoding the values and see the result** ``` $key = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" # hardcode the key $computer= "Computer01" # Hardcode the computer $service = get-wmiObject -query "select * from SoftwareLicensingService" -computername $computer $service.InstallProductKey($key) $service.RefreshLicenseStatus() ``` For further thing ,please post the exact error. Hope it helps...!!!
Found out that the key from `Get-WmiObject` has whitespace on the end. The original command will work if a `.Trim()` is added. Also not running as administrator will result in the same error. ``` (Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey | out-file c:\license.txt $computer = gc env:computername $key = (get-content c:\license.txt).Trim() #trim here $service = get-wmiObject -query “select * from SoftwareLicensingService” -computername $computer $service.InstallProductKey($key) $service.RefreshLicenseStatus() ```
23,567,099
I have an query related to straight join the query is correct but showing error ``` SELECT table112.id,table112.bval1,table112.bval2, table111.id,table111.aval1 FROM table112 STRAIGHT_JOIN table111; ``` Showing an error can anybody help out this
2014/05/09
[ "https://Stackoverflow.com/questions/23567099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3612276/" ]
There is missing the join condition. ``` SELECT table112.id,table112.bval1,table112.bval2, table111.id,table111.aval1 FROM table112 STRAIGHT_JOIN table111 ON table112.id = table111.id ```
``` SELECT table112.id, table112.bval1, table112.bval2, table111.id,table111.aval1 FROM table112 ``` That is not a join ``` Select * from table112 join table111 ON table112.id = table111.id ``` That is how a join works. What are you trying to do? I might be able to help more than.
35,219,203
``` import iAd @IBOutlet weak var Banner: ADBannerView! override func viewDidLoad() { super.viewDidLoad() Banner.hidden = true Banner.delegate = self self.canDisplayBannerAds = true } func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool { return true } func bannerViewDidLoadAd(banner: ADBannerView!) { self.Banner.hidden = false } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { NSLog("Error") } func bannerViewWillLoadAd(banner: ADBannerView!) { } ``` Hello, I am currently developing an iOS app with Xcode 7.2, Swift 2.0, and iOS 9.2. I have implemented iAds, and it works perfectly. However in my region the fill rate is not high, and I would like to use Google's AdMob to advertise on my app, as a backup. I would like for the AdMob banner ad to show up when iAd does not receive an ad. Note that I am new to Swift, and have no knowledge of Objective-C. Thanks.
2016/02/05
[ "https://Stackoverflow.com/questions/35219203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843135/" ]
Your connection string looks like it's not in line with what's specified in the [documentation](https://msdn.microsoft.com/en-us/library/ms378428(v=sql.110).aspx). Try changing your connection string from: ``` "jdbc:sqlserver://localhost:1433;sa;VMADMIN#123;" ``` To: ``` "jdbc:sqlserver://localhost:1433;user=sa;password={VMADMIN#123};" ```
try this it will definitely work ``` Connection con = DriverManager .getConnection("jdbc:sqlserver://localhost:1433;databaseName=<name of your database>;user=sa;password=VMADMIN#123"); ```
29,804,680
I am working with `ViewPager` i.e on top of the `MainActivity` class and the `Viewpager` class extends fragment. The problem is that, normally when we need a class to return some `result` then while passing the `intent` we use `startActivityforresult(intent,int)` hence it passes the result captured in the secondactivity the class from where it's been called. **But as i am working with viewpager on top of the mainactivity and i am using `floating action button`, when i click the button to open the second activity it returns the result to the mainactivity but not the viewpager class.** > > **So my question is how can i pass the result taken from the secondactivity to my desired class?** > > > **Update::** `MainActivity.java` this is my main class which is using the intent as well as receiving the result from the second activity class `ActivityTwo` What i have done here is ``` startActivityForResult(intent,1); public void onActivityresult(i,j,intent){MyFragment fragment; fragment.onActivityReusult(i,j,intent);//Here i have passes the values received by this class to the fragment class where i need the values but it's not working } ```
2015/04/22
[ "https://Stackoverflow.com/questions/29804680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4578454/" ]
Some suggested improvements: ``` BEGIN { split("KS .07 MO .08",tmp) for (i=1;i in tmp;i+=2) taxRate[tmp[i]] = tmp[i+1] fmtS = "%12s%s\n" fmtF = "%12s$%.2f\n" } NR>1 { name=$1" "$2 state=$3 payRate=$4 hoursWorked=$5 overtime=$6 grossPay=(hoursWorked+(overtime*1.5))*payRate tax = grossPay* taxRate[state] netPay = grossPay-tax printf fmtS, "Name", "State" printf fmtS, name, state printf fmtF, "Gross Pay:", grossPay printf fmtF, "Taxes:", tax printf fmtF, "Net Pay:", netPay } END { print "\n-complete-" } ```
Thanks to zzevann here's my final code ``` #!/bin/awk -f #Skips the first line NR==1{next;} { name=$1" "$2 state=$3 payRate=$4 hoursWorked=$5 overtime=$6 grossPay=(hoursWorked+(overtime*1.5))*payRate if (state == "KS") tax = grossPay* .07 else if (state == "MO") tax = grossPay* .08 else tax = 0 #If tax reads 0 you KNOW something's wrong netPay = grossPay-tax print "\nName \tState" print name, "\t" state, "\nGross Pay:\t$" grossPay, "\nTaxes: \t$" tax, "\nNet Pay:\t$" netPay } END{ print "\n-complete-" } ``` with the final output ``` Name State John Doe MO Gross Pay: $371.25 Taxes: $29.7 Net Pay: $341.55 Name State Jane Doe KS Gross Pay: $672 Taxes: $47.04 Net Pay: $624.96 Name State Sam Smith MO Gross Pay: $1690 Taxes: $135.2 Net Pay: $1554.8 Name State Barb Jones MO Gross Pay: $1808 Taxes: $144.64 Net Pay: $1663.36 Name State Jenny Lind KS Gross Pay: $294 Taxes: $20.58 Net Pay: $273.42 ```
6,030,137
I am trying to build a WCF service that allows me to send large binary files from clients to the service. However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond) **The Error I get if I try to send the 4.91MB file is:** **Exception Message:** An error occurred while receiving the HTTP response to <http://localhost:56198/Service.svc>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. **Inner Exception Message:** The underlying connection was closed: An unexpected error occurred on a receive. **Inner Exception Message:** Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. **Inner Exception Message:** An existing connection was forcibly closed by the remote host This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method. I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error. I am going to paste my sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well. **Service Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00" openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="DragDrop.Service.ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> <dataContractSerializer maxItemsInObjectGraph="2147483646"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ``` **Client (Asp.net page) Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm=""> <extendedProtectionPolicy policyEnforcement="Never" /> </transport> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="debuggingBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483646" /> </behavior> </endpointBehaviors> </behaviors> <client> <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService" name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" /> </client> </system.serviceModel> ```
2011/05/17
[ "https://Stackoverflow.com/questions/6030137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402186/" ]
*(While I agree that [streaming transfer](http://msdn.microsoft.com/en-us/library/ms789010.aspx) would be preferrable, the below should make it work without any other changes)* You also need to increase the maximum message length in the Web.config: ``` <configuration> <system.web> <httpRuntime maxMessageLength="409600" executionTimeoutInSeconds="300"/> </system.web> </configuration> ``` This will set the maximum message length to 400 MB (parameter is in kB). Check [this MSDN page](http://msdn.microsoft.com/en-us/library/aa528822.aspx) for more information.
Have you had a look at using Streaming Transfer? > > Windows Communication Foundation (WCF) > can send messages using either > buffered or streamed transfers. In the > default buffered-transfer mode, a > message must be completely delivered > before a receiver can read it. In > streaming transfer mode, the receiver > can begin to process the message > before it is completely delivered. The > streaming mode is useful when the > information that is passed is lengthy > and can be processed serially. > Streaming mode is also useful when the > message is too large to be entirely > buffered. > > > <http://msdn.microsoft.com/en-us/library/ms789010.aspx>
6,030,137
I am trying to build a WCF service that allows me to send large binary files from clients to the service. However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond) **The Error I get if I try to send the 4.91MB file is:** **Exception Message:** An error occurred while receiving the HTTP response to <http://localhost:56198/Service.svc>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. **Inner Exception Message:** The underlying connection was closed: An unexpected error occurred on a receive. **Inner Exception Message:** Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. **Inner Exception Message:** An existing connection was forcibly closed by the remote host This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method. I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error. I am going to paste my sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well. **Service Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00" openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="DragDrop.Service.ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> <dataContractSerializer maxItemsInObjectGraph="2147483646"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ``` **Client (Asp.net page) Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm=""> <extendedProtectionPolicy policyEnforcement="Never" /> </transport> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="debuggingBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483646" /> </behavior> </endpointBehaviors> </behaviors> <client> <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService" name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" /> </client> </system.serviceModel> ```
2011/05/17
[ "https://Stackoverflow.com/questions/6030137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402186/" ]
As pointed out, try using [Streaming Transfer](http://msdn.microsoft.com/en-us/library/ms789010.aspx), here's some example code showing both sending and receiving (possibly) large amounts of data using streamed transfer. Use a **binding** like this, notice the `MaxReceivedMessageSize` and `TranferMode` settings. ``` <binding name="Streaming_Binding" maxReceivedMessageSize="67108864" messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"> </binding> ``` Add some **service code**: ``` [OperationContract] public Stream GetLargeFile() { return new FileStream(path, FileMode.Open, FileAccess.Read); } [OperationContract] public void SendLargeFile(Stream stream) { // Handle stream here - e.g. save to disk ProcessTheStream(stream); // Close the stream when done processing it stream.Close(); } ``` And some **client code**: ``` public Stream GetLargeFile() { var client = /* create proxy here */; try { var response = client.GetLargeFile(); // All communication is now handled by the stream, // thus we can close the proxy at this point client.Close(); return response; } catch (Exception) { client.Abort(); throw; } } public void SendLargeFile(string path) { var client = /* create proxy here */; client.SendLargeFile(new FileStream(path, FileMode.Open, FileAccess.Read)); } ``` Also, make sure you are not getting a timeout, a large file might take a while to transfer (the default receiveTimeout is 10 minutes though). You can download Microsoft WCF/WF sample code [here](https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/) (top C# link is broken at the time of writing but other samples code seems ok).
Have you had a look at using Streaming Transfer? > > Windows Communication Foundation (WCF) > can send messages using either > buffered or streamed transfers. In the > default buffered-transfer mode, a > message must be completely delivered > before a receiver can read it. In > streaming transfer mode, the receiver > can begin to process the message > before it is completely delivered. The > streaming mode is useful when the > information that is passed is lengthy > and can be processed serially. > Streaming mode is also useful when the > message is too large to be entirely > buffered. > > > <http://msdn.microsoft.com/en-us/library/ms789010.aspx>
6,030,137
I am trying to build a WCF service that allows me to send large binary files from clients to the service. However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond) **The Error I get if I try to send the 4.91MB file is:** **Exception Message:** An error occurred while receiving the HTTP response to <http://localhost:56198/Service.svc>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. **Inner Exception Message:** The underlying connection was closed: An unexpected error occurred on a receive. **Inner Exception Message:** Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. **Inner Exception Message:** An existing connection was forcibly closed by the remote host This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method. I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error. I am going to paste my sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well. **Service Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00" openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="DragDrop.Service.ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> <dataContractSerializer maxItemsInObjectGraph="2147483646"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ``` **Client (Asp.net page) Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm=""> <extendedProtectionPolicy policyEnforcement="Never" /> </transport> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="debuggingBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483646" /> </behavior> </endpointBehaviors> </behaviors> <client> <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService" name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" /> </client> </system.serviceModel> ```
2011/05/17
[ "https://Stackoverflow.com/questions/6030137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402186/" ]
Have you had a look at using Streaming Transfer? > > Windows Communication Foundation (WCF) > can send messages using either > buffered or streamed transfers. In the > default buffered-transfer mode, a > message must be completely delivered > before a receiver can read it. In > streaming transfer mode, the receiver > can begin to process the message > before it is completely delivered. The > streaming mode is useful when the > information that is passed is lengthy > and can be processed serially. > Streaming mode is also useful when the > message is too large to be entirely > buffered. > > > <http://msdn.microsoft.com/en-us/library/ms789010.aspx>
I'll echo what others have said and say that using a Streaming Transfer is the way to go when using Windows Communication Foundation. Below is an excellent guide that explains all of the steps in order to stream files over WCF. It's quite comprehensive and very informative. Here it is: [Guide on Streaming Files over WCF](http://bartwullems.blogspot.com/2011/01/streaming-files-over-wcf.html).
6,030,137
I am trying to build a WCF service that allows me to send large binary files from clients to the service. However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond) **The Error I get if I try to send the 4.91MB file is:** **Exception Message:** An error occurred while receiving the HTTP response to <http://localhost:56198/Service.svc>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. **Inner Exception Message:** The underlying connection was closed: An unexpected error occurred on a receive. **Inner Exception Message:** Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. **Inner Exception Message:** An existing connection was forcibly closed by the remote host This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method. I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error. I am going to paste my sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well. **Service Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00" openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="DragDrop.Service.ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> <dataContractSerializer maxItemsInObjectGraph="2147483646"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ``` **Client (Asp.net page) Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm=""> <extendedProtectionPolicy policyEnforcement="Never" /> </transport> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="debuggingBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483646" /> </behavior> </endpointBehaviors> </behaviors> <client> <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService" name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" /> </client> </system.serviceModel> ```
2011/05/17
[ "https://Stackoverflow.com/questions/6030137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402186/" ]
*(While I agree that [streaming transfer](http://msdn.microsoft.com/en-us/library/ms789010.aspx) would be preferrable, the below should make it work without any other changes)* You also need to increase the maximum message length in the Web.config: ``` <configuration> <system.web> <httpRuntime maxMessageLength="409600" executionTimeoutInSeconds="300"/> </system.web> </configuration> ``` This will set the maximum message length to 400 MB (parameter is in kB). Check [this MSDN page](http://msdn.microsoft.com/en-us/library/aa528822.aspx) for more information.
As pointed out, try using [Streaming Transfer](http://msdn.microsoft.com/en-us/library/ms789010.aspx), here's some example code showing both sending and receiving (possibly) large amounts of data using streamed transfer. Use a **binding** like this, notice the `MaxReceivedMessageSize` and `TranferMode` settings. ``` <binding name="Streaming_Binding" maxReceivedMessageSize="67108864" messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"> </binding> ``` Add some **service code**: ``` [OperationContract] public Stream GetLargeFile() { return new FileStream(path, FileMode.Open, FileAccess.Read); } [OperationContract] public void SendLargeFile(Stream stream) { // Handle stream here - e.g. save to disk ProcessTheStream(stream); // Close the stream when done processing it stream.Close(); } ``` And some **client code**: ``` public Stream GetLargeFile() { var client = /* create proxy here */; try { var response = client.GetLargeFile(); // All communication is now handled by the stream, // thus we can close the proxy at this point client.Close(); return response; } catch (Exception) { client.Abort(); throw; } } public void SendLargeFile(string path) { var client = /* create proxy here */; client.SendLargeFile(new FileStream(path, FileMode.Open, FileAccess.Read)); } ``` Also, make sure you are not getting a timeout, a large file might take a while to transfer (the default receiveTimeout is 10 minutes though). You can download Microsoft WCF/WF sample code [here](https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/) (top C# link is broken at the time of writing but other samples code seems ok).
6,030,137
I am trying to build a WCF service that allows me to send large binary files from clients to the service. However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond) **The Error I get if I try to send the 4.91MB file is:** **Exception Message:** An error occurred while receiving the HTTP response to <http://localhost:56198/Service.svc>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. **Inner Exception Message:** The underlying connection was closed: An unexpected error occurred on a receive. **Inner Exception Message:** Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. **Inner Exception Message:** An existing connection was forcibly closed by the remote host This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method. I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error. I am going to paste my sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well. **Service Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00" openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="DragDrop.Service.ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> <dataContractSerializer maxItemsInObjectGraph="2147483646"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ``` **Client (Asp.net page) Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm=""> <extendedProtectionPolicy policyEnforcement="Never" /> </transport> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="debuggingBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483646" /> </behavior> </endpointBehaviors> </behaviors> <client> <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService" name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" /> </client> </system.serviceModel> ```
2011/05/17
[ "https://Stackoverflow.com/questions/6030137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402186/" ]
*(While I agree that [streaming transfer](http://msdn.microsoft.com/en-us/library/ms789010.aspx) would be preferrable, the below should make it work without any other changes)* You also need to increase the maximum message length in the Web.config: ``` <configuration> <system.web> <httpRuntime maxMessageLength="409600" executionTimeoutInSeconds="300"/> </system.web> </configuration> ``` This will set the maximum message length to 400 MB (parameter is in kB). Check [this MSDN page](http://msdn.microsoft.com/en-us/library/aa528822.aspx) for more information.
I'll echo what others have said and say that using a Streaming Transfer is the way to go when using Windows Communication Foundation. Below is an excellent guide that explains all of the steps in order to stream files over WCF. It's quite comprehensive and very informative. Here it is: [Guide on Streaming Files over WCF](http://bartwullems.blogspot.com/2011/01/streaming-files-over-wcf.html).
6,030,137
I am trying to build a WCF service that allows me to send large binary files from clients to the service. However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond) **The Error I get if I try to send the 4.91MB file is:** **Exception Message:** An error occurred while receiving the HTTP response to <http://localhost:56198/Service.svc>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. **Inner Exception Message:** The underlying connection was closed: An unexpected error occurred on a receive. **Inner Exception Message:** Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. **Inner Exception Message:** An existing connection was forcibly closed by the remote host This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method. I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error. I am going to paste my sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well. **Service Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00" openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="DragDrop.Service.ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> <dataContractSerializer maxItemsInObjectGraph="2147483646"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ``` **Client (Asp.net page) Web.Config** ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm=""> <extendedProtectionPolicy policyEnforcement="Never" /> </transport> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="debuggingBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483646" /> </behavior> </endpointBehaviors> </behaviors> <client> <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService" name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" /> </client> </system.serviceModel> ```
2011/05/17
[ "https://Stackoverflow.com/questions/6030137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402186/" ]
As pointed out, try using [Streaming Transfer](http://msdn.microsoft.com/en-us/library/ms789010.aspx), here's some example code showing both sending and receiving (possibly) large amounts of data using streamed transfer. Use a **binding** like this, notice the `MaxReceivedMessageSize` and `TranferMode` settings. ``` <binding name="Streaming_Binding" maxReceivedMessageSize="67108864" messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"> </binding> ``` Add some **service code**: ``` [OperationContract] public Stream GetLargeFile() { return new FileStream(path, FileMode.Open, FileAccess.Read); } [OperationContract] public void SendLargeFile(Stream stream) { // Handle stream here - e.g. save to disk ProcessTheStream(stream); // Close the stream when done processing it stream.Close(); } ``` And some **client code**: ``` public Stream GetLargeFile() { var client = /* create proxy here */; try { var response = client.GetLargeFile(); // All communication is now handled by the stream, // thus we can close the proxy at this point client.Close(); return response; } catch (Exception) { client.Abort(); throw; } } public void SendLargeFile(string path) { var client = /* create proxy here */; client.SendLargeFile(new FileStream(path, FileMode.Open, FileAccess.Read)); } ``` Also, make sure you are not getting a timeout, a large file might take a while to transfer (the default receiveTimeout is 10 minutes though). You can download Microsoft WCF/WF sample code [here](https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/) (top C# link is broken at the time of writing but other samples code seems ok).
I'll echo what others have said and say that using a Streaming Transfer is the way to go when using Windows Communication Foundation. Below is an excellent guide that explains all of the steps in order to stream files over WCF. It's quite comprehensive and very informative. Here it is: [Guide on Streaming Files over WCF](http://bartwullems.blogspot.com/2011/01/streaming-files-over-wcf.html).
4,608,257
I evaluated the integral as follow, $$\int\_0^\pi \cos^3x dx=\int\_0^\pi(1-\sin^2x)\cos xdx$$ Here I used the substitution $u=\sin x$ and $du=\cos x dx$ and for $x\in [0,\pi]$ we have $\sin x\in [0,1]$ Hence the integral is, $$\int\_0^11-u^2du=u-\frac{u^3}3\large\vert ^1\_0=\small\frac23$$But the answer I got is wrong since if I evaluate the indefinite integral $\int \cos^3x dx$ I get $\sin x-\dfrac{\sin^3x}{3}$ and now if I apply the interval $[0,\pi]$ I get $\int\_0^\pi \cos^3x dx=0$. My question is why I got the wrong value in my approach and how to fix it?
2022/12/30
[ "https://math.stackexchange.com/questions/4608257", "https://math.stackexchange.com", "https://math.stackexchange.com/users/794843/" ]
The substitution rule can only be applied if the substitution is by a monotonous function. This is not the case for the sine on $[0,\pi]$. You would have to split the domain and apply the substitution rule separately on the intervals $[0,\frac\pi2]$ and $[\frac\pi2,\pi]$. In the other way you computed the primitive or anti-derivative and then applied the fundamental theorem of infinitesimal calculus. In this case there are no restrictions by monotonicity.
Else Use $\int\_{0}^a f(x) dx=\int\_{0}^a f(a-x) dx$ $I=\int\_{0}^{\pi} \cos^3x~ dx=-I \implies 2I =0 \implies I=0$
44,887,617
I'm trying to make a code that's verified if someone (1) is checking out his name but it does not really ``` <?php if($usrn['verified'] == 1): { ?> <i class="fa fa-check-circle verified verified-sm showTooltip" title="Verified User" data-toggle="tooltip" data-placement="right"></i> <?php } endif; ?> <?php $usern = protect($_GET['usern']); $sql = mysql_query("SELECT * FROM purchasify_users WHERE usern='$usern' OR id='$id'"); if(mysql_num_rows($sql)==0) { $redirect = $web['url']."not_found"; header("Location: $redirect"); } $row = mysql_fetch_array($sql); ?> ```
2017/07/03
[ "https://Stackoverflow.com/questions/44887617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8248870/" ]
Those "3 Dots" are the "Overflow" menu, and is created when you establish a menu using a file in the menu resources directory. If you have buttons or functionality you are wanting to expose via you action bar, you will need to have the overflow buttons (or instead, you can choose to have your buttons exposed at the top level *inside* the Action bar. If you really don't want a menu, get rid of the menu.xml file describing this menu, and then get rid of the onCreateOptionsMenu() from your Activity. Here are the [official docs](https://developer.android.com/training/appbar/actions.html), which describe how this works.
I think you are speaking about the [options menu](https://developer.android.com/guide/topics/ui/menus.html#options-menu), to get rid of it remove the override of the method onCreateOptionsMenu
44,887,617
I'm trying to make a code that's verified if someone (1) is checking out his name but it does not really ``` <?php if($usrn['verified'] == 1): { ?> <i class="fa fa-check-circle verified verified-sm showTooltip" title="Verified User" data-toggle="tooltip" data-placement="right"></i> <?php } endif; ?> <?php $usern = protect($_GET['usern']); $sql = mysql_query("SELECT * FROM purchasify_users WHERE usern='$usern' OR id='$id'"); if(mysql_num_rows($sql)==0) { $redirect = $web['url']."not_found"; header("Location: $redirect"); } $row = mysql_fetch_array($sql); ?> ```
2017/07/03
[ "https://Stackoverflow.com/questions/44887617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8248870/" ]
Just Remove Override Method like this ``` @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_and_add, menu); return true; } ``` This Override Method is responsible to for creating three dote as you mention it's really `OptionMenu`. If you don't want it, don't override `onCreateOptionsMenu`method. Alternative ----------- Don't Inflate the menu xml. Just block the line like this ``` //getMenuInflater().inflate(R.menu.search_and_add, menu); ``` other code can remain same. No problem at all..
I think you are speaking about the [options menu](https://developer.android.com/guide/topics/ui/menus.html#options-menu), to get rid of it remove the override of the method onCreateOptionsMenu
44,887,617
I'm trying to make a code that's verified if someone (1) is checking out his name but it does not really ``` <?php if($usrn['verified'] == 1): { ?> <i class="fa fa-check-circle verified verified-sm showTooltip" title="Verified User" data-toggle="tooltip" data-placement="right"></i> <?php } endif; ?> <?php $usern = protect($_GET['usern']); $sql = mysql_query("SELECT * FROM purchasify_users WHERE usern='$usern' OR id='$id'"); if(mysql_num_rows($sql)==0) { $redirect = $web['url']."not_found"; header("Location: $redirect"); } $row = mysql_fetch_array($sql); ?> ```
2017/07/03
[ "https://Stackoverflow.com/questions/44887617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8248870/" ]
Those "3 Dots" are the "Overflow" menu, and is created when you establish a menu using a file in the menu resources directory. If you have buttons or functionality you are wanting to expose via you action bar, you will need to have the overflow buttons (or instead, you can choose to have your buttons exposed at the top level *inside* the Action bar. If you really don't want a menu, get rid of the menu.xml file describing this menu, and then get rid of the onCreateOptionsMenu() from your Activity. Here are the [official docs](https://developer.android.com/training/appbar/actions.html), which describe how this works.
In your `menu` folder the `xml`file that is used by your activity, change the `app:showAsAction="never"` to `app:showAsAction="always"` or some other you can see the options that are availabe by pressing `ctrl+space`. Or else to get rid of it completely just remove the whole code and it's corresponding usages.
44,887,617
I'm trying to make a code that's verified if someone (1) is checking out his name but it does not really ``` <?php if($usrn['verified'] == 1): { ?> <i class="fa fa-check-circle verified verified-sm showTooltip" title="Verified User" data-toggle="tooltip" data-placement="right"></i> <?php } endif; ?> <?php $usern = protect($_GET['usern']); $sql = mysql_query("SELECT * FROM purchasify_users WHERE usern='$usern' OR id='$id'"); if(mysql_num_rows($sql)==0) { $redirect = $web['url']."not_found"; header("Location: $redirect"); } $row = mysql_fetch_array($sql); ?> ```
2017/07/03
[ "https://Stackoverflow.com/questions/44887617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8248870/" ]
Just Remove Override Method like this ``` @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_and_add, menu); return true; } ``` This Override Method is responsible to for creating three dote as you mention it's really `OptionMenu`. If you don't want it, don't override `onCreateOptionsMenu`method. Alternative ----------- Don't Inflate the menu xml. Just block the line like this ``` //getMenuInflater().inflate(R.menu.search_and_add, menu); ``` other code can remain same. No problem at all..
In your `menu` folder the `xml`file that is used by your activity, change the `app:showAsAction="never"` to `app:showAsAction="always"` or some other you can see the options that are availabe by pressing `ctrl+space`. Or else to get rid of it completely just remove the whole code and it's corresponding usages.
44,887,617
I'm trying to make a code that's verified if someone (1) is checking out his name but it does not really ``` <?php if($usrn['verified'] == 1): { ?> <i class="fa fa-check-circle verified verified-sm showTooltip" title="Verified User" data-toggle="tooltip" data-placement="right"></i> <?php } endif; ?> <?php $usern = protect($_GET['usern']); $sql = mysql_query("SELECT * FROM purchasify_users WHERE usern='$usern' OR id='$id'"); if(mysql_num_rows($sql)==0) { $redirect = $web['url']."not_found"; header("Location: $redirect"); } $row = mysql_fetch_array($sql); ?> ```
2017/07/03
[ "https://Stackoverflow.com/questions/44887617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8248870/" ]
Just Remove Override Method like this ``` @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_and_add, menu); return true; } ``` This Override Method is responsible to for creating three dote as you mention it's really `OptionMenu`. If you don't want it, don't override `onCreateOptionsMenu`method. Alternative ----------- Don't Inflate the menu xml. Just block the line like this ``` //getMenuInflater().inflate(R.menu.search_and_add, menu); ``` other code can remain same. No problem at all..
Those "3 Dots" are the "Overflow" menu, and is created when you establish a menu using a file in the menu resources directory. If you have buttons or functionality you are wanting to expose via you action bar, you will need to have the overflow buttons (or instead, you can choose to have your buttons exposed at the top level *inside* the Action bar. If you really don't want a menu, get rid of the menu.xml file describing this menu, and then get rid of the onCreateOptionsMenu() from your Activity. Here are the [official docs](https://developer.android.com/training/appbar/actions.html), which describe how this works.
49,438,437
I am working on this game on checkio.org. Its a python game and this level I need to find the word between two defined delimiters. The function calls them. So far I have done alright but I can't get any more help from google probably because I don't know how to ask for what i need. Anyways I am stuck and I would like to know where I am messing this up. ``` def between_markers(text: str, begin: str, end: str) -> str: """ returns substring between two given markers """ # your code here s = text #find the index for begin and end b = s.find(begin) + len(begin) c = s.find(end,b) #if there is a beginning delimiter return string from between if begin in s: return s[b:c] # if the begin is not the only return until end delimiter elif begin not in s: return s[:-c] #if the ending delimiter isnt there return from beinning to end of string elif end not in s: return s[b:] #if both delimiters are missing just return the text elif begin or end not in s: return s if __name__ == '__main__': # print('Example:') # print(between_markers('What is >apple<', '>', '<')) # These "asserts" are used for self-checking and not for testing assert between_markers('What is >apple<', '>', '<') == "apple", "One sym" assert between_markers("<head><title>My new site</title></head>", "<title>", "</title>") == "My new site", "HTML" assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened' assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close' assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all' assert between_markers('No <hi>', '>', '<') == '', 'Wrong direction' print('Wow, you are doing pretty good. Time to check it!') ``` I am stuck here wondering where I am wrong. `elif begin not in s: return s[:c]`: is where its going to hell. `return s[:c]` in theory should return everything up to `c` but it cuts off one letter before the end of the string and every slice i use cuts it off by one character. this `assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'` gives me `h` not `hi`. Using `[:-c]` fails me on the previous assert... Any pointers are welcome.
2018/03/22
[ "https://Stackoverflow.com/questions/49438437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`expand` method is equivalent to flatMap in Dart. ``` [1,2,3].expand((e) => [e, e+1]) ``` What is more interesting, the returned `Iterable` is lazy, and calls fuction for each element every time it's iterated.
*Coming from Swift, [`flatMap`](https://developer.apple.com/documentation/swift/sequence/2905332-flatmap) seems to have a little different meaning than the OP needed. This is a supplemental answer.* Given the following two dimensional list: ```dart final list = [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]; ``` You can convert it into a single dimensional iterable like so: ```dart final flattened = list.expand((element) => element); // (1, 2, 2, 3, 3, 3, 4, 4, 4, 4) ``` Or to a list by appending `toList`: ```dart final flattened = list.expand((element) => element).toList(); // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] ```
18,383,773
I'm facing the problem described in [this question](https://stackoverflow.com/questions/4031857/way-to-make-java-parent-class-method-return-object-of-child-class) but would like to find a solution (if possible) without all the casts and @SuppressWarning annotations. A better solution would be one that builds upon the referenced one by: * removing @SuppressWarning * removing casts Solutions presented here will be graded with 2 points based on the criteria. Bounty goes to solution with most points or the "most elegant" one if there is more than one with 2 points.
2013/08/22
[ "https://Stackoverflow.com/questions/18383773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586682/" ]
One approach is to define an abstract method `getThis()` in `Parent` class, and make all the `Child` classes override it, returning the `this` reference. This is a way to recover the type of `this` object in a class hierarchy. The code would look like this: ``` abstract class Parent<T extends Parent<T>> { protected abstract T getThis(); public T example() { System.out.println(this.getClass().getCanonicalName()); return getThis(); } } class ChildA extends Parent<ChildA> { @Override protected ChildA getThis() { return this; } public ChildA childAMethod() { System.out.println(this.getClass().getCanonicalName()); return this; } } class ChildB extends Parent<ChildB> { @Override protected ChildB getThis() { return this; } public ChildB childBMethod() { return this; } } public class Main { public static void main(String[] args) throws NoSuchMethodException { ChildA childA = new ChildA(); ChildB childB = new ChildB(); childA.example().childAMethod().example(); childB.example().childBMethod().example(); } } ``` As per requirement, there is no *Casting* and no *@SuppressWarnings*. I learnt this trick few days back from [Angelika Langer - Java Generics FAQs](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html). **Reference:** * [How do I recover the actual type of the this object in a class hierarchy?](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#How%20do%20I%20recover%20the%20actual%20type%20of%20the%20this%20object%20in%20a%20class%20hierarchy?)
One solution is to override the method in the child class and change the return type to a more specific one, ie. the child type. This requires casting. Instead of using the typical `(Child)` cast, use the [`Class#cast(Object)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#cast%28java.lang.Object%29) method ``` public class Parent { public Parent example() { System.out.println(this.getClass().getCanonicalName()); return this; } } public class Child extends Parent { public Child example() { return Child.class.cast(super.example()); } public Child method() { return this; } } ``` The cast is hidden within the standard method. From the source of `Class`. ``` public T cast(Object obj) { if (obj != null && !isInstance(obj)) throw new ClassCastException(cannotCastMsg(obj)); return (T) obj; } ```
18,383,773
I'm facing the problem described in [this question](https://stackoverflow.com/questions/4031857/way-to-make-java-parent-class-method-return-object-of-child-class) but would like to find a solution (if possible) without all the casts and @SuppressWarning annotations. A better solution would be one that builds upon the referenced one by: * removing @SuppressWarning * removing casts Solutions presented here will be graded with 2 points based on the criteria. Bounty goes to solution with most points or the "most elegant" one if there is more than one with 2 points.
2013/08/22
[ "https://Stackoverflow.com/questions/18383773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586682/" ]
No cast, no @SuppressWarning, few lines only: ```java public abstract class SuperClass<T extends SuperClass<T>> { protected T that; public T chain() { return that; } } public class SubClass1 extends SuperClass<SubClass1> { public SubClass1() { that = this; } } public class SubClass2 extends SuperClass<SubClass2> { public SubClass2() { that = this; } } ```
One solution is to override the method in the child class and change the return type to a more specific one, ie. the child type. This requires casting. Instead of using the typical `(Child)` cast, use the [`Class#cast(Object)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#cast%28java.lang.Object%29) method ``` public class Parent { public Parent example() { System.out.println(this.getClass().getCanonicalName()); return this; } } public class Child extends Parent { public Child example() { return Child.class.cast(super.example()); } public Child method() { return this; } } ``` The cast is hidden within the standard method. From the source of `Class`. ``` public T cast(Object obj) { if (obj != null && !isInstance(obj)) throw new ClassCastException(cannotCastMsg(obj)); return (T) obj; } ```
18,383,773
I'm facing the problem described in [this question](https://stackoverflow.com/questions/4031857/way-to-make-java-parent-class-method-return-object-of-child-class) but would like to find a solution (if possible) without all the casts and @SuppressWarning annotations. A better solution would be one that builds upon the referenced one by: * removing @SuppressWarning * removing casts Solutions presented here will be graded with 2 points based on the criteria. Bounty goes to solution with most points or the "most elegant" one if there is more than one with 2 points.
2013/08/22
[ "https://Stackoverflow.com/questions/18383773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/586682/" ]
No cast, no @SuppressWarning, few lines only: ```java public abstract class SuperClass<T extends SuperClass<T>> { protected T that; public T chain() { return that; } } public class SubClass1 extends SuperClass<SubClass1> { public SubClass1() { that = this; } } public class SubClass2 extends SuperClass<SubClass2> { public SubClass2() { that = this; } } ```
One approach is to define an abstract method `getThis()` in `Parent` class, and make all the `Child` classes override it, returning the `this` reference. This is a way to recover the type of `this` object in a class hierarchy. The code would look like this: ``` abstract class Parent<T extends Parent<T>> { protected abstract T getThis(); public T example() { System.out.println(this.getClass().getCanonicalName()); return getThis(); } } class ChildA extends Parent<ChildA> { @Override protected ChildA getThis() { return this; } public ChildA childAMethod() { System.out.println(this.getClass().getCanonicalName()); return this; } } class ChildB extends Parent<ChildB> { @Override protected ChildB getThis() { return this; } public ChildB childBMethod() { return this; } } public class Main { public static void main(String[] args) throws NoSuchMethodException { ChildA childA = new ChildA(); ChildB childB = new ChildB(); childA.example().childAMethod().example(); childB.example().childBMethod().example(); } } ``` As per requirement, there is no *Casting* and no *@SuppressWarnings*. I learnt this trick few days back from [Angelika Langer - Java Generics FAQs](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html). **Reference:** * [How do I recover the actual type of the this object in a class hierarchy?](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#How%20do%20I%20recover%20the%20actual%20type%20of%20the%20this%20object%20in%20a%20class%20hierarchy?)
45,993,468
I'm using angular 4 and I try to get data from 2 endpoints but I have a problem understanding rxjs. with this code I can only get list of students and users only. ``` getStudent() { return this.http.get(this.url + this.student_url, this.getHeaders()).map(res => res.json()); } getUsers() { return this.http.get(this.url + this.users_url, this.getHeaders()).map(res => res.json()); } ``` Let's say this is data : Student ``` [{"ID" : 1 , "SchoolCode": "A150", "UserID": 1 }, {"ID" : 5 , "SchoolCode": "A140" , "UserID": 3}, {"ID" : 9 , "SchoolCode": "C140" , "UserID": 4}] ``` User ``` [{"ID" : 1 ,"Name": "Rick" , "FamilyName" , "Grimes" }, {"ID" : 4 ,"Name": "Carle" , "FamilyName" , "Grimes" }] ``` I want to get first all students then compare UserID if it's the same as user then I combine both objects into one until I get an array like this : ``` {"ID" : 1 , "SchoolCode": "A150","Name": "Rick" , "FamilyName" , "Grimes" } ``` I think I should use flatmap but I did try write code but it dosen't work for me and I didn't find an example with such logic. Could you please help me.
2017/09/01
[ "https://Stackoverflow.com/questions/45993468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8525484/" ]
You can use the `switchMap` operator (alias of `flatMap`) in the following code : ``` // Observables mocking the data returned by http.get() const studentObs = Rx.Observable.from([ {"ID" : 1 , "SchoolCode": "A150", "UserID": 1 }, {"ID" : 5 , "SchoolCode": "A140" , "UserID": 4}, {"ID" : 9 , "SchoolCode": "C140" , "UserID": 3} ]); const userObs = Rx.Observable.from([ {"ID" : 1, "Name": "Rick" , "FamilyName": "Grimes" }, {"ID" : 3, "Name": "Tom" , "FamilyName": "Cruise" }, {"ID" : 4, "Name": "Amy" , "FamilyName": "Poehler" } ]); // Return an observable emitting only the given user. function getUser(userID) { return userObs.filter(user => user.ID === userID); } studentObs .switchMap(student => { return getUser(student.UserID).map(user => { // Merge the student and the user. return Object.assign(student, {user: user}); }) }) .subscribe(val => console.log(val)); ``` Check out this JSBin: <http://jsbin.com/batuzaq/edit?js,console>
You could try the following: ``` import { forkJoin } from 'rxjs/observable/forkJoin'; interface Student { id: number; schoolCode: string; userId: number; } interface User { id: number; name: string; familyName: string; } interface Merged { id: number; schoolCode: string; name: string; familyName: string; } getStudents(): Observable<Student[]> { // Implementation } getUsers(): Observable<User[]> { // Implementation } getMerged(): Observable<Merged[]> { const student$ = this.getStudents(); const users$ = this.getUsers(); const merged$ = forkJoin(student$, users$) .map(src => src[0].reduce((acc, current) => { // acc is the accumulated result (list with mapped objects) // current is an element of the students list const user = src[1].find(u => u.id === current.userId); // check if there is a user associated to the current student element if (user) { // if there is a matching user, push new element to result list acc.push({ id: user.id, name: user.name, familyName: user.familyName, schoolCode: current.schoolCode }); } return acc; // this could be changed to use a more immutable based approach }, new Array<Merged>())); // the seed value to start accumulating results is an empty list return merged$; } ```
23,130,785
I have a query as follows ``` SELECT s.`uid` FROM `sessions` s ``` (this was an extended query with a LEFT JOIN but to debug i removed that join) FYI the full query was ``` SELECT s.`uid`, u.`username`, u.`email` FROM `sessions` s LEFT JOIN `users` u ON s.`uid`=u.`user_id` ``` There are three results in the sessions table, for ease sake i'll just list the uid ``` | UID | | 0 | | 0 | | 1 | ``` when i execute the above query, i would expect to receive all 3 rows. In phpMyAdmin, i do. in PHP, i do not, i only receive the rows with 0 as the UID. However, in php. the $result->num\_rows is 2, not 3. This is my php code: ``` $sql = "SELECT s.`uid` FROM `sessions` s"; $result = $acpDB->query($sql); $staffList = array(); if ($result->num_rows > 0) { while ($data = $result->fetch_assoc()) { var_dump($data); $staffList[] = array( 'username' => $data['username'], 'email' => $data['email'], ); } } ``` I've tried plain ->query($sql), and also the prepare/execute method, neither seem to work. The only conflict i can think of, is that i already pull that row from my session class, but how can i just get it to return all rows, even rows that have already been pulled from that table in another class? Any help would be greatly appreciated Dan
2014/04/17
[ "https://Stackoverflow.com/questions/23130785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/780128/" ]
You can add a meta tag to your page header to prevent mobile safari turning telephone numbers into links ``` <meta name="format-detection" content="telephone=no"> ```
I believe you can use [`dataDetectorTypes`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/Reference/Reference.html#//apple_ref/occ/instp/UIWebView/dataDetectorTypes) to tell the web view what links to ignore. ``` webview.dataDetectorType = UIDataDetectorTypeNone; ``` See the [docs](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKitDataTypesReference/Reference/reference.html#//apple_ref/doc/c_ref/UIDataDetectorTypes) for all the types.
23,130,785
I have a query as follows ``` SELECT s.`uid` FROM `sessions` s ``` (this was an extended query with a LEFT JOIN but to debug i removed that join) FYI the full query was ``` SELECT s.`uid`, u.`username`, u.`email` FROM `sessions` s LEFT JOIN `users` u ON s.`uid`=u.`user_id` ``` There are three results in the sessions table, for ease sake i'll just list the uid ``` | UID | | 0 | | 0 | | 1 | ``` when i execute the above query, i would expect to receive all 3 rows. In phpMyAdmin, i do. in PHP, i do not, i only receive the rows with 0 as the UID. However, in php. the $result->num\_rows is 2, not 3. This is my php code: ``` $sql = "SELECT s.`uid` FROM `sessions` s"; $result = $acpDB->query($sql); $staffList = array(); if ($result->num_rows > 0) { while ($data = $result->fetch_assoc()) { var_dump($data); $staffList[] = array( 'username' => $data['username'], 'email' => $data['email'], ); } } ``` I've tried plain ->query($sql), and also the prepare/execute method, neither seem to work. The only conflict i can think of, is that i already pull that row from my session class, but how can i just get it to return all rows, even rows that have already been pulled from that table in another class? Any help would be greatly appreciated Dan
2014/04/17
[ "https://Stackoverflow.com/questions/23130785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/780128/" ]
You can add a meta tag to your page header to prevent mobile safari turning telephone numbers into links ``` <meta name="format-detection" content="telephone=no"> ```
You can put the text-decoration:none in that class also.
23,130,785
I have a query as follows ``` SELECT s.`uid` FROM `sessions` s ``` (this was an extended query with a LEFT JOIN but to debug i removed that join) FYI the full query was ``` SELECT s.`uid`, u.`username`, u.`email` FROM `sessions` s LEFT JOIN `users` u ON s.`uid`=u.`user_id` ``` There are three results in the sessions table, for ease sake i'll just list the uid ``` | UID | | 0 | | 0 | | 1 | ``` when i execute the above query, i would expect to receive all 3 rows. In phpMyAdmin, i do. in PHP, i do not, i only receive the rows with 0 as the UID. However, in php. the $result->num\_rows is 2, not 3. This is my php code: ``` $sql = "SELECT s.`uid` FROM `sessions` s"; $result = $acpDB->query($sql); $staffList = array(); if ($result->num_rows > 0) { while ($data = $result->fetch_assoc()) { var_dump($data); $staffList[] = array( 'username' => $data['username'], 'email' => $data['email'], ); } } ``` I've tried plain ->query($sql), and also the prepare/execute method, neither seem to work. The only conflict i can think of, is that i already pull that row from my session class, but how can i just get it to return all rows, even rows that have already been pulled from that table in another class? Any help would be greatly appreciated Dan
2014/04/17
[ "https://Stackoverflow.com/questions/23130785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/780128/" ]
You can add a meta tag to your page header to prevent mobile safari turning telephone numbers into links ``` <meta name="format-detection" content="telephone=no"> ```
Remove text decorations. ``` <span text-decorations="none" class="order1-button">999-120-9191</span> ```
23,130,785
I have a query as follows ``` SELECT s.`uid` FROM `sessions` s ``` (this was an extended query with a LEFT JOIN but to debug i removed that join) FYI the full query was ``` SELECT s.`uid`, u.`username`, u.`email` FROM `sessions` s LEFT JOIN `users` u ON s.`uid`=u.`user_id` ``` There are three results in the sessions table, for ease sake i'll just list the uid ``` | UID | | 0 | | 0 | | 1 | ``` when i execute the above query, i would expect to receive all 3 rows. In phpMyAdmin, i do. in PHP, i do not, i only receive the rows with 0 as the UID. However, in php. the $result->num\_rows is 2, not 3. This is my php code: ``` $sql = "SELECT s.`uid` FROM `sessions` s"; $result = $acpDB->query($sql); $staffList = array(); if ($result->num_rows > 0) { while ($data = $result->fetch_assoc()) { var_dump($data); $staffList[] = array( 'username' => $data['username'], 'email' => $data['email'], ); } } ``` I've tried plain ->query($sql), and also the prepare/execute method, neither seem to work. The only conflict i can think of, is that i already pull that row from my session class, but how can i just get it to return all rows, even rows that have already been pulled from that table in another class? Any help would be greatly appreciated Dan
2014/04/17
[ "https://Stackoverflow.com/questions/23130785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/780128/" ]
I believe you can use [`dataDetectorTypes`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/Reference/Reference.html#//apple_ref/occ/instp/UIWebView/dataDetectorTypes) to tell the web view what links to ignore. ``` webview.dataDetectorType = UIDataDetectorTypeNone; ``` See the [docs](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKitDataTypesReference/Reference/reference.html#//apple_ref/doc/c_ref/UIDataDetectorTypes) for all the types.
Remove text decorations. ``` <span text-decorations="none" class="order1-button">999-120-9191</span> ```
23,130,785
I have a query as follows ``` SELECT s.`uid` FROM `sessions` s ``` (this was an extended query with a LEFT JOIN but to debug i removed that join) FYI the full query was ``` SELECT s.`uid`, u.`username`, u.`email` FROM `sessions` s LEFT JOIN `users` u ON s.`uid`=u.`user_id` ``` There are three results in the sessions table, for ease sake i'll just list the uid ``` | UID | | 0 | | 0 | | 1 | ``` when i execute the above query, i would expect to receive all 3 rows. In phpMyAdmin, i do. in PHP, i do not, i only receive the rows with 0 as the UID. However, in php. the $result->num\_rows is 2, not 3. This is my php code: ``` $sql = "SELECT s.`uid` FROM `sessions` s"; $result = $acpDB->query($sql); $staffList = array(); if ($result->num_rows > 0) { while ($data = $result->fetch_assoc()) { var_dump($data); $staffList[] = array( 'username' => $data['username'], 'email' => $data['email'], ); } } ``` I've tried plain ->query($sql), and also the prepare/execute method, neither seem to work. The only conflict i can think of, is that i already pull that row from my session class, but how can i just get it to return all rows, even rows that have already been pulled from that table in another class? Any help would be greatly appreciated Dan
2014/04/17
[ "https://Stackoverflow.com/questions/23130785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/780128/" ]
You can put the text-decoration:none in that class also.
Remove text decorations. ``` <span text-decorations="none" class="order1-button">999-120-9191</span> ```
10,701,493
I need to get div id and its child class name by using div name . But div Id will be different and unique all the time. **HTML** ``` <div class="diagram" id="12" > <div class="121"> ... </div> </div> <div class="diagram" id="133" > <div class="33"> ... </div> </div> <div class="diagram" id="199" > <div class="77"> ... </div> </div> So on.. ``` JQUERY ``` $(function(){ //i need to pass to values to the function in the following way o.circle("12","121"); o.circle("133","33"); o.circle("199","77"); //So on.. }); ``` Please help me out
2012/05/22
[ "https://Stackoverflow.com/questions/10701493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1383645/" ]
``` $('div.diagram').each(function() { // this.id -> get the id of parent i.e div.diagram // $('div:first', this) -> get the first child of diagram, here this refers to diagram // $('div:first', this).attr('class') -> get the class name of child div o.circle(this.id, $('div:first', this).attr('class')); }); ``` If you want to try this on any event, then try: example: ``` // I assumed a click event $('div.diagram').on('click', function() { o.circle(this.id, $('div:first', this).attr('class')); }); ```
You can use this.It is working fine for me. ``` $('div.diagram').on('event_name', function() { // use click, hover, change, focus at the place of event_name whatever you need o.circle(this.id, $('div:first', this).attr('class')); }); ```
19,588,606
I am using this code to search for a specific file pattern recursively in a given directory: ``` if (file.isDirectory()) { System.out.println("Searching directory ... " + file.getAbsoluteFile()); if (file.canRead()) { System.out.println("Can read..."); if (file.listFiles() == null) { System.out.println("yes it is null"); } for (File temp : file.listFiles()) { // Problemetic line if (temp.isDirectory()) { search(temp); } else { // code to find a file } } } ``` Above code outputs me like this (also I get exception): ``` Searching directory ... C:\swsetup\SP46840\Lang\zh-TW Can read... Searching directory ... C:\System Volume Information Can read... yes it is null ``` Exception is: ``` Exception in thread "main" java.lang.NullPointerException at Demo.search(Demo.java:61) at Demo.search(Demo.java:63) ``` In my code the line is pointing to : `(file.listFiles())`, because it is trying to get list of files from system directories like "System Volume Information". I assume because it's a system directory, so some problem maybe happening which I am not aware. My question is: * How to handle this scenario, so that even `NullPointerException` occurs my `foreach` loop continues? * Or better how to avoid exception in first place (like by checking if it is a system directory etc)? Can anyone please guide me in this? Note: This is happening in Windows XP (I have tested earlier in Windows 7 few months back but I assume issue was not occurring there)
2013/10/25
[ "https://Stackoverflow.com/questions/19588606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506071/" ]
Try this: ``` if (file.isDirectory()) { System.out.println("Searching directory ... " + file.getAbsoluteFile()); if (file.canRead()) { System.out.println("Can read..."); if (file.listFiles() == null) { System.out.println("yes it is null"); } else { /* add the else */ for (File temp : file.listFiles()) { // Problemetic line if (temp.isDirectory()) { search(temp); } else { // code to find a file } } } } ```
from javaDoc: > > > ``` > An array of abstract pathnames denoting the files and > directories in the directory denoted by this abstract > pathname. The array will be empty if the directory is > empty. Returns <code>null</code> if this abstract pathname > does not denote a directory, or if an I/O error occurs. > > ``` > > So it's good idea to check null and use approach from Narendra Pathai's anwser
19,588,606
I am using this code to search for a specific file pattern recursively in a given directory: ``` if (file.isDirectory()) { System.out.println("Searching directory ... " + file.getAbsoluteFile()); if (file.canRead()) { System.out.println("Can read..."); if (file.listFiles() == null) { System.out.println("yes it is null"); } for (File temp : file.listFiles()) { // Problemetic line if (temp.isDirectory()) { search(temp); } else { // code to find a file } } } ``` Above code outputs me like this (also I get exception): ``` Searching directory ... C:\swsetup\SP46840\Lang\zh-TW Can read... Searching directory ... C:\System Volume Information Can read... yes it is null ``` Exception is: ``` Exception in thread "main" java.lang.NullPointerException at Demo.search(Demo.java:61) at Demo.search(Demo.java:63) ``` In my code the line is pointing to : `(file.listFiles())`, because it is trying to get list of files from system directories like "System Volume Information". I assume because it's a system directory, so some problem maybe happening which I am not aware. My question is: * How to handle this scenario, so that even `NullPointerException` occurs my `foreach` loop continues? * Or better how to avoid exception in first place (like by checking if it is a system directory etc)? Can anyone please guide me in this? Note: This is happening in Windows XP (I have tested earlier in Windows 7 few months back but I assume issue was not occurring there)
2013/10/25
[ "https://Stackoverflow.com/questions/19588606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506071/" ]
``` if (file.listFiles() == null) { System.out.println("yes it is null"); continue; } ``` When you find that the directory does not contain any files then just `continue` to the start of loop and check other directory. So using this when your logic finds that any directory does not contain any files you would skip all the processing(foreach loop) after this check, and you will avoid the `NullPointerException` and successfully skip the present directory. A standard approach for testing of preconditions in a loop ---------------------------------------------------------- ``` foreach(.....){ //check for preconditions continue; // if preconditions are not met //do processing } ```
from javaDoc: > > > ``` > An array of abstract pathnames denoting the files and > directories in the directory denoted by this abstract > pathname. The array will be empty if the directory is > empty. Returns <code>null</code> if this abstract pathname > does not denote a directory, or if an I/O error occurs. > > ``` > > So it's good idea to check null and use approach from Narendra Pathai's anwser
45,433,817
I try to make server-side processing for [DataTables](https://datatables.net) using Web API. There are two actions in my Web API controller with same list of parameters: ``` public class CampaignController : ApiController { // GET request handler public dtResponse Get(int draw, int start, int length) { // request handling } // POST request handler public void Post(int draw, int start, int length) { // request handling } } ``` If I use GET method to send AJAX request to the server, the `Get` action is activated. However, if I use POST method, then neither action are activated. I tried to change POST handler signature to ``` public void Post([FromBody]object value) { // request handling } ``` In this case the `value` is `null`. Note, the `HttpContext.Current.Request.Form` collection isn't empty. The `draw`, `start`, `length` variables are exist in this collection. Thus, I think the trouble is in model binding, but I cannot fix it. Help me, please.
2017/08/01
[ "https://Stackoverflow.com/questions/45433817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7914637/" ]
The only workaround is to get the keycode and cast it to String: ``` var str = ''; var el = document.getElementById('#test'); document.addEventListener('keypress', function(event) { const currentCode = event.which || event.code; let currentKey = event.key; if (!currentKey) { currentKey = String.fromCharCode(currentCode); } str += currentKey; event.preventDefault(); el.innerHTML = str; }) ```
Since there is no character representation for control characters like up, down, left or right, you need to hardcode the character implementation in the code itself. I used **Window.event.KeyCode** event from **document.onkeydown** event listener and it works. Here is my solution: ``` window.onload = function() { try { var el = document.getElementById("#test"); var str = ''; document.onkeydown = function() { var currentKey = window.event.keyCode; switch (currentKey) { case 40: str = "down"; break; case 37: str = "left"; break; case 39: str = "right"; break; case 38: str = "up"; break; } event.preventDefault; e1.innerHTML = str; }; } catch (e) { alert(e.message); } } ```
177,528
I downloaded and enabled translations for my Drupal core and modules using these Drush commands: ``` drush dl l10n_update && drush en -y $_ drush language-add lt && drush language-enable $_ drush l10n-update-refresh drush l10n-update ``` I got almost everything translated, and in "Administration » Configuration » Regional and language" I see that I have almost 60% of translations to Lithuanian. However, not everything is translated. For example, harmony forum module thread reply; [![http://prntscr.com/8rd9aw](https://i.stack.imgur.com/Z15GP.png)](https://i.stack.imgur.com/Z15GP.png) ``` <ul class="post-links links--inline"><li class="show_replies first"><a href="/forumas/" id="post-1-show-replies" class="post-show-replies ajax-processed" data-thread-id="1" data-post-id="1">2 replies</a></li> <li class="reply"><a href="/forumas/post/add?field_harmony_thread=1&amp;field_harmony_post_is_reply_to=1" id="post-1-reply" title="Reply directly to this post" class="reply-link" data-thread-id="1" data-post-id="1">Atsakyti</a></li> <li class="reply_as_new_thread"><a href="/forumas/thread/add?field_harmony_thread_cont_from=1" id="post-1-reply-as-new" title="Create a new thread as a reply to this post" class="reply-link" data-thread-id="1" data-post-id="1">Reply as a new thread</a></li> <li class="flag-harmony_likes last"><span><span class="flag-wrapper flag-harmony-likes flag-harmony-likes-1"> <a href="/forumas/flag/flag/harmony_likes/1?destination=thread/1&amp;token=zOnI9qp9K92XqmzqfCM8P-0n7f_FEMQKzumwX_A4xb4" title="" class="flag flag-action flag-link-toggle flag-processed" rel="nofollow"><span class="count">(0)</span> <span class="text">Like</span></a><span class="flag-throbber">&nbsp;</span> </span> </span></li> </ul> ``` and user profile statistics [![enter image description here](https://i.stack.imgur.com/t6ear.png)](https://i.stack.imgur.com/t6ear.png) ``` <div class="field field--name-field-harmony-thread-count field--type-number-integer field--label-above"> <div class="field__label">Thread count: </div> <div class="field__items"> </div> <div class="field field--name-field-harmony-post-count field--type-number-integer field--label-above"> <div class="field__label">Post count: </div> <div class="field__items"> </div> ``` How can I edit these strings to be translated?
2015/10/14
[ "https://drupal.stackexchange.com/questions/177528", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/50624/" ]
Here is a custom function I use in update hooks, to translate some missing translations, just in case you want to do this programmatically: ```php function translateString($source_string, $translated_string, $langcode) { $storage = \Drupal::service('locale.storage'); $string = $storage->findString(array('source' => $source_string)); if (is_null($string)) { $string = new SourceString(); $string->setString($source_string); $string->setStorage($storage); $string->save(); } // If exists, replace $translation = $storage->createTranslation(array( 'lid' => $string->lid, 'language' => $langcode, 'translation' => $translated_string, ))->save(); } ``` To implement it you can do the following (i.e. in a update hook): ```php function my_module_update_8000() { translateString( 'The original String', 'My translated String to german thats why the next parameter is "de"', 'de' ); } ```
Identify what template it is using with [Themer](https://www.drupal.org/project/devel_themer). Override it and use t() function to wrap those strings needed to be translated.
177,528
I downloaded and enabled translations for my Drupal core and modules using these Drush commands: ``` drush dl l10n_update && drush en -y $_ drush language-add lt && drush language-enable $_ drush l10n-update-refresh drush l10n-update ``` I got almost everything translated, and in "Administration » Configuration » Regional and language" I see that I have almost 60% of translations to Lithuanian. However, not everything is translated. For example, harmony forum module thread reply; [![http://prntscr.com/8rd9aw](https://i.stack.imgur.com/Z15GP.png)](https://i.stack.imgur.com/Z15GP.png) ``` <ul class="post-links links--inline"><li class="show_replies first"><a href="/forumas/" id="post-1-show-replies" class="post-show-replies ajax-processed" data-thread-id="1" data-post-id="1">2 replies</a></li> <li class="reply"><a href="/forumas/post/add?field_harmony_thread=1&amp;field_harmony_post_is_reply_to=1" id="post-1-reply" title="Reply directly to this post" class="reply-link" data-thread-id="1" data-post-id="1">Atsakyti</a></li> <li class="reply_as_new_thread"><a href="/forumas/thread/add?field_harmony_thread_cont_from=1" id="post-1-reply-as-new" title="Create a new thread as a reply to this post" class="reply-link" data-thread-id="1" data-post-id="1">Reply as a new thread</a></li> <li class="flag-harmony_likes last"><span><span class="flag-wrapper flag-harmony-likes flag-harmony-likes-1"> <a href="/forumas/flag/flag/harmony_likes/1?destination=thread/1&amp;token=zOnI9qp9K92XqmzqfCM8P-0n7f_FEMQKzumwX_A4xb4" title="" class="flag flag-action flag-link-toggle flag-processed" rel="nofollow"><span class="count">(0)</span> <span class="text">Like</span></a><span class="flag-throbber">&nbsp;</span> </span> </span></li> </ul> ``` and user profile statistics [![enter image description here](https://i.stack.imgur.com/t6ear.png)](https://i.stack.imgur.com/t6ear.png) ``` <div class="field field--name-field-harmony-thread-count field--type-number-integer field--label-above"> <div class="field__label">Thread count: </div> <div class="field__items"> </div> <div class="field field--name-field-harmony-post-count field--type-number-integer field--label-above"> <div class="field__label">Post count: </div> <div class="field__items"> </div> ``` How can I edit these strings to be translated?
2015/10/14
[ "https://drupal.stackexchange.com/questions/177528", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/50624/" ]
Here is a custom function I use in update hooks, to translate some missing translations, just in case you want to do this programmatically: ```php function translateString($source_string, $translated_string, $langcode) { $storage = \Drupal::service('locale.storage'); $string = $storage->findString(array('source' => $source_string)); if (is_null($string)) { $string = new SourceString(); $string->setString($source_string); $string->setStorage($storage); $string->save(); } // If exists, replace $translation = $storage->createTranslation(array( 'lid' => $string->lid, 'language' => $langcode, 'translation' => $translated_string, ))->save(); } ``` To implement it you can do the following (i.e. in a update hook): ```php function my_module_update_8000() { translateString( 'The original String', 'My translated String to german thats why the next parameter is "de"', 'de' ); } ```
My solution: I tried Devel Themer module as suggested, but I was not able to find function source to copy and change it for my needs. After unsuccessfull tries to add my translations via template.php and by creating custom tpl.php in templates folder of my theme, I decided to use this method: > > *! Before proceeding make sure that you have your non-english language downloaded and enabled as default in "Administration » Configuration » > Regional and language » List"* > > > --- 1. Download and enable: ======================= * <https://www.drupal.org/project/potx> * <https://www.drupal.org/project/i18n> * Locale * Block translation * Entity translation * Field translation * Views translation * String translation 2. In ----- *Administration » Configuration » Regional and language » Multilingual settings » Strings* choose "English" as source language. 3. In ----- *Administration » Configuration » Regional and language » Translate interface » Translate* search for your string, which you want to translate and limit search to Views, Fields or Blocks. 4. Translate ------------ all occurrences of your untranslated strings. 5. Go to -------- *Administration » Configuration » Regional and language » Translate interface » Strings* , choose all text groups and click "Refresh strings" to clean up translations, which can overlap. --- That's it! > > P.S. You can also use *Administration » Configuration » Regional and > language » Translate interface » Extract* to choose any module or > theme, extract untranslated strings to .po file and then Import that > file back when translated. This potx module scans for strings wrapped > with t() function. > > >
5,914,978
I am currently in the planning stages for a fairly comprehensive rewrite of one of our core (commercial) software offerings, and I am looking for a bit of advice. Our current software is a business management package written in Winforms (originally in .NET 2.0, but has transitioned into 4.0 so far) that communicates directly with a SQL Server backend. There is also a very simple ASP.NET Webforms website that provides some basic functionality for users on the road. Each of our customers has to expose this site (and a couple of existing ASMX web services) to the world in order to make use of it, and we're beginning to outgrow this setup. As we rewrite this package, we have decided that it would be best if we made the package more accessible from the outside, as well as providing our customers with the option of allowing us to host their data (we haven't decided on a provider) rather than requiring them to host SQL Server, SQL Server Reporting Services, and IIS on the premises. Right now, our plan is to rewrite the existing Winforms application using WPF, as well as provide a much richer client experience over the web. Going forward, however, our customers have expressed an interest in using tablets, so we're going to need to support iOS and Android native applications as clients, as well. The combination of our desire to offer off-site hosting (without having to use a VPN architecture) and support clients on platforms that are outside of the .NET ecosystem has led us to the conclusion that all of our client-server communication should take place through our own service rather than using the SQL Server client (since we don't want to expose that to the world and SQL Server drivers do not exist, to my knowledge, for some of those platforms). Right now, our options as I see them are: * Write a completely custom service that uses TCP sockets and write everything (authentication, session management, serialization, etc.) from scratch. This is what I know the most *about*, but my assumption is that there's something better. * Use a WCF service for transport, and either take care of authentication and/or session management myself, or use something like durable services for session management My basic question is this: ### What would be the most appropriate choice of overall architecture, as well as specific features like ASP.NET authentication or Durable Services, to provide a stateful, persistent service to WPF, ASP.NET, iOS, and Android clients?
2011/05/06
[ "https://Stackoverflow.com/questions/5914978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82187/" ]
*(I am working on the assumption that by "stateful" you mean session-based).* I guess one big question is: Do you want to use SOAP in your messaging stack? You may be loathe to, as often there is no out-of-box support for SOAP on mobile platforms (see: [How to call a web service with Android](https://stackoverflow.com/questions/297586/how-to-call-web-service-with-android)). No doubt its similarly painful with iOS. Calling SOAP from a browser ("ASP.NET") can't be fun. I'm not even sure its possible! Unfortunately if you aren't using SOAP, then that quickly rules out most of WCFs standard Bindings. Of the one that remains, "[Web HTTP](http://msdn.microsoft.com/en-us/library/bb412169.aspx)", sessions are not supported because obviously HTTP is a stateless protocol. You can actually add session support by hand using a solution [based on Cookies](http://msdn.microsoft.com/en-us/library/bb412169.aspx). You could use the TCP transport (it supports sessions), and build you own channel stack to support a non-SOAP encoding (for example [protocol-buffers](http://code.google.com/p/protobuf-net/)), but even then you need to be careful because the TCP transport places special 'framing' bytes in it, so that would make interop non-trivial. What sort of state do you need to store in your sessions? Maybe there are alternative approaches?
1) consider stateful utility services using singletons, but keep the request/response pattern at the facade level stateless. 2) consider distributed caching, perhaps Windows Server AppFabric Cache.
14,530,617
I am new to CSS/HTML and I am having some trouble adjusting the width of my page. I'm sure the solution is very simple and obvious lol. On this page: <http://www.bodylogicmd.com/appetites-and-aphrodisiacs> - I am trying to set the width to 100% so that the content spans the entire width of the page. The problem I am running into is that when I try to add inline CSS, the external stylesheet called in the head is superseding the inline. I am using Joomla, so the editor let's edit the body, not the head (unless I create a custom module that rewrites code for the head). I do not want to re-write/edit the external (main) stylesheet, since I am using this page for a contest and it is only running for about 1 month. Anyone have any ideas how I can achieve this using inline CSSS and what the code would be? Any help is greatly appreciated!!
2013/01/25
[ "https://Stackoverflow.com/questions/14530617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012426/" ]
``` #main, #content, .landing-wrapper, #column2 .box2 {width: auto;} #column2 {width: auto; float: none;} ``` You should be able to place this in the head of your template's index.php, though I would personally add it to the bottom of the theme's main stylesheet. How long it's there isn't a factor.
you need to find the #main selector and set it wider there. The body is always going to be 100% wide unless you explicitly set it otherwise. In your case the #main container is the wrapper around the whole page, this is what you want to set. I'd also recommend looking up the "box model" and understanding how that works before going too much further. It will save you much weeping and gnashing of teeth. <http://www.w3schools.com/css/css_boxmodel.asp>
14,530,617
I am new to CSS/HTML and I am having some trouble adjusting the width of my page. I'm sure the solution is very simple and obvious lol. On this page: <http://www.bodylogicmd.com/appetites-and-aphrodisiacs> - I am trying to set the width to 100% so that the content spans the entire width of the page. The problem I am running into is that when I try to add inline CSS, the external stylesheet called in the head is superseding the inline. I am using Joomla, so the editor let's edit the body, not the head (unless I create a custom module that rewrites code for the head). I do not want to re-write/edit the external (main) stylesheet, since I am using this page for a contest and it is only running for about 1 month. Anyone have any ideas how I can achieve this using inline CSSS and what the code would be? Any help is greatly appreciated!!
2013/01/25
[ "https://Stackoverflow.com/questions/14530617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012426/" ]
``` #main, #content, .landing-wrapper, #column2 .box2 {width: auto;} #column2 {width: auto; float: none;} ``` You should be able to place this in the head of your template's index.php, though I would personally add it to the bottom of the theme's main stylesheet. How long it's there isn't a factor.
try adding inline .css {width: 100%; (or auto)} to : - #main - #content - .landing-wrapper - #column2 .box2
36,096,204
How do I create a Custom Hook Method in a Subclass? No need to duplicate Rails, of course -- the simpler, the better. My goal is to convert: ``` class SubClass def do_this_method first_validate_something end def do_that_method first_validate_something end private def first_validate_something; end end ``` To: ``` class ActiveClass; end class SubClass < ActiveClass before_operations :first_validate_something, :do_this_method, :do_that_method def do_this_method; end def do_that_method; end private def first_validate_something; end end ``` Example in Module: <https://github.com/PragTob/after_do/blob/master/lib/after_do.rb> Rails #before\_action: <http://apidock.com/rails/v4.0.2/AbstractController/Callbacks/ClassMethods/before_action>
2016/03/19
[ "https://Stackoverflow.com/questions/36096204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5298869/" ]
Here's a solution that uses `prepend`. When you call `before_operations` for the first time it creates a new (empty) module and prepends it to your class. This means that when you call method `foo` on your class, it will look first for that method in the module. The `before_operations` method then defines simple methods in this module that first invoke your 'before' method, and then use `super` to invoke the real implementation in your class. ```ruby class ActiveClass def self.before_operations(before_method,*methods) prepend( @active_wrapper=Module.new ) unless @active_wrapper methods.each do |method_name| @active_wrapper.send(:define_method,method_name) do |*args,&block| send before_method super(*args,&block) end end end end class SubClass < ActiveClass before_operations :first_validate_something, :do_this_method, :do_that_method def do_this_method(*args,&block) p doing:'this', with:args, and:block end def do_that_method; end private def first_validate_something p :validating end end SubClass.new.do_this_method(3,4){ |x| p x } #=> :validating #=> {:doing=>"this", :with=>[3, 4], :and=>#<Proc:0x007fdb1301fa18@/tmp.rb:31>} ``` --- If you want to make the idea by @SteveTurczyn work you must: 1. receive the args params in the block of `define_method`, not as arguments to it. 2. call `before_operations` AFTER your methods have been defined if you want to be able to alias them. ```ruby class ActiveClass def self.before_operations(before_method, *methods) methods.each do |meth| raise "No method `#{meth}` defined in #{self}" unless method_defined?(meth) orig_method = "_original_#{meth}" alias_method orig_method, meth define_method(meth) do |*args,&block| send before_method send orig_method, *args, &block end end end end class SubClass < ActiveClass def do_this_method(*args,&block) p doing:'this', with:args, and:block end def do_that_method; end before_operations :first_validate_something, :do_this_method, :do_that_method private def first_validate_something p :validating end end SubClass.new.do_this_method(3,4){ |x| p x } #=> :validating #=> {:doing=>"this", :with=>[3, 4], :and=>#<Proc:0x007fdb1301fa18@/tmp.rb:31>} ```
You can alias the original method to a different name (so `:do_this_something` becomes `:original_do_this_something`) and then define a new `:do_this_something` method that calls `:first_validate_something` and then the original version of the method Something like this... ``` class ActiveClass def self.before_operations(before_method, *methods) methods.each do |method| alias_method "original_#{method.to_s}".to_sym, method define_method(method, *args, &block) do send before_method send "original_#{method.to_s}", *args, &block end end end end ```
36,096,204
How do I create a Custom Hook Method in a Subclass? No need to duplicate Rails, of course -- the simpler, the better. My goal is to convert: ``` class SubClass def do_this_method first_validate_something end def do_that_method first_validate_something end private def first_validate_something; end end ``` To: ``` class ActiveClass; end class SubClass < ActiveClass before_operations :first_validate_something, :do_this_method, :do_that_method def do_this_method; end def do_that_method; end private def first_validate_something; end end ``` Example in Module: <https://github.com/PragTob/after_do/blob/master/lib/after_do.rb> Rails #before\_action: <http://apidock.com/rails/v4.0.2/AbstractController/Callbacks/ClassMethods/before_action>
2016/03/19
[ "https://Stackoverflow.com/questions/36096204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5298869/" ]
You can alias the original method to a different name (so `:do_this_something` becomes `:original_do_this_something`) and then define a new `:do_this_something` method that calls `:first_validate_something` and then the original version of the method Something like this... ``` class ActiveClass def self.before_operations(before_method, *methods) methods.each do |method| alias_method "original_#{method.to_s}".to_sym, method define_method(method, *args, &block) do send before_method send "original_#{method.to_s}", *args, &block end end end end ```
This is a way of writing the code that does not make use of aliases. It includes a class method `validate` that specifies the validator method and the methods that are to call the validator method. This method `validate` can be invoked multiple times to change the validator and validatees dynamically. ``` class ActiveClass end ``` Place all the methods other than the validators in a subclass of `ActiveClass` named (say) `MidClass`. ``` class MidClass < ActiveClass def do_this_method(v,a,b) puts "this: v=#{v}, a=#{a}, b=#{b}" end def do_that_method(v,a,b) puts "that: v=#{v}, a=#{a}, b=#{b}" end def yet_another_method(v,a,b) puts "yet_another: v=#{v}, a=#{a}, b=#{b}" end end MidClass.instance_methods(false) #=> [:do_this_method, :do_that_method, :yet_another_method] ``` Place the validators, together with a class method `validate`, in a subclass of `MidClass` named (say) `SubClass`. ``` class SubClass < MidClass def self.validate(validator, *validatees) superclass.instance_methods(false).each do |m| if validatees.include?(m) define_method(m) do |v, *args| send(validator, v) super(v, *args) end else define_method(m) do |v, *args| super(v, *args) end end end end private def validator1(v) puts "valid1, v=#{v}" end def validator2(v) puts "valid2, v=#{v}" end end SubClass.methods(false) #=> [:validate] SubClass.private_instance_methods(false) #=> [:validator1, :validator2] ``` The class method `validate` passes symbols for the validation method to use and the methods to be validated. Let's try it. ``` sc = SubClass.new SubClass.validate(:validator1, :do_this_method, :do_that_method) sc.do_this_method(1,2,3) # valid1, v=1 # this: v=1, a=2, b=3 sc.do_that_method(1,2,3) # valid1, v=1 # that: v=1, a=2, b=3 sc.yet_another_method(1,2,3) # yet_another: v=1, a=2, b=3 ``` Now change the validation. ``` SubClass.validate(:validator2, :do_that_method, :yet_another_method) sc.do_this_method(1,2,3) # this: v=1, a=2, b=3 sc.do_that_method(1,2,3) # valid2, v=1 # that: v=1, a=2, b=3 sc.yet_another_method(1,2,3) # valid2, v=1 # yet_another: v=1, a=2, b=3 ``` When `super` is called without arguments from a normal method, all arguments and a block, if there is one, are passed to super. If the method was created with `define_method`, however, no arguments (and no block) are passed to super. In the latter case the arguments must be explicit. I wanted to pass a block or proc on to `super` if there is one, but have been using the wrong secret sauce. I would welcome advice for doing that.
36,096,204
How do I create a Custom Hook Method in a Subclass? No need to duplicate Rails, of course -- the simpler, the better. My goal is to convert: ``` class SubClass def do_this_method first_validate_something end def do_that_method first_validate_something end private def first_validate_something; end end ``` To: ``` class ActiveClass; end class SubClass < ActiveClass before_operations :first_validate_something, :do_this_method, :do_that_method def do_this_method; end def do_that_method; end private def first_validate_something; end end ``` Example in Module: <https://github.com/PragTob/after_do/blob/master/lib/after_do.rb> Rails #before\_action: <http://apidock.com/rails/v4.0.2/AbstractController/Callbacks/ClassMethods/before_action>
2016/03/19
[ "https://Stackoverflow.com/questions/36096204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5298869/" ]
Here's a solution that uses `prepend`. When you call `before_operations` for the first time it creates a new (empty) module and prepends it to your class. This means that when you call method `foo` on your class, it will look first for that method in the module. The `before_operations` method then defines simple methods in this module that first invoke your 'before' method, and then use `super` to invoke the real implementation in your class. ```ruby class ActiveClass def self.before_operations(before_method,*methods) prepend( @active_wrapper=Module.new ) unless @active_wrapper methods.each do |method_name| @active_wrapper.send(:define_method,method_name) do |*args,&block| send before_method super(*args,&block) end end end end class SubClass < ActiveClass before_operations :first_validate_something, :do_this_method, :do_that_method def do_this_method(*args,&block) p doing:'this', with:args, and:block end def do_that_method; end private def first_validate_something p :validating end end SubClass.new.do_this_method(3,4){ |x| p x } #=> :validating #=> {:doing=>"this", :with=>[3, 4], :and=>#<Proc:0x007fdb1301fa18@/tmp.rb:31>} ``` --- If you want to make the idea by @SteveTurczyn work you must: 1. receive the args params in the block of `define_method`, not as arguments to it. 2. call `before_operations` AFTER your methods have been defined if you want to be able to alias them. ```ruby class ActiveClass def self.before_operations(before_method, *methods) methods.each do |meth| raise "No method `#{meth}` defined in #{self}" unless method_defined?(meth) orig_method = "_original_#{meth}" alias_method orig_method, meth define_method(meth) do |*args,&block| send before_method send orig_method, *args, &block end end end end class SubClass < ActiveClass def do_this_method(*args,&block) p doing:'this', with:args, and:block end def do_that_method; end before_operations :first_validate_something, :do_this_method, :do_that_method private def first_validate_something p :validating end end SubClass.new.do_this_method(3,4){ |x| p x } #=> :validating #=> {:doing=>"this", :with=>[3, 4], :and=>#<Proc:0x007fdb1301fa18@/tmp.rb:31>} ```
This is a way of writing the code that does not make use of aliases. It includes a class method `validate` that specifies the validator method and the methods that are to call the validator method. This method `validate` can be invoked multiple times to change the validator and validatees dynamically. ``` class ActiveClass end ``` Place all the methods other than the validators in a subclass of `ActiveClass` named (say) `MidClass`. ``` class MidClass < ActiveClass def do_this_method(v,a,b) puts "this: v=#{v}, a=#{a}, b=#{b}" end def do_that_method(v,a,b) puts "that: v=#{v}, a=#{a}, b=#{b}" end def yet_another_method(v,a,b) puts "yet_another: v=#{v}, a=#{a}, b=#{b}" end end MidClass.instance_methods(false) #=> [:do_this_method, :do_that_method, :yet_another_method] ``` Place the validators, together with a class method `validate`, in a subclass of `MidClass` named (say) `SubClass`. ``` class SubClass < MidClass def self.validate(validator, *validatees) superclass.instance_methods(false).each do |m| if validatees.include?(m) define_method(m) do |v, *args| send(validator, v) super(v, *args) end else define_method(m) do |v, *args| super(v, *args) end end end end private def validator1(v) puts "valid1, v=#{v}" end def validator2(v) puts "valid2, v=#{v}" end end SubClass.methods(false) #=> [:validate] SubClass.private_instance_methods(false) #=> [:validator1, :validator2] ``` The class method `validate` passes symbols for the validation method to use and the methods to be validated. Let's try it. ``` sc = SubClass.new SubClass.validate(:validator1, :do_this_method, :do_that_method) sc.do_this_method(1,2,3) # valid1, v=1 # this: v=1, a=2, b=3 sc.do_that_method(1,2,3) # valid1, v=1 # that: v=1, a=2, b=3 sc.yet_another_method(1,2,3) # yet_another: v=1, a=2, b=3 ``` Now change the validation. ``` SubClass.validate(:validator2, :do_that_method, :yet_another_method) sc.do_this_method(1,2,3) # this: v=1, a=2, b=3 sc.do_that_method(1,2,3) # valid2, v=1 # that: v=1, a=2, b=3 sc.yet_another_method(1,2,3) # valid2, v=1 # yet_another: v=1, a=2, b=3 ``` When `super` is called without arguments from a normal method, all arguments and a block, if there is one, are passed to super. If the method was created with `define_method`, however, no arguments (and no block) are passed to super. In the latter case the arguments must be explicit. I wanted to pass a block or proc on to `super` if there is one, but have been using the wrong secret sauce. I would welcome advice for doing that.
30,065,899
I know the logic/syntax of the code at the bottom of this post is off, but I'm having a hard time figuring out how I can write this to get the desired result. The first section creates this dictionary: ``` sco = {'human + big': 0, 'big + loud': 0, 'big + human': 0, 'human + loud': 0, 'loud + big': 0, 'loud + human': 0} ``` Then, my intention is to loop through each item in the dictionary "cnt" once for x and then loop through the dictionary a second time for x each time the item has the same value as (cnt[x][1]) but a different key (cnt[x][0]), creating a string that will match the format "%s + %s" found in the dictionary "sco." It should then find the key in sco that matches the key assigned to the variable dnt and increment the value for that key in sco by 1. ``` # -*- coding: utf-8 -*- import itertools sho = ('human', 'loud', 'big') sco = {} for a,b in itertools.permutations(sho, 2): sco["{0} + {1}".format(a,b)] = 0 cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')] for x in cnt: upd = cnt[x][0] who = cnt[x][1] for x in cnt: if cnt[x][0] != upd and cnt[x][1] == who: cpg = cnt[x][0] dnt = '%s + %s' % (upd, cpg) for i in sco: if sco[i][0] == dnt: sco[i][1] += sco[i][1] print sco ``` Currently, printing sco results in no change to any of the values. The desired outcome of the code is this: ``` {'human + big': 1, 'big + loud': 0, 'big + human': 1, 'human + loud': 2, 'loud + big': 0, 'loud + human': 2} ``` Any help is greatly appreciated! The revised code is this: ``` # -*- coding: utf-8 -*- import itertools sho = ('human', 'loud', 'big') sco = {} for a,b in itertools.permutations(sho, 2): sco["{0} + {1}".format(a,b)] = 0 cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')] for x in cnt: upd = cnt[0] who = cnt[1] for x in cnt: if cnt[0] != upd and cnt[1] == who: cpg = cnt[0] dnt = '%s + %s' % (upd, cpg) sco[dnt] += 1 print sco ``` The following code does what I intended. Thank you to @dermen & @abarnert: ``` # -*- coding: utf-8 -*- import itertools sho = ('human', 'loud', 'big') sco = {} for a,b in itertools.permutations(sho, 2): sco["{0} + {1}".format(a,b)] = 0 cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')] for x in cnt: upd = x[0] who = x[1] for x in cnt: if x[0] != upd and x[1] == who: cpg = x[0] dnt = '%s + %s' % (upd, cpg) sco[dnt] += 1 print sco ```
2015/05/06
[ "https://Stackoverflow.com/questions/30065899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652988/" ]
The actual problem is that, instead of adding 1 to the values, you're doubling them: ``` sco[i][1] += sco[i][1] ``` And no matter how many times you add 0 to 0, it's still 0. To add 1, just use `+= 1`. --- But you've got another problem, at least in the code you posted. Each `sco[i]` value just a number, not a list of two things, the second of which is a number. So what you really want is: ``` sco[i] += 1 ``` And similarly, the keys aren't `sco[i][0]`, they're just `i`. --- And you've got a third problem. This one doesn't actually *break* your code, it just makes it more complicated, harder to understand, and slower… but that's still worth fixing. The whole point of dictionaries is that you don't have to iterate them to search for a key, you just look up the key directly. So, instead of this: ``` for i in sco: if i == dnt: sco[i] += 1 ``` … just do this: ``` sco[dnt] += 1 ``` It's simpler, harder to get wrong, and more efficient, all at the same time. --- I can't promise there are no other errors in your code, but you definitely need to fix these three, on top of whatever else is wrong, and I'm pretty sure the first one is the one that happens to be causing the specific problem you asked about.
In addition to what @abarnert replied, Dictionaries behave like this: ``` >>> D1 = { 'thing1': [1,2,3 ], 'thing2': ( 1, 2,3), 'thing3':'123' } >>> D1['thing1'] #[1, 2, 3] >>> D1['thing2'] #(1, 2, 3) >>> D1['thing3'] #'123' >>> thing4 = 1 >>> D2 = { thing4:D1 } >>> D2[thing4] #{'thing1': [1, 2, 3], 'thing2': (1, 2, 3), 'thing3': '123'} ``` If you want to iterate over the keys of a dictionary, use ``` >>> D1.keys() #['thing2', 'thing3', 'thing1'] >>> D2.keys() #[1] ``` Finally, I would suggest making a template for your "key", such that ``` >>> template = "{0} + {1}" ``` Then you can replace the line ``` sco["{0} + {1}".format(a,b)] = 0 ``` with ``` sco[template.format(a,b)] = 0 ``` and similarly ``` dnt = '%s + %s' % (upd, cpg) ``` with ``` dnt = template.format(upd, cpg) ``` -that is safer practice in my opinion. Read more on dictionaries [here, see section 5.5.](https://docs.python.org/2/tutorial/datastructures.html)
30,065,899
I know the logic/syntax of the code at the bottom of this post is off, but I'm having a hard time figuring out how I can write this to get the desired result. The first section creates this dictionary: ``` sco = {'human + big': 0, 'big + loud': 0, 'big + human': 0, 'human + loud': 0, 'loud + big': 0, 'loud + human': 0} ``` Then, my intention is to loop through each item in the dictionary "cnt" once for x and then loop through the dictionary a second time for x each time the item has the same value as (cnt[x][1]) but a different key (cnt[x][0]), creating a string that will match the format "%s + %s" found in the dictionary "sco." It should then find the key in sco that matches the key assigned to the variable dnt and increment the value for that key in sco by 1. ``` # -*- coding: utf-8 -*- import itertools sho = ('human', 'loud', 'big') sco = {} for a,b in itertools.permutations(sho, 2): sco["{0} + {1}".format(a,b)] = 0 cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')] for x in cnt: upd = cnt[x][0] who = cnt[x][1] for x in cnt: if cnt[x][0] != upd and cnt[x][1] == who: cpg = cnt[x][0] dnt = '%s + %s' % (upd, cpg) for i in sco: if sco[i][0] == dnt: sco[i][1] += sco[i][1] print sco ``` Currently, printing sco results in no change to any of the values. The desired outcome of the code is this: ``` {'human + big': 1, 'big + loud': 0, 'big + human': 1, 'human + loud': 2, 'loud + big': 0, 'loud + human': 2} ``` Any help is greatly appreciated! The revised code is this: ``` # -*- coding: utf-8 -*- import itertools sho = ('human', 'loud', 'big') sco = {} for a,b in itertools.permutations(sho, 2): sco["{0} + {1}".format(a,b)] = 0 cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')] for x in cnt: upd = cnt[0] who = cnt[1] for x in cnt: if cnt[0] != upd and cnt[1] == who: cpg = cnt[0] dnt = '%s + %s' % (upd, cpg) sco[dnt] += 1 print sco ``` The following code does what I intended. Thank you to @dermen & @abarnert: ``` # -*- coding: utf-8 -*- import itertools sho = ('human', 'loud', 'big') sco = {} for a,b in itertools.permutations(sho, 2): sco["{0} + {1}".format(a,b)] = 0 cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')] for x in cnt: upd = x[0] who = x[1] for x in cnt: if x[0] != upd and x[1] == who: cpg = x[0] dnt = '%s + %s' % (upd, cpg) sco[dnt] += 1 print sco ```
2015/05/06
[ "https://Stackoverflow.com/questions/30065899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652988/" ]
The actual problem is that, instead of adding 1 to the values, you're doubling them: ``` sco[i][1] += sco[i][1] ``` And no matter how many times you add 0 to 0, it's still 0. To add 1, just use `+= 1`. --- But you've got another problem, at least in the code you posted. Each `sco[i]` value just a number, not a list of two things, the second of which is a number. So what you really want is: ``` sco[i] += 1 ``` And similarly, the keys aren't `sco[i][0]`, they're just `i`. --- And you've got a third problem. This one doesn't actually *break* your code, it just makes it more complicated, harder to understand, and slower… but that's still worth fixing. The whole point of dictionaries is that you don't have to iterate them to search for a key, you just look up the key directly. So, instead of this: ``` for i in sco: if i == dnt: sco[i] += 1 ``` … just do this: ``` sco[dnt] += 1 ``` It's simpler, harder to get wrong, and more efficient, all at the same time. --- I can't promise there are no other errors in your code, but you definitely need to fix these three, on top of whatever else is wrong, and I'm pretty sure the first one is the one that happens to be causing the specific problem you asked about.
Solution with using defaultdict and grouping by item in tuple: ``` import itertools from collections import defaultdict sho = ('human', 'loud', 'big') sco = {} for a, b in itertools.permutations(sho, 2): sco["{0} + {1}".format(a, b)] = 0 cnt = [('human', 'ron g.'), ('loud', 'ron g.'), ('big', 'kim p.'), ('human', 'kim p.'), ('loud', 'brian a.'), ('human', 'linda m.'), ('loud', 'linda m.')] groups = defaultdict(list) for obj in cnt: groups[obj[1]].append(obj[0]) final_list = [] # create list of pairs a + b final_list.extend(map(lambda x: " + ".join(x), groups.values())) for key in groups.keys(): groups[key].reverse() # create list of pairs b + a final_list.extend(map(lambda x: " + ".join(x), groups.values())) for val in final_list: if val in sco: sco[val] += 1 print(sco) ``` Here we: * grouping `cnt` tuple by person in to a dict * create list of value pairs from previous step * create reverse pairs(according to expected results of OP) * count existed pairs in `sco` Result: ``` {'human + loud': 2, 'loud + human': 2, 'loud + big': 0, 'human + big': 1, 'big + loud': 0, 'big + human': 1} ```
17,143,401
What I'm having is that this error is displayed when I wanted to copy a exe debug project that I have created (which works witout any problems) to another machine (the error message is displayed). According to the [question posted previously](https://stackoverflow.com/questions/7904213/msvcp100d-dll-missing), the best solution to get rid of the error message is to make a release and not a debug in the Configuration Manager. Doing that, and when rebuilding the project with the RELEASE one, I'm having new errors in my project which were not included when doing the DEBUG. For instance, one of them is : ``` Error 2 error C1083: Cannot open include file: 'opencv\highgui.h': No such file or directory c:\...\projects\...\ex\opencv.h 4 23 IntelliSense: identifier "IplImage" is undefined c:\...\ex.cpp 80 ``` Any feedbacks?
2013/06/17
[ "https://Stackoverflow.com/questions/17143401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2441175/" ]
MSVCP100.dll is part of the Microsoft Visual Studio 10 runtime. MSVCP100d.dll is the debug build of the same dll - useful for running your program in debug mode. <http://www.microsoft.com/en-us/download/details.aspx?id=5555> Basically it is a relatively new package and is not guaranteed to be on all systems, especially Windows XP, so you can distribute the required DLL files or the entire runtime with your program. EDIT: Keep in mind that debug builds are not meant to be distributed, so your program should not contain debug dll-s either such as MSVCP100d.dll. Try downloading it, and then see what happens. Also check out [this question.](https://stackoverflow.com/questions/12799783/visual-studio-2010-runtime-libraries)
MSVCP100D.dll and MSVCP100.dll is part of the Microsoft Visual Studio 10 runtime, so if someone compile her/his programs with this package, then uninstall the package and install another one for example Microsoft Visual Studio 12 (2013). When trying to run her/his programs , then her/his will get the message that 'so and so... try to reinstalling the program to fix this problem'. this means you have to reinstall Microsoft Visual Studio 10. the other way is to recompile your programs under the new package!
17,143,401
What I'm having is that this error is displayed when I wanted to copy a exe debug project that I have created (which works witout any problems) to another machine (the error message is displayed). According to the [question posted previously](https://stackoverflow.com/questions/7904213/msvcp100d-dll-missing), the best solution to get rid of the error message is to make a release and not a debug in the Configuration Manager. Doing that, and when rebuilding the project with the RELEASE one, I'm having new errors in my project which were not included when doing the DEBUG. For instance, one of them is : ``` Error 2 error C1083: Cannot open include file: 'opencv\highgui.h': No such file or directory c:\...\projects\...\ex\opencv.h 4 23 IntelliSense: identifier "IplImage" is undefined c:\...\ex.cpp 80 ``` Any feedbacks?
2013/06/17
[ "https://Stackoverflow.com/questions/17143401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2441175/" ]
You've probably added include paths for OpenCV to your project file. Unfortunately, Visual Studio by default makes such changes ONLY to the active configuration, which in your case was debug. This rarely makes sense. Adding a logging library would be such a rare case, but you probably needs OpenCV in both debug and release builds.
MSVCP100D.dll and MSVCP100.dll is part of the Microsoft Visual Studio 10 runtime, so if someone compile her/his programs with this package, then uninstall the package and install another one for example Microsoft Visual Studio 12 (2013). When trying to run her/his programs , then her/his will get the message that 'so and so... try to reinstalling the program to fix this problem'. this means you have to reinstall Microsoft Visual Studio 10. the other way is to recompile your programs under the new package!
40,298,290
In MSDN, "For **reference types**, an explicit cast is required if you need to convert from a base type to a derived type". In wiki, "In programming language theory, a **reference type is a data type that refers to an object in memory**. A pointer type on the other hand refers to a memory address. Reference types can be thought of as pointers that are implicitly dereferenced." which is the case in C. How to explain the memory storing procedure when considering explicit casting for reference type in C#?
2016/10/28
[ "https://Stackoverflow.com/questions/40298290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3902173/" ]
First of all don't try to write all your code in a single statement. Its is easier to debug using multiple statements: ``` itemCode.setText((String)showItem.getValueAt(showItem.getSelectedRow(), 0)); ``` Can easily be written as: ``` Object value = showItem.getValueAt(rowCount, 0); itemCode.setText( value.toString() ); ``` Note there is no need to invoke the getSelectedRow() method twice since you have a variable that contains that value. Then you can always add some debug code like: ``` Object value = showItem.getValueAt(rowCount, 0); System.out.println( value.getClass() ); ``` to see what type of Object your table has in that cell.
Maybe you should check this. [How do I convert from int to String?](https://stackoverflow.com/questions/4105331/how-do-i-convert-from-int-to-string) for ``` itemCode.setText((String)showItem.getValueAt(showItem.getSelectedRow(), 0)); ```
40,298,290
In MSDN, "For **reference types**, an explicit cast is required if you need to convert from a base type to a derived type". In wiki, "In programming language theory, a **reference type is a data type that refers to an object in memory**. A pointer type on the other hand refers to a memory address. Reference types can be thought of as pointers that are implicitly dereferenced." which is the case in C. How to explain the memory storing procedure when considering explicit casting for reference type in C#?
2016/10/28
[ "https://Stackoverflow.com/questions/40298290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3902173/" ]
First of all don't try to write all your code in a single statement. Its is easier to debug using multiple statements: ``` itemCode.setText((String)showItem.getValueAt(showItem.getSelectedRow(), 0)); ``` Can easily be written as: ``` Object value = showItem.getValueAt(rowCount, 0); itemCode.setText( value.toString() ); ``` Note there is no need to invoke the getSelectedRow() method twice since you have a variable that contains that value. Then you can always add some debug code like: ``` Object value = showItem.getValueAt(rowCount, 0); System.out.println( value.getClass() ); ``` to see what type of Object your table has in that cell.
You can't cast an `Integer` to `String`, because `Integer` *is not* a `String`, that is, `Integer` is not a subclass of `String`. However, you can pass the `Integer` to a `String`, since all `Object` have the `toString()` method. ```java Integer a = new Integer( 10 ); String myString = "" + a; //Is the same as String myString = "" + a.toString(), so you could do just //String myString = a.toString(); ``` I hope I have helped. Have a nice day. :)
7,900
[The Axis of Awesome](http://en.wikipedia.org/wiki/The_Axis_of_Awesome) has a song called "4 Chords", a medley of various songs all written, or so it's claimed, using the same four chords. Now, from what I understand, a chord is just a bunch of tones played at the same time so they sound like one. For example, a 300 Hz note and a 500 Hz note played simultaneously will be a 100 Hz sound (because 100 is the greatest common factor of 300 and 500) with a lot of nuance in it, and that's called a chord. So the songs in the medley all have the same chords, that is, the same sounds with the same… what I called nuances. They don't. Never mind the lyrics: there are clearly more than four sounds in any of the songs when sung: just listen to 'em. But even watching the keyboardist's hands on the electronic keyboard (for [the one segment where you get to do so for any significant length of time](http://www.youtube.com/watch?v=oOlDewpCfZQ#t=310s) (warning, foul language in that clip)), you can see he hits more than four chords. What gives? Am I hearing and seeing wrong, or is my definition of *chord* wrong, or is Axis of Awesome lying, or is there some explanation of how the songs in this medley are considered to have but four chords even though they have more?
2012/11/27
[ "https://music.stackexchange.com/questions/7900", "https://music.stackexchange.com", "https://music.stackexchange.com/users/400/" ]
**tl;dr - your definition of chord is wrong.** Your initial assumption > > a 300 Hz note and a 500 Hz note played simultaneously will be a 100 > Hz sound > > > is unfortunately incorrect. When you play a 300Hz note and a 500Hz note what you will get is a 300Hz note, and a 500Hz note, **and** a 200Hz note (the difference between them) **and** an 800Hz note (the sum of the two frequencies) (Have a listen to the demos on **[this page](http://www.animations.physics.unsw.edu.au/jw/beats.htm)** for examples) In addition to that, a chord can have any number of notes in it (typically on a piano it usually has 10 or less notes, and on a guitar you're usually expecting 6 or less) And finally, a chord can be played in many different ways, so if I wanted to I could play a 4 chord song using 20 different variations of that chord. **Update** After watching the actual video, the keyboard player is only playing 4 chords, and not really playing any variations of them. He is sometimes accenting certain notes more than the others, but the 4 chord shapes he is using are consistent throughout that segment. He is hitting and releasing **keys**, sure, but only as parts of the same chords.
Well, I don't know about all this hertz stuff, that's never interested me as a musician. A chord is a harmony that is created with a SET of usually three or four different notes (tones) that are not repeated. It does not matter which order you play them as long as they are played simulataneously. Now sometimes a band will have a song that is based on a three or four chords - these are the underlying changes - but often the musicians take liberty with this and insert additional chords, substitute chords, and so forth, so in fact they are not playing "just four chords." The guitarist or pianist might be playing more. It just depends.
7,900
[The Axis of Awesome](http://en.wikipedia.org/wiki/The_Axis_of_Awesome) has a song called "4 Chords", a medley of various songs all written, or so it's claimed, using the same four chords. Now, from what I understand, a chord is just a bunch of tones played at the same time so they sound like one. For example, a 300 Hz note and a 500 Hz note played simultaneously will be a 100 Hz sound (because 100 is the greatest common factor of 300 and 500) with a lot of nuance in it, and that's called a chord. So the songs in the medley all have the same chords, that is, the same sounds with the same… what I called nuances. They don't. Never mind the lyrics: there are clearly more than four sounds in any of the songs when sung: just listen to 'em. But even watching the keyboardist's hands on the electronic keyboard (for [the one segment where you get to do so for any significant length of time](http://www.youtube.com/watch?v=oOlDewpCfZQ#t=310s) (warning, foul language in that clip)), you can see he hits more than four chords. What gives? Am I hearing and seeing wrong, or is my definition of *chord* wrong, or is Axis of Awesome lying, or is there some explanation of how the songs in this medley are considered to have but four chords even though they have more?
2012/11/27
[ "https://music.stackexchange.com/questions/7900", "https://music.stackexchange.com", "https://music.stackexchange.com/users/400/" ]
The chords are I, IV, V, and vi (not in that order) which together contain every note in the key. So any extra notes could be considered to be part of one of those chords. Regardless though the idea is not that the keyboardist plays only a specific set of notes. It's that four chords (in the broader sense Dr Mayhem mentions, which includes inversions and so on) are the basis for the songs, forming the major progression and sound. Other chords (if any) serve only to transition to one of the 4 main chords. And of course this is only true for the portion of the song being played — they never get to the part of Don't Start Believing that uses a iii chord! None of those song snippets could be played recognizably without one of those 4 chords. But they could all be played without any other chords and be recognizable. --- Summarizing some discussion from comments: There are 7 notes in every Major/minor key. Capital-numeral (e.g., IV) denotes the Major chord starting on the numbered note, and lowercase-numeral (e.g., iii) denotes the minor chord starting on the numbered note. Every note in the key is used by at least one of the four chords above (I, IV, V, vi), meaning that any note you play in the key could be considered to be functioning as part as one of those 4 chords rather than independently or as part of a different chord. In the key of C Major, any combination of any C's, E's, and G's could be considered a I chord. (Similarly any such combination would be a V chord in F Major, and so on.) Most commonly you'll have one of each note very close together, but it's not necessary. You might consider individual notes part of an arpeggiated chord, but it's important to note that notes can be left out without making it "not a chord". This general sense of "chord" we're using is limited to specific notes, but not specific combinations or positions of said notes. So, one "chord" in the general sense covers an entire subset of chords in the specific sense. The class "G Major chord" covers the specific "G4 B5 D5" chord as well as many many others — "G4 B6 D7", "G4 B5", "D3 G3 B4", etc.
Well, I don't know about all this hertz stuff, that's never interested me as a musician. A chord is a harmony that is created with a SET of usually three or four different notes (tones) that are not repeated. It does not matter which order you play them as long as they are played simulataneously. Now sometimes a band will have a song that is based on a three or four chords - these are the underlying changes - but often the musicians take liberty with this and insert additional chords, substitute chords, and so forth, so in fact they are not playing "just four chords." The guitarist or pianist might be playing more. It just depends.
56,606,827
Currently working on a very basic three table/model problem in Laravel and the proper Eloquent setup has my brain leaking. COLLECTION -> coll\_id, ... ITEM -> item\_id, coll\_id, type\_id, ... TYPE -> type\_id, ... I can phrase it a thousand ways but cannot begin to conceptualize the appropriate Eloquent relationships: COLLECTIONS have many ITEMS, each ITEM has a TYPE. Or, an ITEM belongs to a single COLLECTION, TYPES are associated with many ITEMS. To me COLLECTION and ITEM are key, while TYPE is really additional reference data on a given ITEM; basically a category for the item. My objective is to build a solution where users create COLLECTIONS, add ITEMS to those COLLECTIONS, and those ITEMS are associated with one of many TYPES (which they will also define). I know this example isn't far from other Author, Book, Category; or City, State, Country examples but implementing those model frameworks doesn't build the full connection from COLLECTION<->ITEM<->TYPE and most obviously fails when trying to associate TYPES within a COLLECTION. Models: COLLECTION ``` class Collection extends Model { protected $guarded = []; public function items() { return $this->hasMany(Item::class); } public function types() { return $this->hasManyThrough(Type::class, Item::class); } } ``` ITEM ``` class Item extends Model { public function collection() { return $this->belongsTo(Collection::class); } public function type() { return $this->belongsTo(Type::class); } } ``` TYPE ``` class Type extends Model { public function item() { return $this->hasMany(Item::class); } } ``` These models have COLLECTION<->ITEM in both directions working well, but the wheels fall off when I try to integrate TYPE. Depending on the 1000 variations I've tried I either get NULL in Tinker or it's looking for an ITEM\_ID in TYPE which doesn't and shouldn't exist. What would a solution be to update the model to accurately reflect ITEMS having one TYPE and the eventual set of TYPES within a COLLECTION? Thanks in advance! --- UPDATE: Working *nested* solution - the primary response solution was showing 2 relations at COLLECTION, no nesting: ``` class Collection extends Model { protected $guarded = []; public function items() { return $this->hasMany(Item::class); } ``` ``` class Item extends Model { public function collection() { return $this->hasOne(Collection::class); } public function type() { return $this->belongsto(Type::class); } } ``` ``` class Type extends Model { public function items() { return $this->hasMany(Item::class); } } ``` ``` $collection->load('items.type'); dd($collection); ``` ``` Collection {#280 ▼ #guarded: [] #connection: "mysql" #table: "collections" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:5 [▶] #original: array:5 [▶] #changes: [] #casts: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] **#relations: array:1** [▼ "items" => Collection {#285 ▼ #items: array:2 [▼ 0 => Item {#288 ▼ #connection: "mysql" #table: "items" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:13 [▶] #original: array:13 [▶] #changes: [] #casts: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] **#relations: array:1** [▼ "type" => Type {#296 ▶} ] #touches: [] +timestamps: true #hidden: [] #visible: [] #fillable: [] #guarded: array:1 [▶] } 1 => Item {#289 ▶} ] } ] ```
2019/06/15
[ "https://Stackoverflow.com/questions/56606827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11558094/" ]
`HasManyThrough` isn't the right relationship between Collection and Type. `HasManyThrough` is kind of like chaining 2 `HasMany` relationships together: ``` Country -> State -> City ``` Notice how the arrows all go one way. That's because City has a foreign key to State, and State has a foreign key to Country. Your relationship looks like this: ``` Collection -> Item <- Type ``` So Item has foreign keys to both Collection and Type. In this case, the relationship between Collection and Type is actually `BelongsToMany`, and the Item table is the join table. <https://laravel.com/docs/5.8/eloquent-relationships#many-to-many> ```php class Collection extends Model { protected $guarded = []; public function items() { return $this->hasMany(Item::class); } public function types() { // Substitute your table and key names here return $this->belongsToMany(Type::class, 'items_table', 'coll_id', 'type_id'); } } class Type extends Model { public function items() { return $this->hasMany(Item::class); } public function collections() { // Substitute your table and key names here return $this->belongsToMany(Collection::class, 'items_table', 'type_id', 'coll_id'); } } class Item extends Model { public function collection() { return $this->belongsto(Collection::class); } public function type() { return $this->belongsto(Type::class); } } ``` If you want to get collections with their items, and the corresponding type under each item, you can do: ``` Collection::with(['items.type'])->get(); ```
You can call the item first then get the item type through your relationship. ``` public function getCollectionOfItemsBaseOnType($type){ $collections = Collection::all(); $items = []; foreach($collections as $collection){ if($collection->item->type == $type){ array_push($items, $collection->item); } } } return $items; ```
58,545,828
I know that JAWS, by default, will ignore `<span/>` tags. My team got around that issue. Now, however, we have some content that is displayed using `<span/>` tags where the text displayed for sighted users doesn't play well with JAWS reading the information out. In our specific case, it would be international bank account numbers, which can contain letters. In this case, instead of reading individual digits, JAWS attempts to read the content as a word, resulting in predictably poor output. So, a couple of questions: 1. Given that this is part of a large page that I have neither the time nor the permission to refactor, is there a way to get this working within the constraints I've described? 2. If you were to write a page like this from scratch, what's the best practice for crafting the page such that I would have the ability to supply "alternate" text for read-only, non-interactive content? If it helps, the outcome I'm envisioning is something like this: `<span id="some-label" aria-label="1 2 3 4 5 A">12345A</span>` We have been unable to come up with any combination of techniques that would have JAWS read: "1 2 3 4 5 A" instead of reading "12345A" as a single word.
2019/10/24
[ "https://Stackoverflow.com/questions/58545828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394484/" ]
The technical answer is always the same, and has been repeated many times here and elsewhere: **aria-label has no effect if you don't also assign a role**. Now, for the more user experience question, I'm blind myself, and I can tell you, it may not be a good idea to force a spell out of each digit individually. * We are used in having account, telephone, etc. numbers grouped * IF we want a spell out of each digit individually, Jaws has the function: insert+up arrow twice quickly. Other screen readers have similar shortcuts. * My native language is french, not english. Although I'm on an english page, I may want to have numbers spoken in french, because it's easier for me. BY forcing a label, you prevent me from hearing numbers in french. * And probably the best argument: what are you going to say if you were to give your account number on the phone ? Will you say "one two three four five", "twelve thousend thirty hundred twenty one", "twelve thirty four five", something else ? Doing this litle exercise is likely to give you a good label to put in, but several people are probably going to give you different answers.
Quentin has given a very good answer that covers 99.9% of all scenarios. However there are some less proficient screen reader users who may benefit from having things read back letter by letter. **This should be an optional toggle on the field.** The way to implement a letter by letter read out is as follows but **please** use it sparingly and with the above scenarios in mind. The trick is to use a visual hidden class (screen reader only - `vh` in this example) to add full stops between each item. Make sure that everything is tightly packed or you will end up with unwanted spaces due to using `<span>`s. The beauty of doing this way is as QuentiC said - some people use a different language and `ARIA` labels don't always get translated, numbers in the below example should. ```css .vh { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px 1px 1px 1px); /* IE6, IE7 */ clip: rect(1px, 1px, 1px, 1px); white-space: nowrap; /* added line */ } ``` ```html <div> A<span class="vh">.</span>1<span class="vh">.</span>C<span class="vh">.</span> </div> ```
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
Java defines two types of streams, byte and character. The main reason why System.out.println() can't show Unicode characters is that System.out.println() is a byte stream that deal with only the low-order eight bits of character which is 16-bits. In order to deal with Unicode characters(16-bit Unicode character), you have to use character based stream i.e. PrintWriter. PrintWriter supports the print( ) and println( ) methods. Thus, you can use these methods in the same way as you used them with System.out. ``` PrintWriter printWriter = new PrintWriter(System.out,true); char aa = '\u0905'; printWriter.println("aa = " + aa); ```
try to use utf8 character set - ``` Charset utf8 = Charset.forName("UTF-8"); Charset def = Charset.defaultCharset(); String charToPrint = "u0905"; byte[] bytes = charToPrint.getBytes("UTF-8"); String message = new String(bytes , def.name()); PrintStream printStream = new PrintStream(System.out, true, utf8.name()); printStream.println(message); // should print your character ```
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
try to use utf8 character set - ``` Charset utf8 = Charset.forName("UTF-8"); Charset def = Charset.defaultCharset(); String charToPrint = "u0905"; byte[] bytes = charToPrint.getBytes("UTF-8"); String message = new String(bytes , def.name()); PrintStream printStream = new PrintStream(System.out, true, utf8.name()); printStream.println(message); // should print your character ```
I ran into the same problem wiht Eclipse. I solved my problem by switching the Encoding format for the console from ISO-8859-1 to UTF-8. You can do in the Run/Run Configurations/Common menu. <https://eclipsesource.com/blogs/2013/02/21/pro-tip-unicode-characters-in-the-eclipse-console/>
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
try to use utf8 character set - ``` Charset utf8 = Charset.forName("UTF-8"); Charset def = Charset.defaultCharset(); String charToPrint = "u0905"; byte[] bytes = charToPrint.getBytes("UTF-8"); String message = new String(bytes , def.name()); PrintStream printStream = new PrintStream(System.out, true, utf8.name()); printStream.println(message); // should print your character ```
Unicode is a unique code which is used to print any character or symbol. You can use unicode from --> <https://unicode-table.com/en/> Below is an example for printing a symbol in Java. ``` package Basics; /** * * @author shelc */ public class StringUnicode { public static void main(String[] args) { String var1 = "Cyntia"; String var2 = new String(" is my daughter!"); System.out.println(var1 + " \u263A" + var2); //printing heart using unicode System.out.println("Hello World \u2665"); } } ****************************************************************** OUTPUT--> Cyntia ☺ is my daughter! Hello World ♥ ```
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
Java defines two types of streams, byte and character. The main reason why System.out.println() can't show Unicode characters is that System.out.println() is a byte stream that deal with only the low-order eight bits of character which is 16-bits. In order to deal with Unicode characters(16-bit Unicode character), you have to use character based stream i.e. PrintWriter. PrintWriter supports the print( ) and println( ) methods. Thus, you can use these methods in the same way as you used them with System.out. ``` PrintWriter printWriter = new PrintWriter(System.out,true); char aa = '\u0905'; printWriter.println("aa = " + aa); ```
Your `myString` variable contains the perfectly correct value. The problem must be the output from `System.out.println(myString)` which has to send some bytes to some output to show the glyphs that you want to see. `System.out` is a PrintStream using the "platform default encoding" to convert characters to byte sequences - maybe your platform doesn't support that character. E.g. on my Windows 7 computer in Germany, the default encoding is CP1252, and there's no byte sequence in this encoding that corresponds to your character. Or maybe the encoding is correct, but simply the font that creates graphical glyphs from characters doesn't have that charater. If you are sending your output to a Windows CMD.EXE window, then maybe both reasons apply. But be assured, your string is correct, and if you send it to a destination that can handle it (e.g. a Swing JTextField), it'll show up correctly.
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
Your `myString` variable contains the perfectly correct value. The problem must be the output from `System.out.println(myString)` which has to send some bytes to some output to show the glyphs that you want to see. `System.out` is a PrintStream using the "platform default encoding" to convert characters to byte sequences - maybe your platform doesn't support that character. E.g. on my Windows 7 computer in Germany, the default encoding is CP1252, and there's no byte sequence in this encoding that corresponds to your character. Or maybe the encoding is correct, but simply the font that creates graphical glyphs from characters doesn't have that charater. If you are sending your output to a Windows CMD.EXE window, then maybe both reasons apply. But be assured, your string is correct, and if you send it to a destination that can handle it (e.g. a Swing JTextField), it'll show up correctly.
I ran into the same problem wiht Eclipse. I solved my problem by switching the Encoding format for the console from ISO-8859-1 to UTF-8. You can do in the Run/Run Configurations/Common menu. <https://eclipsesource.com/blogs/2013/02/21/pro-tip-unicode-characters-in-the-eclipse-console/>
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
Your `myString` variable contains the perfectly correct value. The problem must be the output from `System.out.println(myString)` which has to send some bytes to some output to show the glyphs that you want to see. `System.out` is a PrintStream using the "platform default encoding" to convert characters to byte sequences - maybe your platform doesn't support that character. E.g. on my Windows 7 computer in Germany, the default encoding is CP1252, and there's no byte sequence in this encoding that corresponds to your character. Or maybe the encoding is correct, but simply the font that creates graphical glyphs from characters doesn't have that charater. If you are sending your output to a Windows CMD.EXE window, then maybe both reasons apply. But be assured, your string is correct, and if you send it to a destination that can handle it (e.g. a Swing JTextField), it'll show up correctly.
Unicode is a unique code which is used to print any character or symbol. You can use unicode from --> <https://unicode-table.com/en/> Below is an example for printing a symbol in Java. ``` package Basics; /** * * @author shelc */ public class StringUnicode { public static void main(String[] args) { String var1 = "Cyntia"; String var2 = new String(" is my daughter!"); System.out.println(var1 + " \u263A" + var2); //printing heart using unicode System.out.println("Hello World \u2665"); } } ****************************************************************** OUTPUT--> Cyntia ☺ is my daughter! Hello World ♥ ```
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
Java defines two types of streams, byte and character. The main reason why System.out.println() can't show Unicode characters is that System.out.println() is a byte stream that deal with only the low-order eight bits of character which is 16-bits. In order to deal with Unicode characters(16-bit Unicode character), you have to use character based stream i.e. PrintWriter. PrintWriter supports the print( ) and println( ) methods. Thus, you can use these methods in the same way as you used them with System.out. ``` PrintWriter printWriter = new PrintWriter(System.out,true); char aa = '\u0905'; printWriter.println("aa = " + aa); ```
I ran into the same problem wiht Eclipse. I solved my problem by switching the Encoding format for the console from ISO-8859-1 to UTF-8. You can do in the Run/Run Configurations/Common menu. <https://eclipsesource.com/blogs/2013/02/21/pro-tip-unicode-characters-in-the-eclipse-console/>
44,878,541
I have a few activities: * Splash screen * Login * Registration * Dashboard If the user has never logged in, it will go like this: > > Splash screen > Login > Registration > Dashboard > > > When I `back` from the Dashboard, it should exit the app, skipping through the other activities. `noHistory` on the Login page doesn't work here because sometimes the user will `back` from Registration. If the user has previously logged on, it should go like this: > > Splash screen > Dashboard > > > If the user logs out, perhaps to use another account, then it should go: > > Dashboard > Login > Dashboard > > > But if the user goes `back` from the new Dashboard, it shouldn't enter the previous account's Dashboard. Aside from that, my app contains multiple modules, some of which don't have access to other modules, so a solution that can work between modules would be helpful. I have tried a mix of `finish()` and `startActivityForResult()` and trying to check where the activities return from but it felt very hacky, time-consuming, and it messes up on new use cases. Are there better ways?
2017/07/03
[ "https://Stackoverflow.com/questions/44878541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402526/" ]
Java defines two types of streams, byte and character. The main reason why System.out.println() can't show Unicode characters is that System.out.println() is a byte stream that deal with only the low-order eight bits of character which is 16-bits. In order to deal with Unicode characters(16-bit Unicode character), you have to use character based stream i.e. PrintWriter. PrintWriter supports the print( ) and println( ) methods. Thus, you can use these methods in the same way as you used them with System.out. ``` PrintWriter printWriter = new PrintWriter(System.out,true); char aa = '\u0905'; printWriter.println("aa = " + aa); ```
Unicode is a unique code which is used to print any character or symbol. You can use unicode from --> <https://unicode-table.com/en/> Below is an example for printing a symbol in Java. ``` package Basics; /** * * @author shelc */ public class StringUnicode { public static void main(String[] args) { String var1 = "Cyntia"; String var2 = new String(" is my daughter!"); System.out.println(var1 + " \u263A" + var2); //printing heart using unicode System.out.println("Hello World \u2665"); } } ****************************************************************** OUTPUT--> Cyntia ☺ is my daughter! Hello World ♥ ```
24,662,079
I am trying to make all the table cells equal to the image size, but for some reason, they won't be set to it. <http://jsfiddle.net/gzkhW/> HTML(shortened a bit) ``` <table> <tr> <td><img src="http://i.imgur.com/CMu2qnB.png"></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> ``` CSS ``` table { border:1px solid black; } td {width:206px; height:214px; border:1px solid black; } ```
2014/07/09
[ "https://Stackoverflow.com/questions/24662079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077972/" ]
You would like to do these: 1. You can directly select using `.slide`. 2. Check the length of `nextUp` instead. Try this, seems to be a workaround: **JS** ``` $('.next').click(function() { var current = $('.slide'); var nextUp = $('.slide').next('.hello'); if( nextUp.length == 0 ) { $('div.hello:first').addClass('slide'); $('div.hello:last').removeClass('slide'); } else { $(nextUp).addClass('slide'); $(current).removeClass('slide'); } }); ``` **[JSFIDDLE DEMO](http://jsfiddle.net/c4ZNm/15/)**
You code have some issues. First, `.has` check if the element has descendant that match the selector. You just need to combine the selector to `.hello.slide`. ``` var current = $('.hello.slide'); ``` --- You can then reuse that variable to target the next element. ``` var nextUp = current.next('.hello'); ``` --- You need to check the length to know if it found something, not an empty string. ``` if( nextUp.length === 0) ``` --- You also don't need to wrap your `current` and `nextUp` in a jQuery element, they already are a jQuery element. ``` nextUp.addClass('slide'); current.removeClass('slide'); ``` --- Final code : ============ ``` $('.next').click(function() { var current = $('.hello.slide'); var nextUp = current.next('.hello'); if( nextUp.length === 0) { $('.hello:first').addClass('slide'); $('.hello:last').removeClass('slide'); } else { nextUp.addClass('slide'); current.removeClass('slide'); } }); ``` Fiddle : <http://jsfiddle.net/c4ZNm/14/>
24,662,079
I am trying to make all the table cells equal to the image size, but for some reason, they won't be set to it. <http://jsfiddle.net/gzkhW/> HTML(shortened a bit) ``` <table> <tr> <td><img src="http://i.imgur.com/CMu2qnB.png"></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> ``` CSS ``` table { border:1px solid black; } td {width:206px; height:214px; border:1px solid black; } ```
2014/07/09
[ "https://Stackoverflow.com/questions/24662079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077972/" ]
You would like to do these: 1. You can directly select using `.slide`. 2. Check the length of `nextUp` instead. Try this, seems to be a workaround: **JS** ``` $('.next').click(function() { var current = $('.slide'); var nextUp = $('.slide').next('.hello'); if( nextUp.length == 0 ) { $('div.hello:first').addClass('slide'); $('div.hello:last').removeClass('slide'); } else { $(nextUp).addClass('slide'); $(current).removeClass('slide'); } }); ``` **[JSFIDDLE DEMO](http://jsfiddle.net/c4ZNm/15/)**
Here is working fiddle: <http://jsfiddle.net/c4ZNm/10/> instead of ``` $('.hello').has('.slide') ``` use ``` $('.hello.slide') ``` When there is no more next element, nextUp wont be '', its length will be 0. I added count to count all .hello divs - 1 for indexication. because :last-child is your "a" tag element, not .hello div, so instead :nth-child(3) selector i added .eq(count) to be more dynamic. Best regards
17,373,866
I wrote an android library for some UI utilities. I have a function that return ImageView. But, my problem is that I want that the resource of the drawable image, will be in the project that contains the library. I will explain... I want that the ImageView will always take the drawable with the source name: `R.drawable.ic_img_logo` (and only this name). This resource will not actually be in the library. But the project that contains the library will contains also drawable with the resource name `R.drawable.ic_img_logo`. I know that this thing works with id (of views), you can create file call `ids.xml` and define some ids in the file that others can use them, and you will recognize them. But how can I do this with drawables?
2013/06/28
[ "https://Stackoverflow.com/questions/17373866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1725836/" ]
I found the answer. You need to create a file called `drawables.xml` in the library. Then inside it write: ``` <resource> <item name="ic_img_logo" type="drawable" /> </resource> ``` Its make fake resource `R.drawable.ic_img_logo`. Then if the project that include the library have drawable called `ic_img_logo`. The library be able to access to this drawable, because it will be the same resource.
If the drawable is not in the library, then it's not a resource. An alternative would be accessing it from the assets, like this: ``` Drawable d = Drawable.createFromStream(getAssets().open(path_in_assets), null); ``` Where the `path_in_assets` would be a constant.
17,373,866
I wrote an android library for some UI utilities. I have a function that return ImageView. But, my problem is that I want that the resource of the drawable image, will be in the project that contains the library. I will explain... I want that the ImageView will always take the drawable with the source name: `R.drawable.ic_img_logo` (and only this name). This resource will not actually be in the library. But the project that contains the library will contains also drawable with the resource name `R.drawable.ic_img_logo`. I know that this thing works with id (of views), you can create file call `ids.xml` and define some ids in the file that others can use them, and you will recognize them. But how can I do this with drawables?
2013/06/28
[ "https://Stackoverflow.com/questions/17373866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1725836/" ]
I found the answer. You need to create a file called `drawables.xml` in the library. Then inside it write: ``` <resource> <item name="ic_img_logo" type="drawable" /> </resource> ``` Its make fake resource `R.drawable.ic_img_logo`. Then if the project that include the library have drawable called `ic_img_logo`. The library be able to access to this drawable, because it will be the same resource.
you have to name the file ic\_img\_logo
60,817,243
I have large data files formatted as follows: ``` 1 M * 0.86 2 S * 0.81 3 M * 0.68 4 S * 0.53 5 T . 0.40 6 S . 0.34 7 T . 0.25 8 E . 0.36 9 V . 0.32 10 I . 0.26 11 A . 0.17 12 H . 0.15 13 H . 0.12 14 W . 0.14 15 A . 0.16 16 F . 0.13 17 A . 0.12 18 I . 0.12 19 F . 0.22 20 L . 0.44 21 I * 0.68 22 V * 0.79 23 A * 0.88 24 I * 0.88 25 G * 0.89 26 L * 0.88 27 C * 0.81 28 C * 0.82 29 L * 0.79 30 M * 0.80 31 L * 0.74 32 V * 0.72 33 G * 0.62 ``` What I'm trying to figure out how to do is loop through each line in the file and, if the line contains an asterisk, begin finding a subsequent range that satisfies this condition. Additionally it would be nice to output the largest range in a file. So for this example, the desired output would look like: ``` 1-4,21-33 13 ``` Thanks for any assistance!
2020/03/23
[ "https://Stackoverflow.com/questions/60817243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441735/" ]
There are several way to perform this. One solution is to read the file line by line. I advise you to have a look at this very good [tutorial](https://stackabuse.com/read-a-file-line-by-line-in-python/) on how to read file. Once you did it, you can try the following: * Iterate over each line of the file: + If there is an `*` in the line: + Then: - keep the index (this a starting point) - read the lines while there is an "\*" in the line - keep the index (this a end point) + read next line In Python: ```py # your file path filepath = 'test.txt' with open(filepath) as fp: line = fp.readline() # Count the line index cnt = 1 # Output storing deb and end index output = [] # While there are lines in the file (e.g. the end of file not reached) while line: # Check if the current line has a "*" if "*" in line: # If yes, keep the count value, it's the starting point deb = cnt # Iterate while there are "*" in line while "*" in line: cnt += 1 line = fp.readline() # END while (e.g end of file or there is no "*" in the line # Add the starting index and end index to the output output.append({"deb" : deb, "end": cnt - 1}) # Read next line cnt += 1 line = fp.readline() print(output) # [{'deb': 1, 'end': 4}, {'deb': 21, 'end': 33}] ```
Since people are running to answer, this one uses a generator to generate ranges: ``` def find_ranges(fn): with open(fn) as f: start = None for line_no, line in enumerate(f): if start is None: if '*' in line: start = line_no + 1 # start of a range elif '*' not in line: yield [start, line_no] # seen end of range start = None if start is not None: # end of file without seeing end of a range yield [start, line_no + 1] ranges = [range for range in find_ranges('test.txt')] max_range = max(ranges, key = lambda x: x[1] - x[0]) # largest range seen print(ranges, max_range[1] - max_range[0] + 1) ``` Prints: ``` [[1, 4], [21, 33]] 13 ``` You can, of course, format the ranges anyway you wish. The same algorithm without using a generator: ``` def find_ranges(fn): ranges = [] with open(fn) as f: start = None for line_no, line in enumerate(f): if start is None: if '*' in line: start = line_no + 1 # start of a range elif '*' not in line: ranges.append([start, line_no]) # end of a range start = None if start is not None: # end of file without seeing end of a range ranges.append([start, line_no + 1]) max_range = max(ranges, key = lambda x: x[1] - x[0]) return ranges, max_range[1] - max_range[0] + 1 ranges, max_range = find_ranges('test.txt') print(ranges, max_range) ```
19,056,546
I want to create an HTML Message to send an email in PHP. ``` $message = $mess0 . "</br>" . $mess1 . "</br>" . $mess2 . "</br>" . $mes1 . "</br></br>" . $mes2 . "</br>" . $mes23 . "</br></br>" . $mes3 . "</br></br>" . $mes4 . "</br>" . $mes5 . "</br>" . $mes6 . "</br>" . $mes7 . "</br>" . $mes8 . "</br>" . $mes9 . "</br></br>" . $mes10 ; $message = <html><body><p>$message</p></body></html>; ``` Here are some variables. I am getting the following error. > > Parse error: syntax error, unexpected '<' in /home/thevowaa/public\_html/iphoneapp/webservice/file.php on line 214 > > >
2013/09/27
[ "https://Stackoverflow.com/questions/19056546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1921872/" ]
Add HTML tags between double quotes. ``` $message = "<html><body><p>".$message."</p></body></html>"; ```
Where are the double quotes see below ``` $message = "<html><body><p>$message</p></body></html>"; ```
19,056,546
I want to create an HTML Message to send an email in PHP. ``` $message = $mess0 . "</br>" . $mess1 . "</br>" . $mess2 . "</br>" . $mes1 . "</br></br>" . $mes2 . "</br>" . $mes23 . "</br></br>" . $mes3 . "</br></br>" . $mes4 . "</br>" . $mes5 . "</br>" . $mes6 . "</br>" . $mes7 . "</br>" . $mes8 . "</br>" . $mes9 . "</br></br>" . $mes10 ; $message = <html><body><p>$message</p></body></html>; ``` Here are some variables. I am getting the following error. > > Parse error: syntax error, unexpected '<' in /home/thevowaa/public\_html/iphoneapp/webservice/file.php on line 214 > > >
2013/09/27
[ "https://Stackoverflow.com/questions/19056546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1921872/" ]
Add HTML tags between double quotes. ``` $message = "<html><body><p>".$message."</p></body></html>"; ```
There are two possible ways to hold HTML in PHP variable. You can use single quote or double quotes. You also need to put a dot(.) before and after single/double quotes. Your PHP string could be constructed in following two ways: ``` $message = '<html><body><p>'.$message.'</p></body></html>'; ``` or like this, ``` $message = "<html><body><p>".$message."</p></body></html>"; ``` Also, use of single quotes(') is encouraged in PHP coding because it's doesn't clash with javascript or css double quotes(") when constructing html pages using PHP. For more information on usage of quotes in PHP, check out this [stackoverflow answer](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php)
23,859,259
I would like to ask a question about "foreach loop" in PHP. Towards the bottom of the code below, the "while" loop accesses elements from an array individually. How can I rewrite the BODY of the while loop using a "foreach" loop? ``` <?php require_once('MDB2.php'); $db = MDB2::connect("mysql://mk:[email protected]/mk"); if(PEAR::iserror($db)) die($db->getMessage()); $sql = "SELECT courses.ID,courses.Name,staff.Name FROM courses,staff WHERE courses.Coordinator=staff.id and courses.ID = \"$course\""; $q = $db->query($sql); if(PEAR::iserror($q)) die($q->getMessage()); while($row = $q->fetchRow()){ echo "<tr><td>$row[0]</td>\n"; echo "<td>$row[1]</td>\n"; echo "<td>$row[2]</td></tr>\n"; } } ?> </table> </body></html> ```
2014/05/25
[ "https://Stackoverflow.com/questions/23859259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975787/" ]
If you dereference a `char **`, you should get a pointer to `char`. There are no pointers in a `char[3][10]`. They're just not interchangeable. It works for a one-dimensional `char *` array because the array name implicitly converts to a pointer to the first element in this context, and if you dereference a `char *` you get a `char`, and that's exactly what your one-dimensional `char` array contains. The line of thinking that "if it works for a one-dimensional array, shouldn't it work for a two-dimensional array?" is just invalid, here. To make what you want to do work, you'd have to create `char *` arrays, like so: ``` #include <stdio.h> void fn(int argc, char ** argv) { printf("argc : %d\n", argc); for (int i = 0; i < argc; ++i) { printf("%s\n", argv[i]); } } int main(void) { char * var3[3] = { "arg1", "argument2", "arg3" }; char * var4[4] = { "One", "Two", "Three", "Four" }; fn(3, var3); fn(4, var4); return 0; } ``` which outputs: ``` paul@local:~/src/c/scratch$ ./carr argc : 3 arg1 argument2 arg3 argc : 4 One Two Three Four paul@local:~/src/c/scratch$ ``` An alternative is to declare your function as accepting an array of (effectively a pointer to) 10-element arrays of `char`, like so: ``` #include <stdio.h> void fn(int argc, char argv[][10]) { printf("argc : %d\n", argc); for (int i = 0; i < argc; ++i) { printf("%s\n", argv[i]); } } int main(void) { char var3[3][10] = { "arg1", "argument2", "arg3" }; char var4[4][10] = { "arg1", "argument2", "arg3", "arg4" }; fn(3, var3); fn(4, var4); return 0; } ``` but this obviously requires hard-coding the sizes of all dimensions except the leftmost, which is usually less desirable and flexible. `char argv[][10]` in the parameter list here is another way of writing `char (*argv)[10]`, i.e. declaring `argv` as a pointer to array of `char` of size `10`.
A `type**` is by definition a pointer to a pointer, or an array of pointers. When used in a function declaration, `type[][]` is inteligible with `type**` as in: ``` int main(int argc, char argv[][]) { ... ``` But it is not when declaring variables. When you do this: ``` char var[a][b] = { ... } ``` This is a matrix of `char` and there are no pointers envolved here. The compiler pretty much handles this as a straight forward array of `char var[a*b]` and when you access `var[1][2]` it internally does `var[1*b+2]`. It is not really an array of strings, and its utilization is only possible because the compiler knows the value of `b` when compiling this function, as the variable was declared there. In order to pass as `char**`, `var` must be an array of pointers. A list containing pointers of `char*`. When you do this: ``` char *var[a] { ... } ``` Now you are telling the compiler your intention. `var` is no longer a matrix of `char`, it is truly a list of pointers `char*`.
1,300,792
In Windows I would like to be able to run a script or application that starts an another application and sets its size and location. An example of this would be to run an application/script that starts notepad and tells it to be 800x600 and to be in the top right corner. Does anyone have any ideas regardless of language?
2009/08/19
[ "https://Stackoverflow.com/questions/1300792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143074/" ]
Do you mean something like this: ``` $ xterm -geometry 135x35+0+0 ``` which puts an xterm at the top-left of the screen (`+0+0`) and makes it 135 columns by 35 lines? Most X apps take a -geometry argument with the same syntax (though often in pixels, not characters like xterm), and you can obviously put that in a shell script. Alternatively, if the program is already running, the xwit command can be used to move it: ``` xwit -move 0 0 -columns 135 -id $WINDOWID ``` That will move the xterm its running in to the top-left corner of the screen, and make it 135 columns wide. It works on any window, not just xterms. For example: ``` xwit -move 0 0 -id 0x6600091 ``` just moved my browser window. You can find window IDs with `xwininfo`, `xlsclients`, or several others.
Some OSs or desktops allow to set the size and location of a window in a config dialog, for example [KDE](http://www.kde.org/).
1,645,166
image naturalWidth return zero... that's it, why ? ``` var newimage = new Image(); newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; var width = newimage.naturalWidth; alert (width); ``` HELP, i dont know why ! \*\*\* that path is good, the image show up !
2009/10/29
[ "https://Stackoverflow.com/questions/1645166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71830/" ]
I'd guess it's because you're not waiting for the image to load - try this: ``` var newimage = new Image(); newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; newimage.onload = function() { var width = this.naturalWidth; alert(width); } ```
Here is the FINAL WORKING CODE... in case somebody wants to know. It's all a matter of waiting until the images have loaded! ``` <script type="text/javascript"> $(function() { $("#thumb").jCarouselLite({ btnNext: "#down", btnPrev: "#up", vertical: true, visible: 4 }); $("#thumb li img").click(function() { var newlinkimage = $(this).attr("src"); newlinkimage = 'retouche-hr' + newlinkimage.substring(14,17); $('#hr').remove(); var newimage = new Image(); newimage.src = newlinkimage + '-a.jpg'; newimage.onload = function() { var width = (newimage.width); var height = (newimage.height); $('#contentfull').append('<div id="hr"> </div>'); $("#hr").attr("width", width).attr("height", height); $("#hr").addClass('hrviewer'); //alert('a'); $("#hr").append('<div id="avant"> <img alt="before" src="' + newlinkimage +'-a.jpg"></div>'); $("#hr").append('<div id="apres"> <img alt="after" src="' + newlinkimage +'-b.jpg"></div>'); //alert('b'); $("#avant img").attr("src", newlinkimage + '-a.jpg').attr("width", width).attr("height", height); $("#apres img").attr("src", newlinkimage + '-b.jpg').attr("width", width).attr("height", height); $("#apres img").load(function(){$("#hr").beforeAfter({animateIntro:true});}); } }) }); </script> ```
1,645,166
image naturalWidth return zero... that's it, why ? ``` var newimage = new Image(); newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; var width = newimage.naturalWidth; alert (width); ``` HELP, i dont know why ! \*\*\* that path is good, the image show up !
2009/10/29
[ "https://Stackoverflow.com/questions/1645166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71830/" ]
I'd guess it's because you're not waiting for the image to load - try this: ``` var newimage = new Image(); newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; newimage.onload = function() { var width = this.naturalWidth; alert(width); } ```
For me the following works ... ``` $('<img src="mypathtotheimage.png"/>').load(function () { if (!isNotIe8) { // ie8 need a fix var image = new Image(); // or document.createElement('img') var width, height; image.onload = function () { width = this.width; height = this.height; }; image.src = $(this).attr("src"); } else { // everythings fine here .... // this.naturalWidth / this.naturalHeight; } ```
1,645,166
image naturalWidth return zero... that's it, why ? ``` var newimage = new Image(); newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; var width = newimage.naturalWidth; alert (width); ``` HELP, i dont know why ! \*\*\* that path is good, the image show up !
2009/10/29
[ "https://Stackoverflow.com/questions/1645166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71830/" ]
Here is the FINAL WORKING CODE... in case somebody wants to know. It's all a matter of waiting until the images have loaded! ``` <script type="text/javascript"> $(function() { $("#thumb").jCarouselLite({ btnNext: "#down", btnPrev: "#up", vertical: true, visible: 4 }); $("#thumb li img").click(function() { var newlinkimage = $(this).attr("src"); newlinkimage = 'retouche-hr' + newlinkimage.substring(14,17); $('#hr').remove(); var newimage = new Image(); newimage.src = newlinkimage + '-a.jpg'; newimage.onload = function() { var width = (newimage.width); var height = (newimage.height); $('#contentfull').append('<div id="hr"> </div>'); $("#hr").attr("width", width).attr("height", height); $("#hr").addClass('hrviewer'); //alert('a'); $("#hr").append('<div id="avant"> <img alt="before" src="' + newlinkimage +'-a.jpg"></div>'); $("#hr").append('<div id="apres"> <img alt="after" src="' + newlinkimage +'-b.jpg"></div>'); //alert('b'); $("#avant img").attr("src", newlinkimage + '-a.jpg').attr("width", width).attr("height", height); $("#apres img").attr("src", newlinkimage + '-b.jpg').attr("width", width).attr("height", height); $("#apres img").load(function(){$("#hr").beforeAfter({animateIntro:true});}); } }) }); </script> ```
For me the following works ... ``` $('<img src="mypathtotheimage.png"/>').load(function () { if (!isNotIe8) { // ie8 need a fix var image = new Image(); // or document.createElement('img') var width, height; image.onload = function () { width = this.width; height = this.height; }; image.src = $(this).attr("src"); } else { // everythings fine here .... // this.naturalWidth / this.naturalHeight; } ```
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
How to *skip*, *ignore* and/or *reject* git credentials prompts =============================================================== The answers above only worked partly for me when using Git-for-Windows: *two* different applications there were vying for my attention from the automated git pull/push scripts: * git-credentials-manager (developed by the GfW team AFAICT; has a clean, grey Windows interface look) * another dialog, which' ancestry has some definitely (crappy looking) X-Windows genes. **To shut all of them up**, *without* uninstalling the credentials manager as mentioned in some answers here: <https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows>, here's what now works, sitting on top of the automated (`bash`) shell scripts: ```sh # https://serverfault.com/questions/544156/git-clone-fail-instead-of-prompting-for-credentials export GIT_TERMINAL_PROMPT=0 # next env var doesn't help... export GIT_SSH_COMMAND='ssh -oBatchMode=yes' # these should shut up git asking, but only partly: the X-windows-like dialog doesn't pop up no more, but ... export GIT_ASKPASS=echo export SSH_ASKPASS=echo # We needed to find *THIS* to shut up the bloody git-for-windows credential manager: # https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654 export GCM_INTERACTIVE=never ``` What did NOT work ----------------- * All the incantations of `git config credential.modalprompt false` -- mentioned as a solution in answers to that linked SO question. *no dice* for me. * fiddling with that `GIT_SSH_COMMAND` environment variable: nothing worked but keeping it as I suspect it'll kick in when running this stuff on a Linux box instead of Windows. * `GIT_TERMINAL_PROMPT=0`: *no worky either*. Kept it in for the same reason, but *no dice* on Windows. Oh, and *uninstalling* the git credentials manager as suggested in other answers in that SO link was decided a **no go** option as it would definitely impact other repository trees where this thing *may* be useful one day. Though it was considered for a bit, before I decided against doing this. What DID work ------------- * messing with those two `*_ASKPASS` env.vars., oddly enough shut up the 'X-Windows looking' login prompt on (automated) `git push`. Yay! * `GCM_INTERACTIVE=never` was the magic ingredient to finally shut up that git-for-windows credential manager dialog. Thanks to that particular answer (<https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654>), which isn't near the top of the list, but definitely was the most important one for my case. My git version -------------- ``` $ git --version git version 2.30.1.windows.1 ``` ### Parting note `<rant>` Been looking for this info on-and-off for years: this time apparently I was lucky and maybe persevered longer(?), wading through the zillion pages yakking about *setting up* your credentials: google clearly is *not* intelligent. At least it does not listen very well to minority questions, that's for sure. `</rant>` The title is added in hopes that google indexing places this page higher for the next one looking for answers to these questions or variations therefor...
``` GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo ``` Work for me on Mac.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
``` GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo ``` Work for me on Mac.
Depending on how you're running git, redirecting stdin or stdout so that they are not connected to terminals will stop git from prompting for details and just cause it to error. This would also allow you to surface errors (or at least logs) to the webservice.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
In git version 2.3 there's an environment variable `GIT_TERMINAL_PROMPT` which when set to `0` will disable prompting for credentials. You can get more info about it in `man git` (after updating to git version `2.3`) or in [this blog post on github](https://github.com/blog/1957-git-2-3-has-been-released). Examples: * `git clone https://github.com/some/non-existing-repo` will prompt for username & password * `GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo` will fail without prompting for username & password
``` GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo ``` Work for me on Mac.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
In git version 2.3 there's an environment variable `GIT_TERMINAL_PROMPT` which when set to `0` will disable prompting for credentials. You can get more info about it in `man git` (after updating to git version `2.3`) or in [this blog post on github](https://github.com/blog/1957-git-2-3-has-been-released). Examples: * `git clone https://github.com/some/non-existing-repo` will prompt for username & password * `GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo` will fail without prompting for username & password
When you only have control over the git configuration: ``` git config --global credential.helper '!f() { echo quit=1; }; f' ``` Gives ``` $ git clone https://github.com/edx/drf-extensions.git/ Cloning into 'drf-extensions'... fatal: credential helper '!f() { echo quit=1; }; f' told us to quit ``` The [idea](https://github.com/gitster/git/commit/86362f7205a31188846de0aed94620c1f0776931#diff-34bca67031e9e8c12799a2252004d3f6R294) comes from the original committer of `GIT_TERMINAL_PROMPT` after following @user243345's link.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
In git version 2.3 there's an environment variable `GIT_TERMINAL_PROMPT` which when set to `0` will disable prompting for credentials. You can get more info about it in `man git` (after updating to git version `2.3`) or in [this blog post on github](https://github.com/blog/1957-git-2-3-has-been-released). Examples: * `git clone https://github.com/some/non-existing-repo` will prompt for username & password * `GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo` will fail without prompting for username & password
Depending on how you're running git, redirecting stdin or stdout so that they are not connected to terminals will stop git from prompting for details and just cause it to error. This would also allow you to surface errors (or at least logs) to the webservice.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
How to *skip*, *ignore* and/or *reject* git credentials prompts =============================================================== The answers above only worked partly for me when using Git-for-Windows: *two* different applications there were vying for my attention from the automated git pull/push scripts: * git-credentials-manager (developed by the GfW team AFAICT; has a clean, grey Windows interface look) * another dialog, which' ancestry has some definitely (crappy looking) X-Windows genes. **To shut all of them up**, *without* uninstalling the credentials manager as mentioned in some answers here: <https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows>, here's what now works, sitting on top of the automated (`bash`) shell scripts: ```sh # https://serverfault.com/questions/544156/git-clone-fail-instead-of-prompting-for-credentials export GIT_TERMINAL_PROMPT=0 # next env var doesn't help... export GIT_SSH_COMMAND='ssh -oBatchMode=yes' # these should shut up git asking, but only partly: the X-windows-like dialog doesn't pop up no more, but ... export GIT_ASKPASS=echo export SSH_ASKPASS=echo # We needed to find *THIS* to shut up the bloody git-for-windows credential manager: # https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654 export GCM_INTERACTIVE=never ``` What did NOT work ----------------- * All the incantations of `git config credential.modalprompt false` -- mentioned as a solution in answers to that linked SO question. *no dice* for me. * fiddling with that `GIT_SSH_COMMAND` environment variable: nothing worked but keeping it as I suspect it'll kick in when running this stuff on a Linux box instead of Windows. * `GIT_TERMINAL_PROMPT=0`: *no worky either*. Kept it in for the same reason, but *no dice* on Windows. Oh, and *uninstalling* the git credentials manager as suggested in other answers in that SO link was decided a **no go** option as it would definitely impact other repository trees where this thing *may* be useful one day. Though it was considered for a bit, before I decided against doing this. What DID work ------------- * messing with those two `*_ASKPASS` env.vars., oddly enough shut up the 'X-Windows looking' login prompt on (automated) `git push`. Yay! * `GCM_INTERACTIVE=never` was the magic ingredient to finally shut up that git-for-windows credential manager dialog. Thanks to that particular answer (<https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654>), which isn't near the top of the list, but definitely was the most important one for my case. My git version -------------- ``` $ git --version git version 2.30.1.windows.1 ``` ### Parting note `<rant>` Been looking for this info on-and-off for years: this time apparently I was lucky and maybe persevered longer(?), wading through the zillion pages yakking about *setting up* your credentials: google clearly is *not* intelligent. At least it does not listen very well to minority questions, that's for sure. `</rant>` The title is added in hopes that google indexing places this page higher for the next one looking for answers to these questions or variations therefor...
Working from git version 1.8.3.1; `git clone -c core.askPass $echo url/or/path/to/git/repo` The configuration [`core.askPass`](https://git-scm.com/docs/gitcredentials) works by passing the control of handling credentials to the aforementioned program. However since `$echo` cant do anything except output, the clone attempt promptly fails and respective bash redirection applies. This code is only invoked in the event that the git repository happens to be private, and will pipe error output stating that authentication failed for the particular repository. You can test this against the `https://github.com/git/git` public repository against a private repository you know about. To sweeten the deal, you wouldn't even need to reference a program like `echo` in the first place. Simply passing git configuration `-c core.askPass` with no following input would still cause failure in the event the repository happens to be private as the code will not know what program to offload credential handling to. While this is certainly an older and simpler method than the others mentioned here, I do not know if it will have the same effect in older versions of git.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
If you are using ssh authentication, and on linux, then you can create an ssh command replacement to disable this. Create a file called "sshnoprompt.sh" with: `ssh -oBatchMode=yes $@` Make this file executable with `chmod +x sshnoprompt.sh` Then when starting git: `GIT_SSH="sshnoprompt.sh" git clone foo@dummyserver:not_a_repo` And it will not allow any interactive git prompts or questions - it shouldn't be able to ask the user for anything.
Working from git version 1.8.3.1; `git clone -c core.askPass $echo url/or/path/to/git/repo` The configuration [`core.askPass`](https://git-scm.com/docs/gitcredentials) works by passing the control of handling credentials to the aforementioned program. However since `$echo` cant do anything except output, the clone attempt promptly fails and respective bash redirection applies. This code is only invoked in the event that the git repository happens to be private, and will pipe error output stating that authentication failed for the particular repository. You can test this against the `https://github.com/git/git` public repository against a private repository you know about. To sweeten the deal, you wouldn't even need to reference a program like `echo` in the first place. Simply passing git configuration `-c core.askPass` with no following input would still cause failure in the event the repository happens to be private as the code will not know what program to offload credential handling to. While this is certainly an older and simpler method than the others mentioned here, I do not know if it will have the same effect in older versions of git.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
If you are using ssh authentication, and on linux, then you can create an ssh command replacement to disable this. Create a file called "sshnoprompt.sh" with: `ssh -oBatchMode=yes $@` Make this file executable with `chmod +x sshnoprompt.sh` Then when starting git: `GIT_SSH="sshnoprompt.sh" git clone foo@dummyserver:not_a_repo` And it will not allow any interactive git prompts or questions - it shouldn't be able to ask the user for anything.
Depending on how you're running git, redirecting stdin or stdout so that they are not connected to terminals will stop git from prompting for details and just cause it to error. This would also allow you to surface errors (or at least logs) to the webservice.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
How to *skip*, *ignore* and/or *reject* git credentials prompts =============================================================== The answers above only worked partly for me when using Git-for-Windows: *two* different applications there were vying for my attention from the automated git pull/push scripts: * git-credentials-manager (developed by the GfW team AFAICT; has a clean, grey Windows interface look) * another dialog, which' ancestry has some definitely (crappy looking) X-Windows genes. **To shut all of them up**, *without* uninstalling the credentials manager as mentioned in some answers here: <https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows>, here's what now works, sitting on top of the automated (`bash`) shell scripts: ```sh # https://serverfault.com/questions/544156/git-clone-fail-instead-of-prompting-for-credentials export GIT_TERMINAL_PROMPT=0 # next env var doesn't help... export GIT_SSH_COMMAND='ssh -oBatchMode=yes' # these should shut up git asking, but only partly: the X-windows-like dialog doesn't pop up no more, but ... export GIT_ASKPASS=echo export SSH_ASKPASS=echo # We needed to find *THIS* to shut up the bloody git-for-windows credential manager: # https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654 export GCM_INTERACTIVE=never ``` What did NOT work ----------------- * All the incantations of `git config credential.modalprompt false` -- mentioned as a solution in answers to that linked SO question. *no dice* for me. * fiddling with that `GIT_SSH_COMMAND` environment variable: nothing worked but keeping it as I suspect it'll kick in when running this stuff on a Linux box instead of Windows. * `GIT_TERMINAL_PROMPT=0`: *no worky either*. Kept it in for the same reason, but *no dice* on Windows. Oh, and *uninstalling* the git credentials manager as suggested in other answers in that SO link was decided a **no go** option as it would definitely impact other repository trees where this thing *may* be useful one day. Though it was considered for a bit, before I decided against doing this. What DID work ------------- * messing with those two `*_ASKPASS` env.vars., oddly enough shut up the 'X-Windows looking' login prompt on (automated) `git push`. Yay! * `GCM_INTERACTIVE=never` was the magic ingredient to finally shut up that git-for-windows credential manager dialog. Thanks to that particular answer (<https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654>), which isn't near the top of the list, but definitely was the most important one for my case. My git version -------------- ``` $ git --version git version 2.30.1.windows.1 ``` ### Parting note `<rant>` Been looking for this info on-and-off for years: this time apparently I was lucky and maybe persevered longer(?), wading through the zillion pages yakking about *setting up* your credentials: google clearly is *not* intelligent. At least it does not listen very well to minority questions, that's for sure. `</rant>` The title is added in hopes that google indexing places this page higher for the next one looking for answers to these questions or variations therefor...
Depending on how you're running git, redirecting stdin or stdout so that they are not connected to terminals will stop git from prompting for details and just cause it to error. This would also allow you to surface errors (or at least logs) to the webservice.
544,156
When cloning git repositories in automated tools - web front ends, CI systems, sometimes the git clone invocation opens up a prompt asking for the username and password (for example, when cloning a non-existent Github repo or on a new node missing ssh keys). How do I make git just fail (preferably with a sensible error message and exit code) instead of waiting for the server process to give it a username and password?
2013/10/06
[ "https://serverfault.com/questions/544156", "https://serverfault.com", "https://serverfault.com/users/109581/" ]
In git version 2.3 there's an environment variable `GIT_TERMINAL_PROMPT` which when set to `0` will disable prompting for credentials. You can get more info about it in `man git` (after updating to git version `2.3`) or in [this blog post on github](https://github.com/blog/1957-git-2-3-has-been-released). Examples: * `git clone https://github.com/some/non-existing-repo` will prompt for username & password * `GIT_TERMINAL_PROMPT=0 git clone https://github.com/some/non-existing-repo` will fail without prompting for username & password
How to *skip*, *ignore* and/or *reject* git credentials prompts =============================================================== The answers above only worked partly for me when using Git-for-Windows: *two* different applications there were vying for my attention from the automated git pull/push scripts: * git-credentials-manager (developed by the GfW team AFAICT; has a clean, grey Windows interface look) * another dialog, which' ancestry has some definitely (crappy looking) X-Windows genes. **To shut all of them up**, *without* uninstalling the credentials manager as mentioned in some answers here: <https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows>, here's what now works, sitting on top of the automated (`bash`) shell scripts: ```sh # https://serverfault.com/questions/544156/git-clone-fail-instead-of-prompting-for-credentials export GIT_TERMINAL_PROMPT=0 # next env var doesn't help... export GIT_SSH_COMMAND='ssh -oBatchMode=yes' # these should shut up git asking, but only partly: the X-windows-like dialog doesn't pop up no more, but ... export GIT_ASKPASS=echo export SSH_ASKPASS=echo # We needed to find *THIS* to shut up the bloody git-for-windows credential manager: # https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654 export GCM_INTERACTIVE=never ``` What did NOT work ----------------- * All the incantations of `git config credential.modalprompt false` -- mentioned as a solution in answers to that linked SO question. *no dice* for me. * fiddling with that `GIT_SSH_COMMAND` environment variable: nothing worked but keeping it as I suspect it'll kick in when running this stuff on a Linux box instead of Windows. * `GIT_TERMINAL_PROMPT=0`: *no worky either*. Kept it in for the same reason, but *no dice* on Windows. Oh, and *uninstalling* the git credentials manager as suggested in other answers in that SO link was decided a **no go** option as it would definitely impact other repository trees where this thing *may* be useful one day. Though it was considered for a bit, before I decided against doing this. What DID work ------------- * messing with those two `*_ASKPASS` env.vars., oddly enough shut up the 'X-Windows looking' login prompt on (automated) `git push`. Yay! * `GCM_INTERACTIVE=never` was the magic ingredient to finally shut up that git-for-windows credential manager dialog. Thanks to that particular answer (<https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows#answer-45513654>), which isn't near the top of the list, but definitely was the most important one for my case. My git version -------------- ``` $ git --version git version 2.30.1.windows.1 ``` ### Parting note `<rant>` Been looking for this info on-and-off for years: this time apparently I was lucky and maybe persevered longer(?), wading through the zillion pages yakking about *setting up* your credentials: google clearly is *not* intelligent. At least it does not listen very well to minority questions, that's for sure. `</rant>` The title is added in hopes that google indexing places this page higher for the next one looking for answers to these questions or variations therefor...
2,963,436
I have the following: ``` echo time()."<br>"; sleep(1); echo time()."<br>"; sleep(1); echo time()."<br>"; ``` I wrote the preceding code with intention to echo `time()."<br>"` ln 1,echo `time()."<br>"` ln 4, wait a final second and then echo the final `time()."<br>"`. Altough the time bieng echoed is correct when it comes to the intervals between time(), all echo functions are echoeing after the total of the waiting period/parameters in each sleep function. This is how the script runs: * Excutes. * Waits 2 secons. * echoes 1275540664 1275540665 1275540666 Notice the correct incrementation in `time()` being echoed. My question is why is it not behaving like expected to where it echoes, waits a second, echoes again, waits one final second and then echos the last parameter? I know my question is a little confusing due to my wording, but i will try my hardest to answer any comments regarding this, thanks.
2010/06/03
[ "https://Stackoverflow.com/questions/2963436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/98204/" ]
You have output buffering turned on. It is more efficient for PHP to buffer up output and write it all to the browser in one go than it is to write the output in small bursts. So PHP will buffer the output and send it all in one go at the end (or once the buffer gets to a certain size). You can manually flush the buffer by calling [flush()](http://www.php.net/manual/en/function.flush.php) after each call to `echo` (though I wouldn't recommend this is a "real" app - but then again, I wouldn't recommend calling `sleep` in a regular app, either!).
You can usually use `ob_flush()`, but it's definitely not reliable. And unfortunately, there's no other option.
34,458,383
Sorry if the Question Title is a bit off, couldn't think of something more descriptive. So I have 2 Domains: `aaa.com` and `bbb.com`. I want my second domain `bbb.com` to redirect always to `aaa.com` EXCEPT IF it has a certain path: `bbb.com/ct/:id` Both domains right now hit the same Heroku App. So in my `Application Controller` I guess, or Routes I, have to scan the request URL and if it contains `/ct/:id` let it continue to the controller action, if not redirect to aaa.com. Or can I somehow Set up the the DNS to only redirect if the `ct/:id` is not in the url ? Basically I want to achieve that a User can't navigate the App from `bbb.com` except if the specific url `bbb.com/ct/:id` is present. I'm using GoDaddy as a Registar and have 2 Cnames set up to my Heroku Apps. How do I accomplish this behavior ?
2015/12/24
[ "https://Stackoverflow.com/questions/34458383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1609496/" ]
I prefer to do your redirects in an actual controller and not in the route file so you can write a controller spec for it. ``` # app/controllers/application_controller.rb before_action :redirect_bbb_to_aaa def redirect_bbb_to_aaa if request.host == "http://bbb.com" redirect_to some_aaa_path unless request.url == "http://bbb.com/ct/:id" end end ```
You can create a rack middleware to do the redirects. One such example is here <https://github.com/gbuesing/rack-host-redirect/blob/master/lib/rack/host_redirect.rb> OR Use constraint in routes.rb. Note: I have not tested it. ``` get "*path" => redirect("http://aaa.com"), constraint: lambda { |request| !request.url.match(/ct\/\d/) } ```
28,374,712
I have a class: ``` public class NListingsData : ListingData, IListingData { private readonly IMetaDictionaryRepository _metaDictionary; //Constructor. public NListingsData(IMetaDictionaryRepository metaDictionary) { _metaDictionary = metaDictionary; } //Overridden function from abstract base class public override List<Images> Photos { get { var urlFormat = _metaDictionary.GetDictionary(CommonConstants.ImagesUrlFormat, this.Key); var imgs = new List<Images>(); for (var i = 0; i < PhotosCount; i++) { imgs.Add(new Images { Url = string.Format(urlFormat, this.MNumber, i) }); } return imgs; } set { } } } ``` The metaDictionary is injected by Autofac. I am executing a query with Dapper and I try to materialize NListingsData. This is what I am using: ``` string sqlQuery = GetQuery(predicates); //Select count(*) from LView; select * from lView; //Use multiple queries using (var multi = _db.QueryMultipleAsync(sqlQuery, new { //The parameter names below have to be same as column names and same as the fields names in the function: GetListingsSqlFilterCriteria() @BedroomsTotal = predicates.GetBedrooms(), @BathroomsTotalInteger = predicates.GetBathrooms() }).Result) { //Get count of results that match the query totalResultsCount = multi.ReadAsync<int>().Result.Single(); //Retrieve only the pagesize number of results var dblistings = multi.ReadAsync<NListingsData>().Result; // Error is here } return dblistings; ``` I get the error ``` A parameterless default constructor or one matching signature (System.Guid ListingId, System.String MLSNumber, System.Int32 BedroomsTotal, System.Double BathroomsTotalInteger) is required for CTP.ApiModels.NListingsData materialization ``` Does my class that I use to materialize with dapper must always be parameterless? Now, I could create a simple DataModel then map to my ViewModel. But is that the only way to do it?
2015/02/06
[ "https://Stackoverflow.com/questions/28374712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475882/" ]
Just add an additional private, parameterless, constructor. This will get picked by Dapper.
In F#, add a ``` [<CliMutable>] ``` attribute to your DTO.
203,829
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow. The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?
2013/07/05
[ "https://softwareengineering.stackexchange.com/questions/203829", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/79820/" ]
I would like to point out that Entity Framework (full name: [ADO.NET Entity Framework](http://msdn.microsoft.com/en-us/library/bb399572.aspx)) is an ORM (Object Relational Mapper) that uses ADO.NET under the hood for connecting to the database. So the question "should we use ADO.NET or EF?" doesn't really make sense in that respect. Unless you re-architect your application, adding EF to the mix is simply adding another layer on top of ADO.NET. I sincerely doubt that ADO.NET is the source of your performance problems, however. It sounds like the problem exists in your stored procedures themselves. I think [Luc Franken's comments](https://softwareengineering.stackexchange.com/questions/203829/ado-net-or-ef-for-a-point-of-sale-system#comment398288_203829) are on the right track, though. You need to measure and determine exactly where the delays are happening. Then concentrate on fixing exactly that problem. Anything else is groping around in the dark.
If you are looking for performance stay away from EF. It is the slowest ORM out there and uses a lot of memory to keep the database metadata. Most [benchmarks](http://www.servicestack.net/benchmarks/) out there show that -
203,829
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow. The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?
2013/07/05
[ "https://softwareengineering.stackexchange.com/questions/203829", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/79820/" ]
If you are looking for performance stay away from EF. It is the slowest ORM out there and uses a lot of memory to keep the database metadata. Most [benchmarks](http://www.servicestack.net/benchmarks/) out there show that -
How necessary is it that each transaction require a database call? At what point is the db insertion being performed? Is there one call per transaction or is it inserting with every addition to the order causing a major lag throughout the user's interaction? Can the db call be handled through private HTTP requests to a dedicated server on the client's own LAN? Perhaps a better approach would be to save the transactions in a repository and post them to the server all at once using the Unit of Work pattern that is triggered as soon as there is a pause of more than 5 seconds. Or perhaps the slow client machines could post to a service that can handle the database insertions. What else could be slowing the machine? Is the GUI processor intensive? It's a POS, not a graphic designer's portfolio piece.
203,829
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow. The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?
2013/07/05
[ "https://softwareengineering.stackexchange.com/questions/203829", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/79820/" ]
I would like to point out that Entity Framework (full name: [ADO.NET Entity Framework](http://msdn.microsoft.com/en-us/library/bb399572.aspx)) is an ORM (Object Relational Mapper) that uses ADO.NET under the hood for connecting to the database. So the question "should we use ADO.NET or EF?" doesn't really make sense in that respect. Unless you re-architect your application, adding EF to the mix is simply adding another layer on top of ADO.NET. I sincerely doubt that ADO.NET is the source of your performance problems, however. It sounds like the problem exists in your stored procedures themselves. I think [Luc Franken's comments](https://softwareengineering.stackexchange.com/questions/203829/ado-net-or-ef-for-a-point-of-sale-system#comment398288_203829) are on the right track, though. You need to measure and determine exactly where the delays are happening. Then concentrate on fixing exactly that problem. Anything else is groping around in the dark.
You say you are calling a "lot of stored procedures". If every call includes a seperate trip to the database, that is your performance issue, because trips to the database are always expensive, no matter what they do. You should have one stored procedure to save a transaction. If that procedure has to call other procedures, fine, as long as you don't have to make a seperate trip to the database.
203,829
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow. The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?
2013/07/05
[ "https://softwareengineering.stackexchange.com/questions/203829", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/79820/" ]
I would like to point out that Entity Framework (full name: [ADO.NET Entity Framework](http://msdn.microsoft.com/en-us/library/bb399572.aspx)) is an ORM (Object Relational Mapper) that uses ADO.NET under the hood for connecting to the database. So the question "should we use ADO.NET or EF?" doesn't really make sense in that respect. Unless you re-architect your application, adding EF to the mix is simply adding another layer on top of ADO.NET. I sincerely doubt that ADO.NET is the source of your performance problems, however. It sounds like the problem exists in your stored procedures themselves. I think [Luc Franken's comments](https://softwareengineering.stackexchange.com/questions/203829/ado-net-or-ef-for-a-point-of-sale-system#comment398288_203829) are on the right track, though. You need to measure and determine exactly where the delays are happening. Then concentrate on fixing exactly that problem. Anything else is groping around in the dark.
How necessary is it that each transaction require a database call? At what point is the db insertion being performed? Is there one call per transaction or is it inserting with every addition to the order causing a major lag throughout the user's interaction? Can the db call be handled through private HTTP requests to a dedicated server on the client's own LAN? Perhaps a better approach would be to save the transactions in a repository and post them to the server all at once using the Unit of Work pattern that is triggered as soon as there is a pause of more than 5 seconds. Or perhaps the slow client machines could post to a service that can handle the database insertions. What else could be slowing the machine? Is the GUI processor intensive? It's a POS, not a graphic designer's portfolio piece.
203,829
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow. The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?
2013/07/05
[ "https://softwareengineering.stackexchange.com/questions/203829", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/79820/" ]
You say you are calling a "lot of stored procedures". If every call includes a seperate trip to the database, that is your performance issue, because trips to the database are always expensive, no matter what they do. You should have one stored procedure to save a transaction. If that procedure has to call other procedures, fine, as long as you don't have to make a seperate trip to the database.
How necessary is it that each transaction require a database call? At what point is the db insertion being performed? Is there one call per transaction or is it inserting with every addition to the order causing a major lag throughout the user's interaction? Can the db call be handled through private HTTP requests to a dedicated server on the client's own LAN? Perhaps a better approach would be to save the transactions in a repository and post them to the server all at once using the Unit of Work pattern that is triggered as soon as there is a pause of more than 5 seconds. Or perhaps the slow client machines could post to a service that can handle the database insertions. What else could be slowing the machine? Is the GUI processor intensive? It's a POS, not a graphic designer's portfolio piece.