qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
45,484 | The other day, I ate at a restaurant; the food was fine, and I got to paying the bill. Their payment system went down. They couldn't accept cards; only cash, and I didn't have the cash on me for the bill. In the end, their payments system was down for about 45 minutes, with several diners being forced to wait around. The staff didn't at any time offer a reassurance that if things weren't fixed in a certain period of time, we could just leave.
But it got me thinking to the legality of things - at what point can you just leave? Is it *always* technically illegal in the UK to leave without paying the bill? Could the restaurant just force you to wait until close of business if necessary? What if they still hadn't fixed the payment system by then? | 2019/10/14 | [
"https://law.stackexchange.com/questions/45484",
"https://law.stackexchange.com",
"https://law.stackexchange.com/users/14515/"
] | They can’t hold you there for any period of time, as that would be false imprisonment. You have a legal obligation to pay the bill; however, there is no contract about when your payment is due.
You can leave at any time without paying, so long as you have the intention to pay. You can leave your contact details so there is proof of your intent to pay later. | Leaving contact details and demanding that an invoice will be sent should count as a reasonable intent to settle the billed amount.
In gastronomy, in case one is a regular guest, it is not that uncommon to have debts accumulated by consume paid later (even if this is far more common for beverages).
In such an exceptional situation, where eg. a sign claims CC would be accepted, while this payment gateway is temporarily not available, it should be possible to leave contact information and sign them a certificate of debt, to be payed as soon as technically or personally possible (when traveling, an invoice might be the only way).
In offline situations, one can pay with a signature... all "promissory notes", including bank notes and other signed certificates of debt, are generally a payment promise, often mistaken for "money" (BoE even confirmed that once). The only difference is, that banks are permitted to issue these without the declaration of an ultimatum.
Therefore, after making a reasonable payment promise, one is free to leave the venue. Demanding a bill, which states the outstanding amount, is certainly advised.
Even when "paying" with CC, one does not instantly pay, but one makes a debt contract with the one party and a payment promise to the other party... even if this may meanwhile be fulfilled close to realtime. |
64,288 | I would like to create a small dtmf dialler that connects to a telephone line and dials a single preprogrammed telephone number when a set of contacts closes, how easy is this and how small could this device be? | 2013/04/03 | [
"https://electronics.stackexchange.com/questions/64288",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/21850/"
] | It's fairly easy. You can buy DTMF chips that you can attach a keyboard to and input a number and use "last number redial". I've actually designed one for a track-side telephone that just had one button and called a guy in his signal-box to open the barrier on a track-crossing point.
A couple of issues - you have to draw about 20mA (minimum) from the line to guarantee proper connectivity through to the PBX. You also need to pay-heed to having decent 600ohm return loss although for an autodialler that isn't as important as an actual telephone.
There'll be a few other issues like making sure your circuit is not polarity concious - a bridge rectifier will do that. You also have to, when activating the contact, have a small circuit that uses a FET or BJT for taking the line feed current (equivalent to lifting the hookswitch or handset). This needs a small delay of about 1 second before the dialler is activated.
You'll also need a small battery to keep the DTMF dialler powered during line outages - you don't want to lose the number you've stored etc..
Size - quite small - cigarette pack size is an overkill - matchbox size is pushing it slightly but dependent on the size of the battery. I'll try and find a basic circuit for you. Give me a while....
If all this sounds too daunting then maybe this project is not for you.
Additions/Edit - DTMF dialler available in UK at below GBP£1: -

Here's also a link to a handy page for making your own auto-dialler - I checked the circuit and it looks ok and uses the chip above.
<http://www.nabilkarami.com/projects.php?show=project&id=16> | Simplest way is to interface to an old phone to emulate the off-hook & key presses. Glue in appropriate electronic switches with a 4017 counter and clock and you have an auto dialer. |
16,453,843 | I'm really curious. Is it possible to have a jQuery Ajax post operation send the entire form data, serialized or not, to a MVC 4 method that has specific parameters with the same names as the form's input IDs while excluding elements that do not match?
MVC 4 Controller Method
```
[HttpPost]
public JsonResult DoWork(string companyName, string firstName, string lastName, string email)
{
//.. do stuff and return result...
}
```
HTML
```
<form id="MyForm" method="post">
<input id="CompanyName" name="CompanyName" type="text"/>
<input id="FirstName" name="FirstName" type="text"/>
<input id="LastName" name="LastName" type="text"/>
<input id="Email" name="Email" type="text"/>
<input id="Var1" name="Var1" type="text"/>
<input id="Var2" name="Var2" type="text"/>
</form>
```
jQuery Ajax
```
$.ajax({
type: 'post',
dataType: 'html',
url: '/Controller/DoWork',
data: $('#MyForm').serialize()
});
```
If it's not possible out of the box, does anyone have some basic ideas that I could look into on how to make this happen? I would like to make it 'harder' for someone to figure out my method calls without giving them the exact parameter names and values that are required to make the method work. | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1148554/"
] | >
> Is it possible to have a jQuery Ajax post operation send the entire
> form data, serialized or not, to a MVC 4 method that has specific
> parameters with the same names as the form's input IDs while excluding
> elements that do not match?
>
>
>
Yes it is possible. But you remember that you can still access those posted data via the `Reques` object. You can actually remove all the arguments in your controller method and you can still post data to it. The real benefit of having arguments in a controller method is if the type of the argument is an object - a viewmodel. A viewmodel that has dataannotations so you can do validation. But take note that **it is not required**, it's just a technique.
Another thing to note is if you have something like
```
public ActionResult DoWork(string first, string last, int id, int? id2) {
}
```
and you only pass data for `first` and `last` your post action will cause an exception. The exception will be on the `id` parameter that the controller expect to receive a value. Now if you pass values to `first`, `last` and `id` arguments but leave out `id2`, then no exception will occur as `id2` will have a null value.
So your posted example will work. And you can get the values of `Var1` and `Var2` by doing `Request["Var1"]` and `Request["Var2"]`, if you wishes to get their values. You can ignore them of course. | Ugh I hope you didn't resort to using the accepted answer here as the way to do it. This question is actually a duplicate, and the and the answer here is the preferred way of doing what you want:
[Passing parameters when submitting a form via jQuery in ASP.NET MVC](https://stackoverflow.com/questions/4005639/passing-parameters-when-submitting-a-form-via-jquery-in-asp-net-mvc) |
12,610,098 | I am searching for days how to run in the background a stream Shoutcast whose content / type: **audio / AACP**.
At the moment, I'm getting the run stream using the library [aacdecoder-android](http://code.google.com/p/aacdecoder-android/), but do not understand how to use a service to leave the stream in the background.
Has anyone used something like that?
Code:
**MainActivity:**
```
public class MainActivity extends Activity {
public AACPlayer mp;
private Toast myToast;
private Handler mHandler;
private ImageParser mImageParser;
private WebView publicidadecapa;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Sair");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().toString() == "Sair") {
finish();
}
return super.onOptionsItemSelected(item);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maintab);
mp = new AACPlayer(new RadioCallBack(this));
ProgressBar loading = (ProgressBar) findViewById(R.id.loadingAudio);
loading.setVisibility(View.INVISIBLE);
ImageView playButton = (ImageView) findViewById(R.id.playButton);
playButton.setTag("1");
playButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ImageView playButton = (ImageView) arg0;
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if ( cm.getActiveNetworkInfo() == null || !cm.getActiveNetworkInfo().isConnectedOrConnecting() ) {
if (myToast == null) {
myToast = Toast.makeText(getBaseContext(), "Verifique a conexão com a internet", 5000);
}
myToast.setDuration(5000);
myToast.show();
return;
}
if (playButton.getTag() == "1" && cm.getActiveNetworkInfo().isConnectedOrConnecting() ) {
playButton.setImageResource(R.drawable.btn_menustop);
playButton.setTag("0");
playButton.setVisibility(View.INVISIBLE);
ProgressBar loading = (ProgressBar) findViewById(R.id.loadingAudio);
loading.setVisibility(View.VISIBLE);
((TextView)findViewById(R.id.textView1)).setText("Conectando...");
mp.playAsync( "http://voxsc1.somafm.com:9002/" );
} else if ( playButton.getTag() == "0" ) {
playButton.setVisibility(View.INVISIBLE);
ProgressBar loading = (ProgressBar) findViewById(R.id.loadingAudio);
loading.setVisibility(View.VISIBLE);
playButton.setImageResource(R.drawable.btn_menuplay);
playButton.setTag("1");
mp.stop();
}
}
});
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
SeekBar volumeControl = (SeekBar) findViewById(R.id.volumeControl);
volumeControl.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeControl.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar arg0) {
}
public void onStartTrackingTouch(SeekBar arg0) {
}
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1,0);
if(arg1 == 0) {
((ImageView) findViewById(R.id.imageView2)).setImageResource(R.drawable.ic_volume2);
} else {
((ImageView) findViewById(R.id.imageView2)).setImageResource(R.drawable.ic_volume1);
}
}
});
}
@Override
public void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
if (this.isFinishing()) {
//mp.stop();
}
super.onDestroy();
}
public void onStart()
{
super.onStart();
// your code
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnected())
return true;
return false;
}
/* Abrir em uma nova aba o link da publicidade */
public class MyWebClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//Uri uri = Uri.parse(url);
Context context = view.getContext();
Intent intent = new Intent(context,OpenSiteWebView.class);
Bundle parametros = new Bundle();
parametros.putString("url", url);
intent.putExtras(parametros);
startActivity(intent);
return true;
}
}
}
```
**RadioCallBack:**
```
public class RadioCallBack implements PlayerCallback {
private MainActivity activity;
public RadioCallBack(MainActivity activity) {
super();
this.activity = activity;
}
public void playerException(Throwable arg0) {
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "O stream pode estar offline! Tente novamente mais tarde", 50000).show();
ProgressBar loading = (ProgressBar) activity.findViewById(R.id.loadingAudio);
loading.setVisibility(View.INVISIBLE);
ImageView playButton = (ImageView) activity.findViewById(R.id.playButton);
playButton.setVisibility(View.VISIBLE);
playButton.setImageResource(R.drawable.btn_menuplay);
playButton.setTag("1");
((TextView)activity.findViewById(R.id.textView1)).setText("Pressione PLAY para tocar!");
}
});
}
public void playerPCMFeedBuffer(boolean arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public void playerStarted() {
activity.runOnUiThread(new Runnable() {
public void run() {
ProgressBar loading = (ProgressBar) activity.findViewById(R.id.loadingAudio);
loading.setVisibility(View.INVISIBLE);
ImageView playButton = (ImageView) activity.findViewById(R.id.playButton);
playButton.setVisibility(View.VISIBLE);
((TextView)activity.findViewById(R.id.textView1)).setText("Mais música brasileira");
}
});
}
public void playerStopped(int arg0) {
activity.runOnUiThread(new Runnable() {
public void run() {
activity.mp = null;
activity.mp = new AACPlayer(new RadioCallBack(activity));
ProgressBar loading = (ProgressBar) activity.findViewById(R.id.loadingAudio);
loading.setVisibility(View.INVISIBLE);
ImageView playButton = (ImageView) activity.findViewById(R.id.playButton);
playButton.setVisibility(View.VISIBLE);
((TextView)activity.findViewById(R.id.textView1)).setText("Pressione PLAY para tocar!");
}
});
}
}
``` | 2012/09/26 | [
"https://Stackoverflow.com/questions/12610098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438343/"
] | **before follow please read my edited comments below**
1. Quit XCode
2. Quit Simulator
3. go to all the path in the image and delete all these folders

4. Open simulator and in iOS Simulator menu `Reset content and settings`. Reset it
Start XCode and you should not worry now.
**EDIT**
**I again got issue few days after the error so I tried the steps above but nothing happened
:(, 2nd time i reinstalled the xcode after deleting everything related to xcode and simulator and made a new project. For a clean project application run well but again copying all files from older project in same manner, again faced the same issue. So how i fixed that?**
You might still need to follow the steps above, not sure these works or not. But i tried to find that the issue starts at the time when i was copying files from old project.
While adding files to the new project a dialog box appears to ask location of existing files and if you see `folders` option with 2 `radio buttons` then by default `Create group of any added folder (if needed)` is selected. Everything went well until i did not touch these options.
**Green:** Default,
**Red:** user selected

But problem started appearing again when for a `Resources` folder I used the `2nd radio button` that says, `Create folder references for any added folder`. When I removed this folder reference and cleaned project, application ran well. Adding same folder with `Create group of any added folder (if needed)` option worked also well. Whenever I chose 1st radio button, application showed same issue.

and

I believe you understand [difference between these 2 options](https://stackoverflow.com/a/8851741/362310) i.e. folder colors to `yellow` and folder colors to `blue`! Hope this helps all other people also but it is really frustrating and i request apple to fix this bug ASAP :( :( | I had to go to Product > Schema > Edit Schema
Then in the Run dialog, the Executable dropdown was on None. I changed it to the .app file and it worked! |
1,298,035 | In Perl, if a variable holds the name for another variable, how do I use the first variable to visit the other one?
For example, let
```
$name = "bob";
@bob = ("jerk", "perlfan");
```
how should I use $name to get to know what kind of person bob is?
Although I'm not quite sure, my vague memory tells me it might related to typeglob. | 2009/08/19 | [
"https://Stackoverflow.com/questions/1298035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157300/"
] | See [`perldoc -q "variable name"`](http://faq.perl.org/perlfaq7.html#How_can_I_use_a_vari):
>
> Beginners often think they want to have a variable contain the name of a variable. ...
>
>
>
Short answer: Don't. Long answer: Read the FAQ entry (which is also available on your computer). Longer answer: Read MJD's [Why it's stupid to "use a variable as a variable name"](http://perl.plover.com/varvarname.html) ([Part 2](http://perl.plover.com/varvarname2.html), [Part 3](http://perl.plover.com/varvarname3.html)). | Symbolic references are worth avoiding, but if you really want to use them, they have the same use syntax as regular references: see <http://perlmonks.org/?node=References+quick+reference>. |
8,409 | I'm working with a system where we want to allow users to play around with the date and time if they want, and where reboots may happen arbitrarily. This is fine, except for one thing: if there's a large time jump backwards, the following error appears on reboot:
```
Checking filesystems
IMAGE2: Superblock last mount time (Tue Mar 1 17:32:48 2011,
now = Thu Feb 24 17:34:29 2011) is in the future.
IMAGE2: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY.
(i.e., without -a or -p options)
*** An error occurred during the file system check.
*** Dropping you to a shell; the system will reboot
*** when you leave the shell.
```
…and then the boot hangs waiting for user console input, and even once console access is gained, requires a root password to continue.
This is decidedly less than ideal. Is there any way to either skip the check or force the check to happen automatically on reboot?
Google has only provided help that requires running fsck manually if/when this is hit, which is not what I'm after. Running fsck manually after setting the time doesn't work as the filesystem is still mounted at that point, and just disabling fsck entirely is less than ideal.
I'm using RedHat 6.
**Update**: The solution I'm currently going with is to hack fstab to disable fsck checking on reboot. I'd tried editing the last mount time on the disks using `debugfs`, which works fine for ext3 drives, but appears to fail inconsistently on ext4. | 2011/03/01 | [
"https://unix.stackexchange.com/questions/8409",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/2134/"
] | I was going to suggest hacking `e2fsck` to disable the specific checks for a last mount time or last write times in the future. These are defined in [problem.c](http://git.kernel.org/?p=fs/ext2/e2fsprogs.git;a=blob_plain;f=e2fsck/problem.c;hb=HEAD) / [problem.h](http://git.kernel.org/?p=fs/ext2/e2fsprogs.git;a=blob_plain;f=e2fsck/problem.h;hb=HEAD), and used in [super.c](http://git.kernel.org/?p=fs/ext2/e2fsprogs.git;a=blob_plain;f=e2fsck/super.c;hb=HEAD). But in looking, I discovered that E2fsprogs 1.41.10 adds a new option to `/etc/e2fsck.conf` called **broken\_system\_clock**. This seems to be exactly what you need, and since you're using Red Hat Enterprise Linux 6, you should have 1.41.12, which includes this option. From the man page:
```
broken_system_clock
The e2fsck(8) program has some hueristics that assume that the
system clock is correct. In addition, many system programs make
similar assumptions. For example, the UUID library depends on
time not going backwards in order for it to be able to make its
guarantees about issuing universally unique ID’s. Systems with
broken system clocks, are well, broken. However, broken system
clocks, particularly in embedded systems, do exist. E2fsck will
attempt to use hueristics to determine if the time can no tbe
trusted; and to skip time-based checks if this is true. If this
boolean is set to true, then e2fsck will always assume that the
system clock can not be trusted.
```
Yes, the man page can't spell "heuristics". Oops. But presumably the code works anyway. :) | I doubt there's a way to remove this check specifically, short of modifying the source code. Ignoring all errors from fsck sounds dangerous, what if there was some other problem?
Therefore I'll suggest the following workaround: change the boot scripts to set the system date to some time in the future (say 2038-01-18 on a 32-bit machine) just before running fsck, and read it back from the hardware clock afterwards (`hwclock --hctosys`, with more options as needed depending on your hardware and use of GMT in the hardware clock.) |
923,384 | I've read a bunch of documentation on installers and haven't come across anything good that explains the underlying concepts. Most of the installer software I've come across is based on the same "database" like structure that I just don't understand at all.
All of the documentation that comes with the various products - i.e. WiX, InstallAware, Wise, InstallShield etc expect that you understand these underlying concepts [which I just don't get] in order to follow what they're talking about.
Can anyone point me in the direction of documentation that explains the concepts of software installers so that the software documentation actually makes sense? | 2009/05/28 | [
"https://Stackoverflow.com/questions/923384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/53119/"
] | I recommend the following feeds:
<http://blog.deploymentengineering.com/feeds/posts/default>
<http://forum.installsite.net/newsfeed.php>
<http://msmvps.com/blogs/installsite/rss.aspx>
<http://robmensching.com/blog/Rss.aspx>
<http://support.acresso.com/rss/acresso_is.xml> | If your install needs are not terribly complex, I would suggest trying out InnoSetup. I used it on a suite of windows applications installers a few years ago and had no complaints. Much simpler than InstallShield and MSI, but your mileage may vary.
I am not in any way affiliated with InnoSetup. |
3,016,701 | So. I'm using V2010 release on Windows 7.
And it doesn't attach automatically. How can I enable to auto attach?
Thanks in advance. | 2010/06/10 | [
"https://Stackoverflow.com/questions/3016701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140634/"
] | Make sure you do that with VS2010 unloaded, otherwise the setting gets overwritten upon exit to zero again. | In the web application project properties on the web tab check the "asp.net" in debugger section. It hepls me. |
19,603,998 | I want to add multiple items/rows in SQLite using single insert query,
```
insert into suppliers (supoliers_no,supply_name,city,phone_no)
values (1,'Ali','amman',111111), (2,'tariq','amman',777777), (3,'mohmmed','taiz',null);
```
Is it possible using Sqlite? | 2013/10/26 | [
"https://Stackoverflow.com/questions/19603998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922391/"
] | This is possible but the way to do this is different in SQLITE,
Try this...
```
insert into myTable (mycol1,mycol2)
select aValue as mycol1,anotherValue as mycol2
union select moreValue,evenMoreValue
union...
```
in your case it will be as,
```
INSERT INTO suppliers
SELECT 1 AS supoliers_no, 'Ali' AS supply_name, 'amman' AS city, 111111 AS phone_no
UNION SELECT 2 , 'tariq' , 'amman' , 77777
UNION SELECT 3 , 'mohmmed' , 'taiz', null
```
**Remember** null in small letter do work in SQL Lite as I have created this table and `phone_no` column in INT in my case | Inserting multiple records with a single INSERT statement is supported only in SQLite [3.7.11](http://www.sqlite.org/releaselog/3_7_11.html) and later.
On earlier versions, you have to use `INSERT ... SELECT ...` with `UNION ALL`, or use multiple statements. |
439,177 | How do I calculate sum of a finite harmonic series of the following form?
$$\sum\_{k=a}^{b} \frac{1}{k} = \frac{1}{a} + \frac{1}{a+1} + \frac{1}{a+2} + \cdots + \frac{1}{b}$$
Is there a general formula for this? How can we approach this if not? | 2013/07/08 | [
"https://math.stackexchange.com/questions/439177",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/76116/"
] | **This answer is more for additional information and as an exercise for myself to remember Gosper's algorithm.**
There is no nice closed formula for this. By nice we can take *hypergeometric functions* (functions $f(n)$ such that $f(n+1)/f(n)$ is a rational function) or even finite sums of hypergeometric functions. If there were, in particular you would get a nice closed formula for $H(n):=1+1/2+1/3+...+1/n$.
Assume that $H(n)$ is hypergeometric. Then $1/n=H(n)-H(n-1)$, i.e. $$nH(n)-nH(n-1)=1$$.
Now, since we are assuming $H$ is hypergeometric we get $$nH(n)=\frac{H(n)}{(H(n+1)-H(n))}=\frac{1}{\frac{H(n+1)}{H(n)}-1},$$
which should be rational. So, we are looking for a rational function $K(n):=nH(n)$ such that
$$(n-1)K(n)-nK(n-1)=n-1.$$
Observe that if $a\neq1$ is a pole of $K(n)$ then it would have to be a pole of $K(n-1)$. If $1$ is a pole of $K$ then $-2$ is a pole of $K(n-1)$ and therefore also a pole of $K$. This is impossible because it implies $K$ has infinitely many poles. Therefore $K$ is a polynomial. But there are no polynomials satisfying this equation. In fact, assume $K(n)=an^r+bn^{r-1}+\ldots$. Plug it in the equation and you get that the leading term of the left hand side is $(r-1)an^r$. Therefore we get that $r=1$ and $(r-1)a=1$ from imposing that it should be equal to the right hand side $n-1$. But these equations are impossible.
Thus $H$ is not an hypergeometric function. Further arguments show that it can't be either a finite sum of hypergeometric functions. | The formula for sum of H.P. remained unknown for many years, but now I have found the formula as an infinite polynomial.
The formula or the infinite polynomial which is
equal to the sum of th H.P. $\frac{1}{a} + \frac{1}{a+d} + \frac{1}{a+2d} + \frac{1}{a+3d} + ........$ is :-
$Sum of H.P. = (1/a) [1 + \frac{1}{1×(1+b)}(x-1) - \frac{b}{(2×(1+b)(2+b)}(x-1)(x-2) + \frac{b^2}{3×(1+b)(2+b)(3+b)}(x-1)(x-2)(x-3) - \frac{b^3}{4×(1+b)(2+b)(3+b)(4+b)}(x-1)(x-2)(x-3)(x-4) + \frac{b^4}{5×(1+b)(2+b)(3+b)(4+b)(5+b)}(x-1)(x-2)(x-3)(x-4)(x-5) - .....]$
Here, $b=d/a$ and $x$ is the number of terms upto
which you want to find the sum of the H.P.
Substitute any natural number in place of x and
get the sum of the harmonic series.
For more information, visit <https://facebook.com/ElementaryResearchesinMathematics>.
I have not provided any proof here since that will be a very difficult task at this platform. |
2,702,041 | In particular, I'm interested in the property that the surface area of a sphere in D dimensions gets concentrated near the equator. I know it can be shown with some integrals, for example done in Section 1.2.5 [here](https://www.cs.cmu.edu/~venkatg/teaching/CStheory-infoage/chap1-high-dim-space.pdf).
What I want to know, if anyone can give me a short *relatively* verbal argument for this. It's a point that I need to make in a talk that I'm giving, and I'd like to give some intuition for why this result is true, but going into an integral or something would detract away too much from my main content. A little math is fine (It's going to be an applied math/physics audience), but something which wont take up too much time to explain if possible.
Thanks. | 2018/03/21 | [
"https://math.stackexchange.com/questions/2702041",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/162285/"
] | If $(x\_1,\dots,x\_D)$ is far from the equator, then $|x\_D|$ is large. Let $P(C)$ denote the fraction of the sphere where $|x\_D|>C$. Then by symmetry, $P(C)$ also gives the fraction of the sphere where $|x\_k|>C$ for any $k<D$. But any given point can have at most $\left\lfloor \frac{1}{C^2}\right \rfloor$ coordinates with absolute value larger than $C$, so the regions for all the coordinates can cover the sphere at most $\left\lfloor \frac{1}{C^2}\right \rfloor$ times. As there are $D$ such regions, we have
$$
P(C) \leq \frac{1}{D} \left\lfloor \frac{1}{C^2}\right \rfloor
$$
which goes to $0$ as $D \to \infty$ for any fixed $C$. | I dont know much about higher dimensional spheres so I'll leave some links here for reference which are pretty good.
[A Breakthrough in Higher Dimensional Spheres | Infinite Series | PBS Digital Studios](https://www.youtube.com/watch?v=ciM6wigZK0w)
[Thinking visually about higher dimensions- 3Blue1Brown](https://www.youtube.com/watch?v=zwAD6dRSVyI)
[Strange Spheres in Higher Dimensions - Numberphile](https://www.youtube.com/watch?v=mceaM2_zQd8) |
28,916,917 | I need to send a SQL query to a database that tells me how many rows there are in a table. I could get all the rows in the table with a SELECT and then count them, but I don't like to do it this way. Is there some other way to ask the number of the rows in a table to the SQL server? | 2015/03/07 | [
"https://Stackoverflow.com/questions/28916917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4229007/"
] | ```
select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
and index_id in (0,1)
```
is very fast but very rarely inaccurate. | Use This Query :
```
Select
S.name + '.' + T.name As TableName ,
SUM( P.rows ) As RowCont
From sys.tables As T
Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
( T.is_ms_shipped = 0 )
AND
( P.index_id IN (1,0) )
And
( T.type = 'U' )
Group By S.name , T.name
Order By SUM( P.rows ) Desc
``` |
45,979,007 | In the answer to this question I don't understand why the `input.nextInt` has a newline character as a leftover.
[Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) | 2017/08/31 | [
"https://Stackoverflow.com/questions/45979007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8542239/"
] | The answer is quite simple:
`Scanner#nextInt()` reads the next integer but not the newline (`ENTER`) the user presses to submit the integer.
To understand this you must know that everything you type will be written to a buffer, from which the `Scanner` methods try to read from.
---
Regard the following example:
```
System.out.println("Enter a number: ");
int i = scanner.nextInt();
System.out.println("Enter a line: ");
String l = scanner.nextLine();
```
What will happen:
* The user sees `Enter a number:` and will press `17` and `ENTER`.
* The scanner will read the `17` but leave the newline of the `ENTER`.
* The program will write `Enter a line:` but the scanner will read the newline of the `ENTER` instead of waiting for input. | This is purly a design decision, the reason `nextInt()` doesn't consume the newline character, is because there may be some other tokens that haven't been parsed yet, it would be most inappropriate to assume there's nothing left in the string, and consume the newline char.
For instance, you are given the following input
`123 123 \n`
Calling `nextInt()` will result in the following string left in the buffer
`123 \n`
Calling `nextInt()`again,
`\n` |
58,674,154 | Can you tell me, please?
Why does the mysql2 value substitution not work inside the IN operator?
I do this, but nothing works.
Only the first character of the array is being substituted (number 6)
```
"select * from products_categories WHERE category_id IN (?)", [6,3]);
```
You can do it like this, of course:
IN(?,?,?,?,?,?,?,?,?,?) [6,3,1,1,1,1,1,1,1,1,1]
But that's not right, I thought that the IN should be automatically substituted from an array =( | 2019/11/02 | [
"https://Stackoverflow.com/questions/58674154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10971604/"
] | The `equals` method you're using is comparing references, which is basically the same thing as doing `==` between them (or between any other reference types). Both references are considered equal if they point to the same object in memory. Since you're creating two individual arrays of integers, they are two different objects at two different memory locations. That's why you always get `false` as the result.
To compare arrays element-wise, use the `Arrays.equals` method like this:
```
@Override
public boolean equals(Object obj) {
if(obj instanceof Example)
{
Example ex=(Example)obj;
if(Arrays.equals(ex.getA(), getA())&& Arrays.equals(ex.getB(), getB()))
return true;
if(Arrays.equals(ex.getA(), getB())&& Arrays.equals(ex.getB(), getA()))
return true;
return false;
}
return false;
}
}
``` | When you are using `.equals()` on two arrays, it will do the same thing as `==`, which is to check if the references are the same. Because they are not, it will return `false`. You want to use [`java.util.Arrays.equals(A, ex.getA())`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#equals(int%5B%5D,int%5B%5D)). |
17,537,871 | I run into a very strange problem when using macvim.
Env:
OS: OS X Mountain Lion,
Macvim: <https://github.com/b4winckler/macvim/archive/snapshot-66.tar.gz>
Steps to reproduce:
1. connecting my labtop to a extra display.
2. open macvim
3. disconnecting labtop from extra display
4. restart macvim
I got the following errors:
```
2013-07-09 07:53:05.458 MacVim[9400:707] Error (1007) creating CGSWindow on line 259
2013-07-09 07:53:05.460 MacVim[9400:707] (
0 CoreFoundation 0x00007fff8f3d8b06 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff85b723f0 objc_exception_throw + 43
2 CoreFoundation 0x00007fff8f3d88dc +[NSException raise:format:] + 204
3 AppKit 0x00007fff88215b49 _NSCreateWindowWithOpaqueShape2 + 655
4 AppKit 0x00007fff88214340 -[NSWindow _commonAwake] + 2002
5 AppKit 0x00007fff882c475b -[NSWindow _makeKeyRegardlessOfVisibility] + 88
6 AppKit 0x00007fff882c46c5 -[NSWindow makeKeyAndOrderFront:] + 25
7 MacVim 0x0000000108097192 -[MMWindowController presentWindow:] + 150
8 Foundation 0x00007fff8d1b9d05 __NSFireDelayedPerform + 358
9 CoreFoundation 0x00007fff8f395804 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
10 CoreFoundation 0x00007fff8f39531d __CFRunLoopDoTimer + 557
11 CoreFoundation 0x00007fff8f37aad9 __CFRunLoopRun + 1529
12 CoreFoundation 0x00007fff8f37a0e2 CFRunLoopRunSpecific + 290
13 HIToolbox 0x00007fff8f6bceb4 RunCurrentEventLoopInMode + 209
14 HIToolbox 0x00007fff8f6bcc52 ReceiveNextEventCommon + 356
15 HIToolbox 0x00007fff8f6bcae3 BlockUntilNextEventMatchingListInMode + 62
16 AppKit 0x00007fff8820c533 _DPSNextEvent + 685
17 AppKit 0x00007fff8820bdf2 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
18 AppKit 0x00007fff882031a3 -[NSApplication run] + 517
19 AppKit 0x00007fff881a7bd6 NSApplicationMain + 869
20 libdyld.dylib 0x00007fff8d5ff7e1 start + 0
21 ??? 0x0000000000000003 0x0 + 3
```
does anyone know how to fix it? any suggestion will be appreciated. | 2013/07/08 | [
"https://Stackoverflow.com/questions/17537871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1877703/"
] | The accepted answer didn't work for me by itself, but rebooting after deleting the plist files worked. | There's no need to reboot or delete entire plist files. This command clears the troublesome property:
```
$ defaults delete org.vim.MacVim MMTopLeftPoint
``` |
8,261,971 | I want to read XML Messages from a Message Queue in a C# WPF Application. Messages are saved into the Queue by a Navision codeunit. Firstly, I am not really sure if the messages that are saved in the Queue are usable, because they are in some sort of hexadecimal format which looks like this:
```
FF FE 3C 00 3F 00 78 00 ÿþ<.?.x.
6D 00 6C 00 20 00 76 00 m.l. .v.
65 00 72 00 73 00 69 00 e.r.s.i.
6F 00 6E 00 3D 00 22 00 o.n.=.".
31 00 2E 00 30 00 22 00 1...0.".
20 00 65 00 6E 00 63 00 .e.n.c.
6F 00 64 00 69 00 6E 00 o.d.i.n.
67 00 3D 00 22 00 55 00 g.=.".U.
54 00 46 00 2D 00 31 00 T.F.-.1.
36 00 22 00 20 00 73 00 6.". .s.
74 00 61 00 6E 00 64 00 t.a.n.d.
61 00 6C 00 6F 00 6E 00 a.l.o.n.
...
```
Receiving the messages from the queue already works, but somehow the format is wrong because I get this Runtime Exception "Invalid Operation Exception: Cannot deserialize the message passed as an argument. Cannot recognize the serialization format."
I am using this code to read the messages:
```
public MainWindow()
{
InitializeComponent();
mqCustomerData = new MessageQueue(@".\private$\customerData");
mqCustomerData.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
mqCustomerData.ReceiveCompleted += new ReceiveCompletedEventHandler(mqCustomerData_ReceiveCompleted);
mqCustomerData.BeginReceive(new System.TimeSpan(0, 0, 0, 30));
}
private void mqCustomerData_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e)
{
Message m = new Message();
m.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
m = mqCustomerData.EndReceive(e.AsyncResult);
string text = (string)m.Body;
}
```
I've searched for the problem but not found a useful solution, only found postings of other users experiencing the same problem, like here: <http://www.webmasterworld.com/microsoft_asp_net/4119362.htm>
I hope someone of you out there can help me with this :) | 2011/11/24 | [
"https://Stackoverflow.com/questions/8261971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/825928/"
] | In competent\_tech's answer, no overload for
```
Encoding.Unicode.GetString(m.Body);
```
takes a string argument.
If this is the approach that you want to use, you need to convert the string to a byte array -
```
byte[] arr;
using(MemoryStream ms = new MemoryStream())
{
m.BodyStream.Position = 0;
m.BodyStream.CopyTo(ms);
arr = ms.ToArray();
}
string s = Encoding.Unicode.GetString(arr, 0, arr.Length);
``` | It looks like the data is little-endian UTF-16 since the data starts with FF FE.
You need to decode the string using something like:
```
string text = Encoding.Unicode.GetString(m.Body);
``` |
31,662,225 | I can't figure out how to click on the sign-in element (from UI Automator):
[](https://i.stack.imgur.com/FdHdr.png)
Keep in mind there are multiple TextView-s with 0-index in the UI. Can I use its text ("Sign in") or its unique ListView/TextView path somehow? | 2015/07/27 | [
"https://Stackoverflow.com/questions/31662225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817550/"
] | There are two ways to do it:
First, try this:
```
driver.findElementByName("SignIn").click();
```
Second, try this:
```
public void tap(int index){
List<WebElement> li = driver.findElementByClass("PUT YOUR class name");
li.get(0).click();
}
``` | Try this:
```
driver.findElement(By.xpath("//*[@class='android.widget.TextView' and @index='0']")).click();
```
**OR**
```
driver.findElement(By.name("Sign In")).click();
```
Ideally Both should work. |
78,211 | My understanding is that in a private blockchain, the participating nodes verify and agree that the block is valid and only then add it to the blockchain.In this scenario, are consensus protocols (such as RAFT, PAXOS, etc.) needed? Am I missing anything here? | 2018/08/14 | [
"https://bitcoin.stackexchange.com/questions/78211",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/86357/"
] | **TL;DR** Yes, consensus protocols are always needed in distributed systems where there could be multiple writers to the same data. When it is possible for multiple participants to simultaneously update their local state, it can result in two inconsistent versions which can't be merged together into a globally consistent state.
In the context of a blockchain, publishing a block is analogous to reading and writing to balances, and we wish to enforce the constraint that every account `balance >= 0` to prevent double spending.
[](https://i.stack.imgur.com/y1wtH.png)
Imagine that in the ledger state of block 4, I had 10 coins. Then in Branch A, I sent Alice 8 coins, but in Branch B I sent Bob 8 coins. If we tried to reconcile these two updates into one state then either I would have a balance of -6 coins, violating the `balance >= 0` constraint, or coins would have to be illegally created.
Consensus algorithms are designed to ensure that each node has a valid state consistent with other nodes. As explained by [CAP theorem](https://en.wikipedia.org/wiki/CAP_theorem), during a network partition a consensus algorithm must either make the service unavailable (Read Only) or allow for the two partitions to potentially become inconsistant. This means that when designing or choosing a consensus algorithm, one must decide between either consistency of the data (e.g. preventing double spend) or availability (e.g. making a transaction).
Nakamoto consensus prioritizes availability such that during a network partition it will continue to process transactions, and after a network partition, the global state will eventually be consistent. It quantifies each state's total proof of work to decide which state is the correct state. If our node had previously only observed branch A but then received the blocks from branch B, it would calculate the amount of work done in each state to decide which branch to accept. This means that during a network partition, the state is still available to be updated at the expense of it becoming inconsistent. After the network partition is resolved, the inconsistent states are resolved by [reverting](https://en.bitcoin.it/wiki/Chain_Reorganization) some of the updates and applying the ones that lead to a state with more proof of work.
Other consensus protocols such as the proof of stake variant used in Tendermint will prioritize consistency, meaning that during a network partition attempts to update the state may fail, making the service unavailable. To ensure consistent updates to the state (i.e. creating a block) nodes that controll at least 2/3 of the stake, must agree to a proposed block within a timeout period. If too little stake agrees to the proposed update, it will fail and revert and a new proposal will begin. This is somewhat comparable to a [2 phase commit](https://en.wikipedia.org/wiki/Two-phase_commit_protocol), but differs in that it can tolerate the failure of nodes controlling up to 1/3 of the stake.
Even in a trusted environment where all machines are behaving correctly, inconsistent states can arise due to network latency, as asynchronous messaging is comparable to short-lived network partitions. Keeping state consistent becomes somewhat more difficult where we have more complex constraints to uphold (e.g. ensuring consistent smart contract execution)
Other non-blockchain private distributed systems, must make the same trade-off between Consistency and Availability, [Google's BigTable](https://cloud.google.com/bigtable/docs/replication-overview) maintains availability and replicates updates to other nodes making it eventually consistent throughout their data centers, for coordination within a BigTable cluster it relies on a fault tolerance lock distributed service named [Chubby](https://static.googleusercontent.com/media/research.google.com/en//archive/bigtable-osdi06.pdf) which uses paxos during leader elections. However, It seems that due to the reliability of Google's private WAN (>99.9995% availability) and [very accurate time-keeping](https://www.abhishek-tiwari.com/rise-of-truetime/), they have also built [Spanner](https://storage.googleapis.com/pub-tools-public-publication-data/pdf/45855.pdf), the accuracy of their timestamps allow for updates to be ordered (or delayed if there is uncertainty about the order) such that an application's view of the data is consistent with the application's constraints and other invariants.
I highlight CAP theorem to explain how Nakamoto Consensus will always be available but subject to the eventual consistency, potentially allowing for a [51% attack](https://blog.coinbase.com/ethereum-classic-etc-is-currently-being-51-attacked-33be13ce32de). Other consensus protocols can provide finalization, but may not always be available opening them up to a system-halting DDoS attack. In the context of a private system, control of the hardware means that the distributed system can be virtually always available and shielded from DoS attacks, leading companies like Google to prefer the provision of [consistency](https://cloud.google.com/blog/products/gcp/why-you-should-pick-strong-consistency-whenever-possible). | Yes consensus is needed and for the consensus RAFT ,PAXOS is used for general node failure.If their is malicious node Byzantine Fault Tolerance can be used.But POW isn't used in case of private blockchain as the participating users are known. |
9,649,047 | I'm trying to create a backbone router that can match optional parameters.
Consider the following code:
```
routes: {
'/jobs' : 'jobs',
'/jobs/p:page' : 'jobs',
'/jobs/job/:job_id' : 'jobs',
'/jobs/p:page/job/:job_id' : 'jobs'
}
jobs: function(page, job_id){
// do stuff here ....
}
```
If I navigate to URL abc.com/**#/jobs/p104/** the **page** parameter will be **104**. However, if navigate to abc.com/**#/jobs/job/93**, the **job\_id** parameter is **undefined** but the **page** parameter is **93**.
So Backbone's router basically matches the routes hash parameters by order and not by name.
I know the solution would be to use a \*splat and split the parameters with regex, but I can't seem to get the regex part to work (my regex is pretty rusty). Can someone please help?
If there's a better solution than using \*splat, can someone please share? | 2012/03/10 | [
"https://Stackoverflow.com/questions/9649047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instead of messing with regexes it would be easier and less error prone just to have a second function. You will probably have to bindAll this in an initialize function for this.jobs to work.
```
routes: {
'/jobs' : 'jobs',
'/jobs/p:page' : 'jobs',
'/jobs/job/:job_id' : 'jobsId',
'/jobs/p:page/job/:job_id' : 'jobs'
},
jobs: function(page, job_id){
// do stuff here ....
},
jobsId: function(page, job_id){
this.jobs(undefined, job_id
}
``` | If you're going to be doing a lot of these, you might glance at [this pattern](http://blog.rjzaworski.com/2011/12/regex-routing-with-backbone-js/) for wrapping them up tidily. For just these, though, the following regexs ought to do it:
```
/\/jobs\/p(\d+)/ => /jobs/pXXX
/\/jobs\/p(\d+)\/job\/(\d+)/ => /jobs/pXXX/job/XXX
```
You can then use `String.match` with the splats you retrieve to extract the url fragments in question. Using strings in place of a `splat` variable:
```
var matches = '/jobs/p18'.match(/\/jobs\/p(\d+)/);
var page = matches[1];
var matches = '/jobs/p4/job/6/'.match(/\/jobs\/p(\d+)\/job\/(\d+)/);
var page = matches[1];
var job = matches[2];
``` |
8,469,668 | I tried implementing this for a radio button
```
<form>
<input name="rad" type="radio" value="Yes" onclick="this.form['sub'].disabled=false"> Agreement
<br>
<br>
<input type="submit" name="sub" value="Submit" disabled>
</form>
```
The problem is I need a hyperlink next to Agreement so that people can click and see it then click and proceed.
but when I try adding a hyperlink to the word agreement the Button also gets hyperlinked to the same url.
Also I need to redirect after button is clicked to a different page
How can I accomplish this | 2011/12/12 | [
"https://Stackoverflow.com/questions/8469668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343040/"
] | A compatible implementation with `save_virtual_workbook` deprecated since version 2.6:
```py
from io import BytesIO
from tempfile import NamedTemporaryFile
def save_virtual_workbook(workbook):
with NamedTemporaryFile() as tf:
workbook.save(tf.name)
in_memory = BytesIO(tf.read())
return in_memory.getvalue()
``` | ```
from openpyxl import Workbook
from io import BytesIO
rows = [[1,2], [3,4]]
book = Workbook()
sheet = book.active
for row in rows:
sheet.append(row)
io = BytesIO
book.save(io)
content = io.getValue()
return Response(
content,
mimetype=magic.from_buffer(content, mime=True),
headers={
'Content-Disposition': 'attachment;filename=' + 'test.xlsx'}
)
``` |
9,632,229 | >
> **Possible Duplicate:**
>
> [declaring a const instance of a class](https://stackoverflow.com/questions/4674332/declaring-a-const-instance-of-a-class)
>
> [Why does C++ require a user-provided default constructor to default-construct a const object?](https://stackoverflow.com/questions/7411515/why-does-c-require-a-user-provided-default-constructor-to-default-construct-a)
>
>
>
My program like this:
```
class c
{
};
int main()
{
const c a;
return 0;
}
```
when I compile it using g++, it prompt:
```
main.cpp:10:7: note: ‘const class c’ has no user-provided default constructor
```
Why, this is just an empty class and do not do anything, why I have to provide a user-provided constructor. | 2012/03/09 | [
"https://Stackoverflow.com/questions/9632229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1253826/"
] | You've got sort of a recursive doubleloop there.
Try this:
```
$(function(){
var a = setInterval("getSuggestions()",5000);
});
function getSuggestions(){
var url = $("#baseUrl").val() + '/placement/suggestions/x-fetch-suggestions';
var data ={}
var result = myAjaxJson(data,url); //gets json object via ajax
/* gets object 'sug' and put into #suggestions-list*/
$('#suggestions-list').html(result.sug);
}
``` | Don't use setInterval, use setTimeout. setInterval calls the function every 5 seconds regardless of whether the previous Ajax request completed. setTimeout will wait 5 seconds after the previous Ajax request to start thenext one.:
```
$(function(){
getSuggestions();
});
function getSuggestions(){
var url = $("#baseUrl").val() + '/placement/suggestions/x-fetch-suggestions';
var data ={}
var result = myAjaxJson(data,url); //gets json object via ajax
/* gets object 'sug' and put into #suggestions-list*/
$('#suggestions-list').html(result.sug);
var a = setTimeout("getSuggestions()",5000);
}
``` |
70,012,069 | ok so I have been going at it for a while im making a palindrome program on html for the first time but when I input 111 it says its not a palindrome even tho i went through the while loop with a calc and it should be the same. I checked the outputs by revealing em and
"input" = 111.
"temp" = 0 as it should.
"reversed" tho is equal to infinity lol and idk y any help is appreciated.
```
function Palindrome() {
let input = document.querySelector("#userInput").value;
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) + lastDigit;
temp = (temp / 10);
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
}else {
document.querySelector("#answer").innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}
``` | 2021/11/17 | [
"https://Stackoverflow.com/questions/70012069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10401954/"
] | You're doing floating point division, so `temp` will never be more than 0 until you do many iterations and get floating point underflow. After each iteration it becomes `11.1`, then `1.11`, then `0.111`, `.0111`, and so on. This is multiplying `reversed` by 10 each time, and it eventually overflows to infinity.
Round the number when dividing so that the fraction will be discarded:
```
temp = Math.round(temp / 10);
```
```js
function Palindrome(input) {
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) + lastDigit;
temp = Math.round(temp / 10);
}
if (input == reversed) {
console.log(`This is a Palindrome ${input}`);
} else {
console.log(`This is not a Palindrome ${input} ${temp} ${reversed} `);
}
}
Palindrome(111);
Palindrome(123)
``` | As Barmar explained in his answer about percent division try to git rid of it!
```js
function Palindrome() {
let input = document.querySelector("#userInput").value;
//convert input to number
var temp = +input;//or parseInt(input)
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = reversed * 10 + lastDigit;
temp = Math.floor(temp / 10);//<-- to prevent Infinity
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
} else {
document.querySelector(
"#answer"
).innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}
```
```html
<input type="input" value="" id="userInput">
<input type="button" value="Is Palindrom" onclick="Palindrome()">
<div id='answer'></div>
``` |
41,929,709 | I'm wondering if there is a **shortcut** for VS Code that **highlights** in solution explorer tree current opened file. Like we have in Visual Studio:
```
Alt + Shift + L
``` | 2017/01/30 | [
"https://Stackoverflow.com/questions/41929709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1393225/"
] | Couldn't live with no complete answer, so figured out the following:
**Without a direct keyboard shortcut:**
1. Open the command palette via `Cmd`-`Shift`-`P` (or `Cmd`+`P` then `>`) and type `Files: Reveal Active File in Side Bar`.
2. This reveals the active file in the side bar similar to Visual Studio's `Alt`+`Shift`+`L`
**Then, take the above and map a keyboard shortcut to it:**
3. Open keyboard shortcut preferences file via `Cmd`-`Shift`-`P` followed by `Preferences: Open Keyboard Preferences File`.
4. Add in the following (taking Visual Studio's lead, I've personally mapped it to `Alt`+`Shift`+`L`, but map to what you want).
```js
// Place your key bindings in this file to overwrite the defaults
[
{
"key": "shift+alt+l",
"command": "workbench.files.action.showActiveFileInExplorer",
},
]
```
~~Note that it's not as good as Visual Studio, Atom, etc. in that you can't then navigate with arrow keys in the tree (arrow keys navigate the active file contents), but I guess I'll eventually figure out how to do that.~~
@Tomoyuki Aota points out that you can do the following to navigate with arrow keys:
>
> After Files: Reveal Active File in Side Bar, press Ctrl+Shift+E (Show
> Explorer). After that, I can navigate the files in the explorer by the
> arrow keys.
>
>
> | Try this:
Together with @Rob's correct answer:
```
"explorer.autoReveal": true
```
then `Ctrl`-`Shift`-`E` (Show explorer) focuses that file in the explorer and the `arrow` keys will navigate up/down/left/right like any list. This works even if the explorer is closed prior to the `Ctrl`-`Shift`-`E`.
`Ctrl`-`Shift`-`E` has the added bonus in that it will toggle focus between the highlighted file and its editor as well.
For mac, use `Cmd`-`Shift`-`E` |
14,055 | I was working in a reputable IT company for 2 years, however I took a break of 2 years to pursue a career in Indian Civil Services. I got selected at state level but couldn't make it to Highest post and now I am planning to return to IT.
Please guide on how I can describe my this career gap in the interviews. | 2013/08/29 | [
"https://workplace.stackexchange.com/questions/14055",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/10356/"
] | **Emphasise your strengths**
As always with interviews you should be trying to present yourself in the best light possible.
So when it comes to them asking about your 2 year gap don't just say 'Oh I was meeting personal goals' you want to show what you did and amaze them with the transferable skills you learnt.
**Transferable skills**
For example did you have to communicate a lot with other people? Has this improved your communication abilities? Are you more clear and concise now?
Communication is a skill that is important in every workplace, you will rarely work alone and someone who is able to explain themselves concisely will be a fantastic advantage.
Were you frequently presented with difficult tasks? Did you complete them on time to the best of your abilities?
Showing that you can handle difficult tasks and still give it 100% of your effort shows that you aren't likely to just give up and stop trying if you are presented with difficult tasks whilst working for them. This is definitely a desired quality to have.
Were you presented with conflicts, either in the workplace or with a customer? How did you handle it? Did it go well?
Someone who can remain calm and professional whilst in a conflict of any kind will be a very good trait to have, if you have an example of doing this then definitely bring it to their attention. Someone who isn't going to snap at a client in high pressure situations will be a very valuable person to have.
**Conclusion**
All in all, as long as you can show what you learnt, and show how this has improved you then I can't see it being too much of an issue.
However, on top of this you might want to make sure you have done some sort of training course or tests to bring yourself up to speed. Things change fast in the IT world and 2 years is actually a fairly long time to be out of it. Your biggest challenge probably won't be the 2 year gap, but will be the lack of current knowledge, so make sure you brush up on all of that too to make sure you aren't at a disadvantage! | >
> Please guide on how I can describe my this career gap in the interviews.
>
>
>
I'd go with something like this:
>
> I was working in a reputable IT company for 2 years, however I took a break of 2 years to pursue a career in Indian Civil Services. I got selected at state level but couldn't make it to Highest post and now I am planning to return to IT.
>
>
>
There's no reason to hide your foray into public service, so just be honest about it. Indeed, you might be able to use it to your advantage. Consider looking for IT positions where your interest in and knowledge of government and public policy would be a useful asset. |
8,044,549 | unsure how to go about describing this but here i go:
For some reason, when trying to create a release build version of my game to test, the enemy creation aspect of it isn't working.
```
Enemies *e_level1[3];
e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
e_level1[1] = &Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1);
e_level1[2] = &Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1);
```
Thats how i'm creating my enemies. Works fine when in the debug configuration but when i switch to the release config, it doesn't seem to initialize the enemies correctly.
To me, this seems a bit strange that it works in debug but not in release, any help appreciated on what mostly is what i've done wrong. | 2011/11/08 | [
"https://Stackoverflow.com/questions/8044549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015476/"
] | ```
e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
```
doesn't do what you think it does. If it is the constructor call, it creates a temporary and its address is stored in e\_level1[0]. When e\_level1[1] is initialized e\_level1[0] destructor is probably already called.
You probably want to do
```
Enemies* e_level1[3] =
{
new Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1) ,
new Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1) ,
new Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1)
};
``` | The code initializes the pointers to point to temporary objects that are immediately destroyed. Accessing temporaries that no longer exist through pointers or references is undefined behavior. You want:
```
Enemies *e_level1[3];
e_level1[0] = new Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
e_level1[1] = new Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1);
e_level1[2] = new Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1);
``` |
4,649,639 | How to convert date format to DD-MM-YYYY in C#? I am only looking for DD-MM-YYYY format not anything else. | 2011/01/10 | [
"https://Stackoverflow.com/questions/4649639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/570183/"
] | ```
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
``` | From C# 6.0 onwards (Visual Studio 2015 and newer), you can simply use an interpolated string with formatting:
```cs
var date = new DateTime(2017, 8, 3);
var formattedDate = $"{date:dd-MM-yyyy}";
``` |
21,421,821 | I'm building an Android application using ListView. I have list view items as show below.

^ List Item Index 0

^ List Item Index 1
The xlm is as follows.
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="4dip" >
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="@drawable/icon" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.93"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- JFN bottom used to be 2, top 6 -->
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="0dip"
android:paddingTop="0dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold" />
<!-- Email label -->
<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="0dip"
android:textColor="#acacac" />
<!-- Mobile number label -->
<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Mobile: "
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="vertical" >
<ImageView
android:id="@+id/chat"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="2dip"
android:gravity="right"
android:src="@drawable/chat" />
<ImageView
android:id="@+id/calendar"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="2dip"
android:gravity="right"
android:src="@drawable/calendar" />
</LinearLayout>
</LinearLayout>
```
I'm trying to detect four different click events:
1. When the picture of the dog is clicked
2. When the middle section is clicked
3. When the chat button is clicked
4. When the calendar button is clicked
In addition, each of these clicks must be distinguishable based on which item in the ListView has been clicked.
I know how I can tell each ListItem apart: I can use the ListView.setOnItemClickListener as is shown below, which provides an id of the item in the list. But this does not tell me which of the four portions was clicked on.
```
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
Log.d("JFN","List item clicked with id: "+id);
}
});
```
I can also bind a different onClick function call to each of the four sections in the xml, but this doesn't let me know which of the list items was clicked.
```
android:onClick="imgClicked"
```
I don't think I can combine these two solutions, as it would introduce a race condition. Is there a proper way to accomplish detecting both which list item was clicked, and which part of that particular list item was clicked?
Further Info
------------
The following code shows my creation of the ListView using the adapter.
```
// Retrieve string, convert to JSON, and extract contacts
String jsonData = jsonToStringFromAssetFolder("maemployees.json",this);
JSONObject jsonObj = new JSONObject(jsonData).getJSONObject(TAG_RESULTS);
int numContacts = jsonObj.getInt(TAG_NUM);
Log.d("JFN","Number of contacts stated: "+numContacts);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
Log.d("JFN","Number of contacts present: "+contacts.length());
// Loop over contacts
for( int i=0; i<contacts.length(); i++) {
// Extract this one
JSONObject c = contacts.getJSONObject(i);
// Extract strings
String first = (c.has(TAG_FIRST)) ? c.getString(TAG_FIRST) : "";
String last = (c.has(TAG_LAST)) ? c.getString(TAG_LAST) : "";
String city = (c.has(TAG_CITY)) ? c.getString(TAG_CITY) : "";
String state = (c.has(TAG_STATE)) ? c.getString(TAG_STATE) : "";
String country = (c.has(TAG_COUNTRY)) ? c.getString(TAG_COUNTRY) : "";
String costName = (c.has(TAG_COST_NAME)) ? c.getString(TAG_COST_NAME) : "";
// Temporary hash map for single contact
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("name", first+" "+last);
contact.put("email", city+", "+state+", "+country);
contact.put("mobile", costName);
// Adding single contact to list
contactList.add(contact);
}
Log.d("JFN","Done looping contacts");
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "name", "email",
"mobile" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
``` | 2014/01/29 | [
"https://Stackoverflow.com/questions/21421821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2464556/"
] | Allright I was having a similar kind of problem but i was using a **`ViewPager`** with a **`ListFragment`** and a custom `ListView` Layout.
In the above case you are using just **`ImageViews`**, but just in case if you use controls like `ImageButton`, `CheckBox` ,`Button` etc then you would face problems discussed [here](https://stackoverflow.com/questions/7274231/listfragment-onlistitemclick-not-being-called) and [here](https://stackoverflow.com/questions/1821871/how-to-fire-onlistitemclick-in-listactivity-with-buttons-in-list).
This is simply because such controls can steal **focus** from the `ListView` and the complete **list item** cant be selected/clicked. so I would say that just using **`ImageViews`** is a smart move.
I am assuming that you are using an Adapter to set the content of your list. Inside that adapter you can assign `onClickListener()`s for each item like this:
```
public class MyListAdapter extends ArrayAdapter<String>{
.......
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView=inflator.inflate(R.layout.channel_list_item, null, true);
ImageView chat=(ImageView) rowView.findViewById(R.id.chat);
chat.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//do something
}
}
ImageView calendar=(ImageView) rowView.findViewById(R.id.calendar);
calendar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//do something
}
}
.......
}
}
```
but remember that while using controls like `ImageButton`, `CheckBox` ,`Button` you need to assign property **`android:focusable="false"`** in the XML. and for the **`ImageButton`** you need to do this inside the `getView()` method:
```
final ImageButton imgBtn=(ImageButton) rowView.findViewById(R.id.imgBtn);
imgBtn.setFocusable(false);
imgBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//do your task here
}
});
```
---
or you can also use [Nathaniel Waggoner](https://stackoverflow.com/users/2757729/nathaniel-waggoner)'s approach.
Hope I answered your question. | You must be setting the content of your list view in an Adapter, So inside the adapter, there is a method `getView()`. Inside that `getView()` define each of your view and then set onCLickListener inside those view.
For Ex:
```
dog.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//operation to be performed.
}
});
```
similarly apply `onCLickListeners()` to all other views. |
24,302,398 | how to access immediate unknown key in object. in pic "367:sl" is dynamic key and i want to access cptyName value which is in "367:sl". Thanks in advance
 | 2014/06/19 | [
"https://Stackoverflow.com/questions/24302398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2396721/"
] | If your dynamic key is the only key in `quotes` object, you can get the first key and then access value with:
```
var firstKey = Object.keys(quotes)[0];
var cptyName = quotes[firstKey].cptyName;
```
<http://jsfiddle.net/mGZpa/> | You can iterate through the object.
```
var quotes = {
'367:sl': 'cptyname'
}
for(var i in quotes) {
alert(quotes[i]);
}
```
[Demo](http://jsfiddle.net/LPK3L/) |
348,449 | I recently flagged the following answer as being of low-quality, and both flags were disputed.
* <https://stackoverflow.com/a/43623198/1415724>
The flags and responses are as follows:
1) *very low quality – Fred -ii- 12 hours ago
Response: disputed*
2) (for moderation): *I flagged this question yesterday as being of low-quality since it only contains linked only resources. This is a known topic [Are answers that just contain links elsewhere really "good answers"?](https://meta.stackexchange.com/q/8231/)
Response: declined - If you remove the links, the answer is still (minimally) viable, which is how it was reviewed: <https://stackoverflow.com/review/low-quality-posts/15950023> - disputed*
What is up with that? That totally goes against what has already been posted on meta about this:
* [Are answers that just contain links elsewhere really "good answers"?](https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers)
This is a known problem with reviewers sending the wrong message by not paying attention or upholding what with Stack deems as being of low-quality.
So, has the playing field now just suddenly changed? Has Stack and its reviewers/moderators now turned over a new leaf without telling us and that we are to continually support link-only answers?
That's the message I am getting out of this and I don't support, I protest it.
---
**Edit:**
If the answer in question had contained a better descriptive method, then I'd of supported it and not have said/done anything.
Say for example and I'll use this analogy:
**Chef:** *"Ok, cut up those potatoes for me."*
**Apprentice cook:** *"So, how do you want me to cut them and in how big a piece and where should I put them after, in a bowl or just anywhere?"*
So, IMHO, it should have at *least* contained something like:
>
> *"Place the following inside `<head></head>` of your document and you should be good to go. Stylesheet references (should) go inside (valid HTML) markup tags."*
>
>
>
Many don't know HTML or have even gone through an HTML 101 course. They'll just drop code in a file wherever it fits (believe me, I've seen this often and some pretty bad ones also).
Well, HTML doesn't work that way and we don't know the OP's knowledge and this for any future visitor to the question/answer who may also not know.
---
**Edit #2:**
Comments pulled from under the question (in question):
*"This is not a link only answer. Even without the hyperlink markup, this is a valid answer. You need to include those files, wherever you may get them from for bootstrap to work properly. The links themselves are just useful additions to this answer. – Tiny Giant 2 hours ago"*
*"@Alon for sure, bootstrap will throw an error because jQuery is not included, but bootstrap's JavaScript isn't necessary (AFAIK) to make the tabs feature work. Again, this is an attempted answer. Regardless of how much you dislike the answer or despise the person for even thinking of trying to be helpful, it is an attempted answer and should not be flagged. If you think this answer is incorrect or not useful, feel free to downvote, but this answer should not be flagged, nor should it be deleted through review or by a moderator. – Tiny Giant 1 hour ago"*
and one of my replies:
*"This is not a link only answer" - It's not only a link only answer, it's also incomplete. @TinyGiant Edit: "nor should it be deleted through review or by a moderator." - Nor should it be edited by anyone else but the answerer themselves. – Fred -ii- 13 mins ago"*
IMHO, an incomplete answer not containing (all) the essential parts means just that; of low quality.
To merely say/contain: *"include bootstrap.min.css and bootstrap.min.js"* - (to me), is interpreted as: *"This is all you need"*, or *"Include this and then figure out the rest for yourself"*; which is being unclear. | 2017/04/26 | [
"https://meta.stackoverflow.com/questions/348449",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/1415724/"
] | That answer is not "link only" by the ["Castle" guidance.](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer)
The answer, without link markup (as it is supposed to be reviewed for link-onlyness):
>
> include bootstrap.min.css and bootstrap.min.js
>
>
>
**Is that a poor answer?** Certainly. It needs to explain itself a bit more, to be really useful to other users.
**Does it answer the question?** Yes, as can be seen in the accepted answer. The answer in question is done poorly, but it does answer the question.
**Can it be salvaged through editing?** Most certainly! Therefore, it is *also* not "very low quality."
Therefore, this answer is a low quality answer, but it is not a *very* low quality answer, so your first flag was incorrect. Likewise, the mods were correct that the answer does not merit *immediate* deletion according to the guidelines.
Now, it does merit downvotes. Should it be deleted eventually? Probably, if it's not edited by the author, but it's not 100% unsalvagable trash that has to go right this instance. That's what the "very low quality" flag is for, trash that is so smelly it has to go to the dumpster immediately.
**But doesn't it work as a comment?** No. Comments are for clarification of posts, *not* for answers. Technically, yes, it would be able to be posted as a comment, but it would not be what comments are for. | I think this is perfectly valid complete answer "include bootstrap.min.css and bootstrap.min.js".
Anyone with minimal knowledge of HTML should be able to understand it and create solution based on given information.
Is it the best ever answer - no. Should it be improved - it could, but it is not beneficial for the site - there are plenty of existing <https://stackoverflow.com/search?q=html+include+bootstrap> answers. It definitely can be downvoted in comparison to hundreds of other posts explaining how to do so. If that would be unique post (like first ever question about the topic) I would upvote it.
Should the other answer be upvoted for reasonable content or both downvoted for posting yet another "how to include bootstrap"? Personally I don't feel upvoting duplication of content as a good thing...
Proper action would be to VTC question as duplicate. |
5,894,262 | I am trying to solve the reverse word problem. My solution works, and even skips blank lines. However, after all the lines of a file are read, the program gets stuck in a loop, constantly accepting input. This is very puzzling, and I feel like it has to do with my outer while loop, but I can't see what's wrong with it.
```
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
int main(int argc, char** argv)
{
stack<string> s;
ifstream in;
in.open(argv[1]);
do
{
do
{
string t;
in >> t;
s.push(t);
} while(in.peek() != '\n');
do
{
cout << s.top();
s.pop();
if(s.size() > 0) cout << " ";
else cout << endl;
} while(s.size() > 0);
} while(in.peek() != -1 || in.fail() || in.eof() || in.bad() );
in.close();
return 0;
}
``` | 2011/05/05 | [
"https://Stackoverflow.com/questions/5894262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/224322/"
] | The problem is the inner loop. If I give in a text file containing only one word on a single line, it will fail since it will never come out of the inner loop.
This code works for me:
```
int main(int argc, char** argv)
{
stack<string> s;
ifstream in;
in.open(argv[1]);
do
{
do
{
string t;
in >> t;
s.push(t);
} while((in.peek() != '\n') && (in.peek() != -1));
do
{
cout << s.top();
s.pop();
if(s.size() > 0) cout << " ";
else cout << endl;
} while(s.size() > 0);
} while(in.peek() != -1 && !(in.fail()) && !(in.eof()) && !(in.bad()) );
in.close();
return 0;
}
```
Sriram | Here is an approach that may work.
```
// read the file line by line
string line;
while (std::getline(in, line))
{
if (!line.empty())
{
// now have a valid line, extract all the words from it
<input string stream> in_str(line); // construct a input string stream with the string
string word;
while (in_str >> word)
{
// push into the stack
}
// now print the contets of the stack
}
else
// print a blank line(?)
}
``` |
15,557,088 | I am refactoring a class with a public facing interface and thinking about the usage led me to ask:
What is the difference between declaring the following within some larger class (as an instance variable):
```
private final OnClickListener mButtonOnClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
//some codes
}
};
```
vs declaring as an anonymous inner class as follows (on the fly):
```
private void someFunctionInClass() {
someOtherFunctionThatTakesAnOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//some codes
}
});
}
```
More specifically, is the former still considered an anonymous inner class? I read in [this answer](https://stackoverflow.com/a/12058422/822005) that an anonymous inner class
>
> is one that is created AND defined within the body of another class' method
>
>
>
The first example I gave is created and defined within the body of another class but not within another class' method as the second one is. Is it still an anonymous inner class? Furthermore, what is the accepted practice for one vs. another? Is it more efficient to declare (what I think is still) an anonymous inner class as an instance variable because new objects don't need to be recreated? | 2013/03/21 | [
"https://Stackoverflow.com/questions/15557088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/822005/"
] | Those are both anonymous classes. In the first one, you can reuse it, but both are just objects that are created. An anonymous class is necessarily an inner class, and can access any fields of the enclosing class.
I think you may be getting anonymous classes confused with [inner classes and static nested classes](http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html), which have distinct differences. | Both are anonymous classes. Taking the example of a listener, if you intend to use the same listener for two components you can have an instance variable for that else you can directly attach it to the component. So it depends on the requirement.
But mostly its a sort-of one-time use, that is, you avoid creating instance for that. If you intend to reuse it, its better you create a separate class for that. |
11,340,619 | I'm currently doing an internship in a medical laboratory
They want to buy Ipad and medical device connected to it
example: diabet tester <http://www.ibgstar.us/>
blood pressure monitoring system <http://www.ihealth99.com/>
I'm wondering if I can code my own application that gets the data from the medical device and then handle it?
thks for your answers | 2012/07/05 | [
"https://Stackoverflow.com/questions/11340619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/862637/"
] | I think they're some step to success it .
At first you need a Hardware solution like said "Mundi".
You need to grab data from device and store them somewhere accessible (like in a BDD with online acces).
And then the iPad application just have to connecte to the data-Source and play with it | I'm not sure this applies, but I've seen some really cool medical apps written using Harvard's SMART project. They provide a simple but effective framework, which is independent of the Hospital Information System (like Cerner, Epic, VistA). |
14,330,470 | I have an app that has 2 models, City and Neighborhood. on the root page, I use collection\_set to display all cities
```
<%= form_tag('/sales/neighborhood', :method => :get) %>`
<%= collection_select(:neighborhood, :city_id, City.all, :id, :name) %>
<%= submit_tag 'Go' %>
```
I then want to have in the following view page, a dropdown list of all neighborhoods with a city\_id that matches the id of the city chosen on the first page. I think I have this part right and the city id is being passed in the params because I get a url like this `http://localhost:3000/sales/neighborhood?utf8=%E2%9C%93&city%5Bid%5D=1&commit=Go`. I just can't get a list of neighborhoods to display. I tried this in sales#neighborhood
```
<%= form_tag('sales/locations', :method => :get) %>
<%= collection_select(:location, :neighborhood_id, @nbhds.all, :id, :name) %>
<%= submit_tag 'Go' %>
```
but I get nothing in the dropdown box. I even tried this to just get a list of neighborhoods with a city\_id matching the id of the city chosen like this...
```
<ul>
<% @nbhds.each do |n| %>
<li>
<%= n.name %>,
<%= n.city.name %>
</li>
<% end %>
</ul>
```
I then want the application to list a set of locations based on the neighborhood\_id, which would be chosen from the collection\_set on the second page. Can anybody point me in the right direction? I think I've just about got it, just missing something.
My models look like this:
```
class City < ActiveRecord::Base
attr_accessible :name, :state
has_many :neighborhoods
end
```
and:
```
class Neighborhood < ActiveRecord::Base
attr_accessible :city_id, :name
belongs_to :city
has_many :locations
end
```
Here is the Sales controller action being called:
```
def neighborhood
@nbhds = Neighborhood.where(:city_id => params[:id])
end
```
I figure my problem is either in the where clause in sales#neighborhood or in my view but I put the code for the ul from the view in rails console and it lists all of the neighborhoods that belong to the city, the only difference is in the console I used
```
nbhds = Neighborhood.where(:city_id => 1)
```
instead of accessing it via params
I still need help with this if anyone can | 2013/01/15 | [
"https://Stackoverflow.com/questions/14330470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855249/"
] | According to the collection select
```
<%= collection_select(:neighborhood, :city_id, City.all, :id, :name) %>
```
parameter you should get in your controller will be like
```
params[:neighborhood][:city_id]
```
But according to your GET url `http://localhost:3000/sales/neighborhood?utf8=%E2%9C%93&city%5Bid%5D=1&commit=Go,` it seems the two parameters you are sending is city[id]=1 and commit=Go "city%5Bid%5D=1&commit=Go"
%5B & %5D are the HTML url encoding for '[' & ']' respectively.
If this is the correct request url then in you controller you would rather use the parameter [:city][:id] than [:id]
```
def neighborhood
@nbhds = Neighborhood.where(:city_id => params[:city][:id])
end
```
Please check your rails log to identify which is the correct params key before you start trying with any of the solution I mentioned. | You have `city_id` as a query parameter, and yet you look for `params[:id]` in your controller.
I would change that to
```
def neighborhood
city = City.find(params[:city_id])
@nbhds = city.neighborhoods
end
```
If that doesn't solve your problem I'll have a better look tomorrow :) |
22,561 | Can you help me to understand this phrase:
>
> I wish I could meet you so bad.
>
>
> | 2014/05/01 | [
"https://ell.stackexchange.com/questions/22561",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/8481/"
] | Don't interpret bad, as a negative thing here. When the person says they want to meet you so bad, they mean they really want to meet you. Not that the manner in which they want to meet you, is a negative thing. | The idiom "so bad" should be taken to mean "very intensely and urgently", and generally applies to wanting, desiring, or needing. As in "I have to go to the bathroom so bad." |
1,698,114 | is there any way to execute multiple statements (none of which will have to return anything) on Firebird? Like importing a SQL file and executing it.
I've been looking for a while and couldn't find anything for this. | 2009/11/08 | [
"https://Stackoverflow.com/questions/1698114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95511/"
] | In IBExpert you can execute multiple commands in single script via Tools->Script Executive (Ctrl+F12) | You can do this with IBOConsole (download from www.mengoni.it). The SQL window allows you to enter a complete script with the usual ";" delimiter. |
41,642 | I know that the order of the words has changed to form an interrogative sentence, and I comprehend that *a* means "has" and *il/elle* means "he/she", but what is the meaning of *-t-*, and from where it has arrived into the question?
For example, the interrogative form of "Tu as douze ans." is "Quel âge as-tu ?". I don't have any problem here, but in the sentence "Elle/il a onze ans.", one can't see any *-t-*, which one sees in the interrogative form of the sentence. | 2020/04/04 | [
"https://french.stackexchange.com/questions/41642",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/-1/"
] | It has no meaning. It occurs for the sound only, or as the French say, *des raisons [euphoniques](https://fr.wikipedia.org/wiki/Euphonie)*.
Specifically, it's a species of [liaison](https://en.wikipedia.org/wiki/Liaison_(French)#Liaison_on_inverted_verbs). Liaison is when the phonological environment of a syllable with no onset is created between two closely linked words, such as subject and verb. A consonant then fills the onset of that syllable.
Sometimes, that consonant is already waiting at the end of a word, normally silent yet still present in the mental grammar.
>
> Elle dort /ɛldɔʀ/ *← In the univerted form, the second word has a consonant /d/ in the onset*
>
>
> Dort-elle ? /dɔʀ**t**ɛl/ *← In the inverted form, the syllable /ɛl/ "borrows" its onset from* dort
>
>
>
Other times, there is no consonant available. Yet liaison demands one, perhaps originally because of grammatical analogy, and so a consonant is inserted from thin air.
>
> Elle va /ɛlva/
>
>
> Va-t-elle ? /vatɛl/ *← There was no silent consonant at the end of the verb*
>
>
>
Incidentally, this also explains what takes place in uninverted forms. You probably know that sometimes you seem to pronounce the last letter of *on*, *nous*, *vous*, *ils*, and *elles* :
>
> Vous venez /vuvəne/ *← The last consonant of* vous *is silent because* venez *has an onset*
>
>
> Vous allez /vu**z**ale/ *← The last consonant of* vous *is pronounced because* allez *has no onset*
>
>
>
The other way for these words to link is for one of the vowels to disappear (elision):
>
> Je sors /jəsɔʁ/
>
>
> J'aime /jɛm/ *← The schwa /ə/ at the end of* je *has been elided*
>
>
>
Oddly enough, in standard written French neither solution obtained for *tu* :
>
> Tu pleures /typlœʁ/
>
>
> Tu aimes /t**yɛ**m/ *← The sequence of two vowels between subject and verb is unexpected*
>
>
>
But in informal French, at least in informal Canadian French, the vowel of *tu* is elided.
>
> T'aimes /tɛm/
>
>
> | It is only for sound reasons, if we say "quel âge a il" it will be so hard to pronounce it, so they add the "t". |
8,412,868 | I am wondering if it's possible to program TPM ( <http://en.wikipedia.org/wiki/Trusted_Platform_Module> ) present in most of Intel chips, in such a way to:
```
- decide what to store in the persistent memory
- decide which cryptographic algorithms to implement.
```
Obviously it should not be reprogrammable once that it starts working (are you aware if this statement is correct?). | 2011/12/07 | [
"https://Stackoverflow.com/questions/8412868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/907921/"
] | The behaviour of a TPM is defined by the [specifications](http://www.trustedcomputinggroup.org/developers/trusted_platform_module/specifications) issued by the Trusted Computing Group. A TPM must exactly behave as specified, so you cannot change the functionality of a proper implemented TPM. The manufacturers of TPMs have limited abilities to update their products after shipping. For example Infineon provides firmware updates for their devices.
Intel TPMs however may be different. Some chipsets included an emulated/software TPM instead of an actual hardware TPM. Those TPMs can be updated with a BIOS update. But also in this case the update has to be provided by Intel. Recent boards like the DQ67SW have stand alone hardware TPMs not manufactured by Intel.
So the answer to your second question is: No, you **cannot program/define the cryptographic algorithms** a TPM uses.
---
Regarding your first question: Yes, you can define what to store in the persistent storage to some extend. This memory region is called *Non-volatile Storage* or **NV**. You have to define some space first using the **TPM\_NV\_DefineSpace** command. Afterwards you can read and write from/to the location using **TPM\_NV\_ReadValue** and **TPM\_NV\_WriteValue**. Defining reserves a given amount of memory in NV and also sets up the security attributes of this location. Those commands are low-level TPM commands, it is highly recommended to use a **Trusted Software Stack (TSS)** to interface the TPM. You can use either [jTSS](http://trustedjava.sourceforge.net/index.php?item=jtss/about) with [jTpmTools](http://trustedjava.sourceforge.net/index.php?item=jtt/about) or [TrouSerS](http://trousers.sourceforge.net/).
Some notes regarding NV:
* There is very limited space in the NV, but the exact amount is vendor specific (usually less than 5kb). The minimum amount for the PC platform is 2048 bytes.
* The TPM is a passive device, it cannot do anything without a command issued to it. If you want to store something in the TPM, you have to have some active piece (BIOS, Software, Chipset, CPU) that issues those commands.
* Even most cryptographic keys are not stored within the TPM. There is a key hierarchy and only the root key (Storage Root Key - SRK) is stored in the TPM. All other keys are stored outside in an encrypted way. | Yes, you can use the TPM chip for exactly these sorts of operations, and many more.
The [TrouSerS](http://trousers.sourceforge.net/faq.html) stack is an open source implementation of the trusted computing software stack necessary for using the TPM chip reliably. |
1,583,979 | new to Spring and here @stackoverflow
I'm building an stand-alone Inventory & Sales tracking app (Apache Pivot/Spring/JPA/Hibernate/MySQL) for a distributor business.
So far I think everything is CRUD, so I plan to have a base class with everything @Transactional.
Then I got a problem with my save generic method. Does persist and merge method of the EntityManager from Spring have a difference?
I tried running and called the save for both inserting and updating and it worked fine(I think spring automatically refreshes the entity every time I call my save method // saw the hibernate queries being logged, is this right?).
```
@Transactional
public abstract class GenericDAO {
protected EntityManager em;
// em getter+@PersistenceContext/setter
public void save(T t) {
// if (t.getId() == null) // create new
// {
// em.persist(t);
// } else // update
// {
em.merge(t);
// }
}
}
```
And btw, having a setup like this, I won't be much compromising performance right? Like calling salesDAO.findAll() for generating reports ( which does not need to be transactional, right? ).
thanks!!! | 2009/10/18 | [
"https://Stackoverflow.com/questions/1583979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265916/"
] | By local hosting, I'm guessing you mean on your own box, so essentially free. If you're not too strapped for cash, you could probably pick up a cheap box, and install a headless linux on there. Well, that's only if you're adverse to using linux as a desktop...
So, first, since you're only learning, I'm assuming you're not trying to put up a production site yet, so you can shut down lighty when you're not using it (getting rid of the boxes popping up for bots). Excuse me if this is unacceptable, since there is probably a solution out there (and how are you getting bots for a sandbox site? oO). Same goes for the performance: it's just a testing grounds, so optimization shouldn't matter too much yet (don't worry about it: remember the maxim that premature optimization is the root of all... something). If you still want fastcgi, there's another stackoverflow question/answer on that: [FastCGI on Windows and Lighttpd](https://stackoverflow.com/questions/766779/fastcgi-on-windows-and-lighttpd). Also, check out scgi, which *might* be a different story on windows.
Also, here's some thoughts from Atwood on yslow: codinghorror.com/blog/archives/000932.html
Finally; last I checked, lighty was no where near as popular as apache, meaning a much smaller user base. When you also consider IIS, then lighty wouldn't really have that many users under Windows. Just noting, you might have a not-so-smooth road ahead of you if you want to continue with lighttpd on windows. Also note, you'll probably end up shifting the server to another box or offsite eventually. I've served stuff from my desktop, and it's not all too fun in the long run. | Try [nginx](http://nginx.net/) - another lightweight alternative to apache, fast and stable. fastcgi on windows works ok.
Regarding your question - I think the reason is that lighttpd is loosing its popularity, look at the web server stats. So less people use it, less features are tested, more bugs are lurking around. |
25,063,324 | I am making four or more ajax rest calls in `$(document).ready(function(){}`.
As a hack, I added `.done()` to largest call. It is "working." I want to improve and add a spinning gif for part of page, not on entire body. I tried method for entire body, the spinner launches on my page transitions. I would like to avoid that.
```
$.getJSON("//urls", function( data ) { data122 = data });
$.getJSON("//urls", function( data ) { data212 = data});
$.getJSON("//urls", function( data ) { data21 = data});
$.getJSON("//urls", function( data ) { data12 = data});
$.getJSON("//urls", function( data ) { survey = data})
.done(function() {
}
``` | 2014/07/31 | [
"https://Stackoverflow.com/questions/25063324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428862/"
] | An alternative would be to use deferred:
```
$(function() { // on document ready
$("#spinner").show(); // show the spinner
var a = $.getJSON(...);
var b = $.getJSON(...);
// more calls...
$.when(a,b).always(function() {
$("#spinner").hide();
});
});
```
<http://api.jquery.com/category/deferred-object/> | ```
<script type="text/javascript">
$(document).ready(function()
{
$('#loading')
.hide()
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
});
</script>
<div id="loading">
Loading....
</div>
```
I found this one here
<https://stackoverflow.com/a/7082403/2630817> |
1,767,679 | Microsoft Visual Studio 2008 is giving me the following warning:
warning C4150: deletion of pointer to incomplete type 'GLCM::Component'; no destructor called
This is probably because I have defined Handles to forward declared types in several places, so now the Handle class is claiming it won't call the destructor on the given object.
I have VLD running and I'm not seeing any leaks. Is this literally not calling the destructor for this object or is this a "may not call destructor for object" warning?
Yet another memory leak question from me, haha. | 2009/11/20 | [
"https://Stackoverflow.com/questions/1767679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208358/"
] | Per the C++ Standard (ISO/IEC 14882:2003 5.3.5/5):
>
> If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.
>
>
>
So, if your class has a non-trivial destructor, don't do this, regardless of how Visual C++ handles this situation. | In g++, the warning could be reproduced too using following code:
```
class A;
void func(A *p)
{
delete p;
}
int main(int argc, char **argv)
{
return 0;
}
```
Warnings but no any errors:
```
test.cpp: In function void func(A*):
test.cpp:6: warning: possible problem detected in invocation
of delete operator:
test.cpp:4: warning: A has incomplete type
test.cpp:2: warning: forward declaration of struct A
test.cpp:6: note: neither the destructor nor the class-specific
operator delete will be called, even if they are declared
when the class is defined.
```
While g++ states very clear here that destructor will not be called because it doesn't know whether needs a destructor or not, or where is the destructor.
In this case delete() downgrates to the C call free(), that is, it just free the object memory itself, but any heap data allocated by the object itself internally (e.g., in constructor) will be keeped, the same behavior as free(p).
I think it would be a similar way if in MS VC/++; and a correct way is you to include the interface headers of A. |
14,276,892 | When I try to use any javascript template Eclipse always hangs and I get this message:
"Unhandled event loop exception Java heap space" on a popup.
I started a top command (using Ubuntu) for the Eclipse process and for Java process and then tried to use an auto-complete on Eclipse. I notice that the Java process takes my CPU to 100% while memory stays the same(arround 22%).
I got this without any prior changes to my Eclipse IDE...
Any ideas on how to solve this?
EDIT:
I notice also that on the preferences window under:
Javascript / Content Assist / Advanced
the option "Other Javascript Proposals" is checked. When unchecked, the problem is solved. However, it lacks the content assist for variables and objects. So this partially solves my problem. | 2013/01/11 | [
"https://Stackoverflow.com/questions/14276892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1769128/"
] | I managed to find the problem. I temporarily moved some js files to my project (some of them duplicated the original ones) and auto-complete was searching in too many files. So I changed the src folder like this:
* Right click on project
* Choose properties
* Javascript
* Include path
* On the source tab I excluded the files/folders that were duplicated and some that I didn't want to use on auto-complete.
This solved my problem and my Eclipse is fast now on auto-complete. | after working several hours in my case I found the solution I hope it works for you ;
change my JDK to alternate JRE
[](https://i.stack.imgur.com/CdPIh.jpg) |
23,586,229 | I am just wondering, how unique is a mt\_rand() number is, if you draw 5-digits number?
In the example, I tried to get a list of 500 random numbers with this function and some of them are repeated.
<http://www.php.net/manual/en/function.mt-rand.php>
```
<?php
header('Content-Type: text/plain');
$errors = array();
$uniques = array();
for($i = 0; $i < 500; ++$i)
{
$random_code = mt_rand(10000, 99999);
if(!in_array($random_code, $uniques))
{
$uniques[] = $random_code;
}
else
{
$errors[] = $random_code;
}
}
/**
* If you get any data in this array, it is not exactly unique
* Run this script for few times and you may see some repeats
*/
print_r($errors);
?>
```
How many digits may be required to ensure that the first 500 random numbers drawn in a loop are unique? | 2014/05/10 | [
"https://Stackoverflow.com/questions/23586229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2156512/"
] | The birthday paradox is at play here. If you pick a random number from 10000-99999 500 times, there's a good chance of duplicates.
**Intuitive idea with small numbers**
If you flip a coin twice, you'll get a duplicate about half the time. If you roll a six-sided die twice, you'll get a duplicate 1/6 of the time. If you roll it 3 times, you'll get a duplicate 4/9 (44%) of the time. If you roll it 4 times you'll get at least one duplicate 13/18 (63.33%). Roll it a fifth time and it's 49/54 (90.7%). Roll it a sixth time and it's 98.5%. Roll it a seventh time and it's 100%.
If you take replace the six-sided die with a 20-sided die, the probabilities grow a bit more slowly, but grow they do. After 3 rolls you have a 14.5% chance of duplicates. After 6 rolls it's 69.5%. After 10 rolls it's 96.7%, near certainty.
**The math**
Let's define a function `f(num_rolls, num_sides)` to generalize this to any number of rolls of any random number generator that chooses out of a finite set of choices. We'll define `f(num_rolls, num_sides)` to be the probability of getting no duplicates in `num_rolls` of a `num_sides`-side die.
Now we can try to build a recursive definition for this. To get `num_rolls` unique numbers, you'll need to first roll `num_rolls-1` unique numbers, then roll one more unique number, now that `num_rolls-1` numbers have been taken. Therefore
```
f(num_rolls, num_sides) =
f(num_rolls-1, num_sides) * (num_sides - (num_rolls - 1)) / num_sides
```
Alternately,
```
f(num_rolls + 1, num_side) =
f(num_rolls, num_sides) * (num_sides - num_rolls) / num_sides
```
This function follows a logistic decay curve, starting at 1 and moving very slowly (since `num_rolls` is very low, the change with each step is very small), then slowly picking up speed as `num_rolls` grows, then eventually tapering off as the function's value gets closer and closer to 0.
I've created a Google Docs spreadsheet that has this function built in as a formula to let you play with this here: <https://docs.google.com/spreadsheets/d/1bNJ5RFBsXrBr_1BEXgWGein4iXtobsNjw9dCCVeI2_8>
**Tying this back to your specific problem**
You've generated rolled a 90000-sided die 500 times. The spreadsheet above suggests you'd expect at least one duplicate pair about 75% of the time assuming a perfectly random mt\_rand. Mathematically, the operation your code was performing is **choosing N elements from a set *with replacement***. In other words, you pick a random number out of the bag of 90000 things, write it down, then put it back in the bag, then pick another random number, repeat 500 times. It sounds like you wanted all of the numbers to be distinct, in other words you wanted to **choose N elements from a set *without replacement***. There are a few algorithms to do this. Dave Chen's suggestion of shuffle and then slice is a relatively straightforward one. Josh from Qaribou's suggestion of separately rejecting duplicates is another possibility. | Your question deals with a variation of the "Birthday Problem" which asks if there are N students in a class, what is the probability that at least two students have the same birthday? See [Wikipedia: The "Birthday Problem"](http://en.wikipedia.org/wiki/Birthday_problem).
You can easily modify the formula shown there to answer your problem. Instead of having 365 equally probable possibilities for the birthday of each student, you have 90001 (=99999-10000+2) equally probable integers that can be generated between 10000 and 99999. The probability that if you generate 500 such numbers that *at least* two numbers will be the same is:
P(500)= 1- 90001! / ( 90001^n (90001 - 500)! ) = 0.75
So there is a 75% chance that at least two of the 500 numbers that you generate will be the same or, in other words, only a 25% chance that you will be successful in getting 500 different numbers with the method you are currently using.
As others here have already suggested, I would suggest checking for repeated numbers in your algorithm rather than just blindly generating random numbers and hoping that you don't have a match between any pair of numbers. |
3,267,145 | I have a makefile structured something like this:
```
all :
compile executable
clean :
rm -f *.o $(EXEC)
```
I realized that I was consistently running "make clean" followed by "clear" in my terminal before running "make all". I like to have a clean terminal before I try and sift through nasty C++ compilation errors. So I tried to add a 3rd target:
```
fresh :
rm -f *.o $(EXEC)
clear
make all
```
This works, however this runs a second instance of make (I believe). Is there a right way to get the same functionality without running a 2nd instance of make? | 2010/07/16 | [
"https://Stackoverflow.com/questions/3267145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394103/"
] | Actually you are right: it runs another instance of make.
A possible solution would be:
```sh
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
```
By calling `make fresh` you get first the `clean` target, then the `clearscreen` which runs `clear` and finally `all` which does the job.
**EDIT Aug 4**
What happens in the case of parallel builds with make’s `-j` option?
There's a way of fixing the order. From the make manual, section 4.2:
>
> Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
>
>
> The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
>
>
>
Hence the makefile becomes
```sh
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
```
**EDIT Dec 5**
It is not a big deal to run more than one makefile instance since each command inside the task will be a [sub-shell](https://www.gnu.org/software/make/manual/html_node/Execution.html#Execution) anyways. But you can have reusable methods using the [call function](https://www.gnu.org/software/make/manual/html_node/Call-Function.html).
```sh
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
``` | If you removed the `make all` line from your "fresh" target:
```
fresh :
rm -f *.o $(EXEC)
clear
```
You could simply run the command `make fresh all`, which will execute as `make fresh; make all`.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in. |
70,466 | I am a Malevolent and deceitful god. My cruelty and treachery is well known throughout the world. These true stories about me are spread by my nemesis, the god of love, kindness and truth. Worship of my nemesis is the main religion around. I desire to make a religion to rivel my nemesis but I have one problem: as a God, I cannot lie. I can deceive, but to tell an outright falsehood is impossible for me. So when followers ask me details about myself, who I am, and my intentions, I have to tell them the truth. How can I convince people to follow a god who delights in their suffering and who cannot be trusted?
Edit: When I say I can not lie I mean that I must answer the truth to any question asked, but that I can deliberately choose to phrase my answer in such a way as to give people the wrong impression. And I can leave out information not asked about, in order to also give the wrong impression. For example "I said I would not kill you but that doesn't mean I wont torture you."
Edit: I need more followers because 1. More followers means more power.
2. I want to stick it to my nemesis. 3. My pride will not accept that there is anything that my nemesis can do that I can't do better.
I want to make it clear I am evil I'm not misunderstand or anything like that. | 2017/02/07 | [
"https://worldbuilding.stackexchange.com/questions/70466",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/17551/"
] | This religion would give true believers (and those who only pretend to believe) an excuse why they can be evil themselves. No more fasting and giving alms and meekness.
Has your story an afterlife with heaven and hell? If so, can any god provide tickets or is it just one?
In the temporal world, the god would tell his followers that *many* other humans are evil and deceitful at heart. If your setting is like the real world, perhaps he can even say *most* others. And he could point out that sociopathic personalities [rise to the top](https://en.wikipedia.org/wiki/Psychopathy_in_the_workplace#Careers_with_highest_proportion_of_psychopaths). So *accepting this truth* is only good adjustment in an evil world. "If you can't beat them, join them. Here is the how-to manual." | First, elaborate on how you can be deceitful but not tell a lie. Do the people *know* this?
As for why follow you, what do you have to offer? There’s no downside to *not*, as that is the status quo. Do you have powers? Do you reward followers? What’s your **offer**? |
37,596,899 | I have several string resources for different languages. As you can see, all of them starts with capitalized letter and then in lower case. So, is there any way how to Converter all of them to UPPERCASE without direct changing of resources? Is it possible to do it in XAML? Maybe combination of Binding's converter?
[](https://i.stack.imgur.com/z5WLL.png) | 2016/06/02 | [
"https://Stackoverflow.com/questions/37596899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5033823/"
] | Here's a C# version of the same thing:
```
public class ToUpperConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string stringValue = value as string;
return string.IsNullOrEmpty(stringValue) ? string.Empty : stringValue.ToUpper();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotSupportedException();
}
}
```
To reference this in XAML:
```
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1">
<Page.Resources>
<local:ToUpperConverter x:Key="UpperCaseConverter" />
</Page.Resources>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="{x:Bind MyString, Converter={StaticResource UpperCaseConverter}}" />
</StackPanel>
</Page>
```
For completeness, this is the property I `x:Bind` to:
```
public sealed partial class MainPage
{
public string MyString => "Hello world!";
public MainPage()
{
InitializeComponent();
}
}
```
**EDIT**
In the comments of the OP, @RaamakrishnanA asks about how this might work with resources. A bit of indirection is one approach.
In the `.resw` file, provide a value for the `Tag` property:
```
<data name="HelloWorld.Tag">
<value>Hello, world!</value>
</data>
```
Now use `x:Uid` to bind that to the `Tag` property of a `TextBlock`, then bind the `Text` property to the tag, allowing us to use the converter:
```
<TextBlock
x:Name="textBlock"
x:Uid="HelloWorld"
Text="{Binding Tag, ElementName=textBlock, Converter={StaticResource UpperCaseConverter}}"
/>
```
Output:
[](https://i.stack.imgur.com/rcOVh.png) | You told the answer yourself. Use a converter.
```
Public Namespace Converter
Public Class ToUpperValueConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object
Dim str = TryCast(value, String)
Return If(String.IsNullOrEmpty(str), String.Empty, str.ToUpper())
End Function
Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object
Return Nothing
End Function
End Class
```
**Edit**
To use this converter you need to use some kind of binding to your property and not the usual `x:Uid` way. You can't bind to a resource directly. Instead, you need to convert the resource into some form of code behind and bind it through your ViewModel. This [SO answer](https://stackoverflow.com/a/21135268/5562523) will walk you through the steps. But instead of the `PublicResXFileCodeGenerator` tool, you may have to use something like [ResW File Code Generator](https://visualstudiogallery.msdn.microsoft.com/3ab88efd-1afb-4ff5-9faf-8825a282596a)
I am afraid there is no way to do this in pure XAML. |
360,890 | I am revising undergrad statistics course via [this course](https://lagunita.stanford.edu/courses/course-v1:OLI+ProbStat+Open_Jan2017/info), where i am learning technique to pull out sample from population.
While ensuring that sample is decent representative of population, i am left with this couple of question.
* Should we care about identification and rectification of outliers prior to taking sample from population ?
[Here](https://github.com/guptakvgaurav/prob_stats/blob/master/3_Sampling/1_sampling_biased_vs_non_biased.ipynb) is my work from where i came up with this question | 2018/08/06 | [
"https://stats.stackexchange.com/questions/360890",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/172680/"
] | This depends hugely of what you even want to do about outliers, through what mechanism they arise and whether they even affect what you want to do.
If outliers are perfectly good values that just happen to be (a bit) extreme, then it may be more a matter of making sure it does not affect what you intend to do too much. Some statistical procedures/summary measures are inherently more robust in this respect, while other have more problems.
1. E.g. if you want to find the population median of something, outliers do not really matter much.
2. On the other hand, a mean might be much more heavily affected, e.g. if you are trying to find the mean of a log-normal distribution, directly taking the sample mean may be a bad idea, if you have just a few values. On the other hand, estimating the parameters of the distribution and then obtaining the theoretical mean from that would likely work a lot better.
If outliers arise through a corrupted sampling process (e.g. people deliberately give nonsense answers to a questionnaire, some biological sample was accidentally contaminated with some other substance etc.), you probably do indeed want to do something about those values. However, what you do depends on what you assume the process that creates these corrupted values to be (following the terminology of missing completely at random/at random/not at random for missing data):
* Is it "completely at random" (it might be a reasonable assumption that whether or not a lab technician spoilt a biological sample had nothing to do with what you would have measured on this sample)?
* Is it "at random" (perhaps young people are more likely to give nonsense answers to questions, but their true response would otherwise have been distributed like for other young people)?
* Or is it "not at random" (e.g. people are reluctant to given answer A and rather give a nonsense answer instead, or the lab technician accidentally spoilt the biological sample, because she was shocked by how many bacteria she saw etc.)? | In general, you won't *have* the population. So, if you, in class exercises, remove the outliers from the population before taking the sample, your exercises will be poor examples for the students when they do future work. |
50,661,871 | I have this dictionary:
```
analytics = {
datetime.datetime(2018, 4, 1, 0, 0):{
'clicks': 5049,
'month': datetime.datetime(2018, 4, 1, 0, 0)
},
datetime.datetime(2018, 3, 1, 0, 0): {
'clicks': 592,
'month': datetime.datetime(2018, 3, 1, 0, 0)
},
datetime.datetime(2018, 6, 1, 0, 0): {
'impressions': 2159, 'clicks': 223,
'month': datetime.datetime(2018, 6, 1, 0, 0)
},
datetime.datetime(2018, 5, 1, 0, 0): {
'impressions': 32747,
'clicks': 4184,
'month': datetime.datetime(2018, 5, 1, 0, 0)
}
}
```
I want to sort it by date, which I do using:
`analytics = sorted(analytics, key=lambda k: k)`
However, while this does sort the dictionary, it removes everything except the key. Any idea why and how to solve it? | 2018/06/02 | [
"https://Stackoverflow.com/questions/50661871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327870/"
] | Dictionaries aren't orderable. When you call `sorted` on a dictionary it treats it as an iterable, which it produces by key only. You can test this with:
```
for k in some_dict:
print(k) # should produce each key
```
What you want instead is to sort `dict.items`, which is still not a dict, but instead more like a list of `(key, value)` tuples
```
analytics = sorted(analytics.items(), key=lambda kv: kv[0])
``` | instead of dict you should use OrderedDict
```
from collections import OrderedDict
ordered_dict = OrderedDict()
sorted_keys = sorted(analytics.keys())
for key in sorted_keys:
ordered_dict.update({key: analytics[key]})
```
see the docs: <https://docs.python.org/2/library/collections.html#collections.OrderedDict> |
17,941,626 | I am using PHP to insert rows into mysql.
I wanted to know the pid (primary ID) immediately after inserting that row as a return value.
Kindly advice ... how can I do this.
Thanks in advance | 2013/07/30 | [
"https://Stackoverflow.com/questions/17941626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2633200/"
] | Depending on the extension you're using:
mysql: `mysql_insert_id()` ([DOCUMENTATION](http://php.net/manual/en/function.mysql-insert-id.php))
mysqli: `mysqli::$insert_id` ([DOCUMENTATION](http://php.net/manual/en/mysqli.insert-id.php))
PDO: `PDO::lastInsertId()` ([DOCUMENTATION](http://php.net/manual/en/pdo.lastinsertid.php)) | You can use as below :
```
$id = mysql_insert_id();
```
For more details refer [This link](http://php.net/manual/en/function.mysql-insert-id.php) |
46,947 | Are the following sentences correct?
>
> *He just got up.* -- Can I say this, informally?
>
> *He just waked up.*
>
>
> | 2015/01/16 | [
"https://ell.stackexchange.com/questions/46947",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/4069/"
] | We can say either sentence, but waked is used far less often than **woke**.
He just **woke** up.
wake (base/infinitive)
**woke** (simple past)
woken (past participle)
The two sentences have almost the same meaning, and we often use them interchangeably.
There is a slight distinction: "He just woke up" tells us that the person is now awake. "He just got up" tells us that the person is now awake and implies that the person also got out of bed. | It's fine!
>
> He just got up = He just waked up
>
>
>
Both mean informally that he's not sleeping now. He just finished his sleep.
However, it's worth knowing that '[wake up](http://www.macmillandictionary.com/dictionary/british/wake-up_1)' and '[get up](http://www.thefreedictionary.com/get+up)' mean many things other than the context of 'sleeping'. And I consider that you are talking about his state of 'sleeping'.
Note that ['woke up' is way more common than 'waked up'.](https://books.google.com/ngrams/graph?content=woke%20up%2C%20waked%20up&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cwoke%20up%3B%2Cc0%3B.t1%3B%2Cwaked%20up%3B%2Cc0) |
65,715,251 | **Note: Most answers that I could find here on stack overflow were either outdated (and used deprecated methods) or were closely related but not exactly useful for my case**
I am making an app that generates a color palette from the image input by the user. I am using [this Jetpack library](https://developer.android.com/training/material/palette-colors)
to achieve this. I am very much a noob and have never dealt with Bitmaps or such intents before. I believe the code to launch an image picker should be like below:
```
const val PICK_IMAGE = 1
class MainActivity : AppCompatActivity() {
private lateinit var openGalleryButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
openGalleryButton = findViewById(R.id.open_gallery_button)
openGalleryButton.setOnClickListener {
val photoPickerIntent = Intent(Intent.ACTION_PICK)
photoPickerIntent.type = "image/*"
startActivityForResult(photoPickerIntent, PICK_IMAGE)
}
}
}
```
Then I guess I have to do override `onActivityResult()` and do something there? But no matter what I do, I can't get it working. I am NOT looking to set this image to any `ImageView` and most answers to similar problems only answer how to set the image to an `ImageView` or are outdated and use deprecated methods.
I want to get the image from the user when they press the button, somehow convert it to a Bitmap that can be used inside with the color palette library. Get the dominant colors from the generated palette as hex color or some other usable format and deal with it myself. | 2021/01/14 | [
"https://Stackoverflow.com/questions/65715251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11620703/"
] | ### Assumption
* The array is sorted.
### The Condition
* Check if it is smaller then the current element in the array and greater then the next element in the array.
**Note:** If the array isn't sorted you can do `Array.sort()`
```js
const arr = [200, 180, 150, 120, 80];
let sum = arr.reduce((acc, x) => {
return acc + x
}, 0)
let avg = sum / arr.length;
for (let i = 0; i < arr.length - 1; i++) {
if (avg < arr[i] && avg > arr[i + 1]) {
console.log("Here at indice " + (i + 1) + " is " + avg + "'s place");
}
}
``` | Use `findIndex` method. (inline comments)
```js
const getIndexesBound = (arr, avg) => {
const index = arr.findIndex((num) => avg > num);
if (index < 1) {
// when index 0 means first element
// when index -1, can not find num
return "Can not find indexes bound";
} else {
return [index - 1, index];
}
};
const arr = [200, 180, 150, 120, 80];
console.log('Bound indexes for 146', getIndexesBound(arr, 146));
``` |
7,228,141 | How do I parse XML, and how can I navigate the result using jQuery? Here is my sample XML:
```
<Pages>
<Page Name="test">
<controls>
<test>this is a test.</test>
</controls>
</Page>
<Page Name = "User">
<controls>
<name>Sunil</name>
</controls>
</Page>
</Pages>
```
I would like to find the node by this path `Pages` -> `Page Name` -> `controls` -> `test` ? | 2011/08/29 | [
"https://Stackoverflow.com/questions/7228141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320126/"
] | you can use [`.parseXML`](http://api.jquery.com/jQuery.parseXML/)
```
var xml='<Pages>
<Page Name="test">
<controls>
<test>this is a test.</test>
</controls>
</Page>
<page Name = "User">
<controls>
<name>Sunil</name>
</controls>
</page>
</Pages>';
```
jquery
```
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$($xml).each(function(){
alert($(this).find("Page[Name]>controls>name").text());
});
```
here is the fiddle <http://jsfiddle.net/R37mC/1/> | Have a look at jQuery's [`.parseXML()` *[docs]*](http://api.jquery.com/jQuery.parseXML):
```
var $xml = $(jQuery.parseXML(xml));
var $test = $xml.find('Page[Name="test"] > controls > test');
``` |
27,157,168 | Is it possible to examine the contents of a directory in squirrel? I need a list of file names, including their paths, in a given directory and its subdirectories.
I'm writing a script for use in Code::Blocks, which uses squirrel as a scripting language. I've had a look at the squirrel standard library, but couldn't find any file related operations. It might also be possible to outsource this task to an external script (bash or whatever), but I'd prefer not to do that. | 2014/11/26 | [
"https://Stackoverflow.com/questions/27157168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/692359/"
] | I think you want to:
```
git fetch --all -Pp
```
where:
`git fetch` Download objects and refs from another (remote) repository
`--all` fetch all remotes.
`-P` remove any remote-tracking references that no longer exist on the remote.
`-p` remove any local tags that no longer exist on the remote.
for more use `git fetch --help`
We have a similar command that only perform a prune *not fetching* remote data:
```
git remote prune origin
```
We can also set the git client to do the remote prune every time we fetch data:
```
git config --global fetch.prune true
``` | Here is a script I wrote that will fetch and fast forward all your branches without doing any checkouts (so it's faster and doesn't affect your current working tree.
<https://stackoverflow.com/a/24451300/965176> |
8,959,720 | I am trying to sort my `locations` array from shortest to longest distance with the following code:
```
for(var i=0; i<locations.length;i++)
{
var swapped = false;
for(var j=locations.length; j>i+1;j--)
{
if (locations[j]['distance'] < locations[j-1]['distance'])
{
var temp = locations[j-1];
locations[j-1]=locations[j];
locations[j]=temp;
swapped = true;
}
}
if(!swapped)
break;
}
```
When I tried running the program, I get the following error in Firebug:
```
locations[j] is undefined
```
I console.logged the locations array and this is what it lloks like:
```
[Object { id="1", marker=U, more...}, Object { id="4", marker=U, more...}, Object { id="6", marker=U, more...}, Object { id="3", marker=U, more...}, Object { id="2", marker=U, more...}, Object { id="5", marker=U, more...}]
```
Is there a way to numerically index the objects, while keeping the objects' data associatively indexed?
Or is there a way to access the ith+1 or ith-1 element if I have for resort to using this.distance in a foreach loop? | 2012/01/22 | [
"https://Stackoverflow.com/questions/8959720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897740/"
] | You started 1 to late, remember array keys are indexes, which start at 0
```
for(var j=locations.length-1; j>i+1;j--)
{
console.log(j);
if (locations[j-1]['distance'] && locations[j]['distance'] < locations[j-1]['distance'])
{
var temp = locations[j-1];
locations[j-1]=locations[j];
locations[j]=temp;
swapped = true;
}
}
```
You're going to run into a problem on the last loop so I added `if(locations[j-1]['distance'] ...` | Index of an array is from 0 to length-1
```
for(var j=locations.length; j>i+1;j--)
```
so `locations[j]` is out of bound |
97,476 | I removed two room's worth of walls and ceiling horsehair plaster and wood lath from a home built in 1890. Would the plaster or paint used in those days cause the wood to release any toxins when burned? I'm wondering if the material can safely be used for firewood. | 2016/08/15 | [
"https://diy.stackexchange.com/questions/97476",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/3917/"
] | Wood smoke itself contains many toxins and carcinogens. I mention it because folks have the false impression that it's somehow more "natural" than other types of smoke, and therefore safer.
If you're managing your fire well, the little bit of extra stuff that clings to the lath shouldn't be an issue. (How would there be a substantial amount of paint on it?) | That old lathe board makes great kindling wood to start a fire. It gets very hot, so I wouldn't load the stove to the top with it. Your whole wood stove is full of toxins when lit so it's all going out the chimney anyways. |
30,774,600 | I'm trying to write a script that counts the number of matches of some pattern in a list of files and outputs its findings. Essentially I want to call the command like this:
`count-per-file.sh str_needle *.c`
and get output like:
```
Main.c: 12
Foo.c: 1
```
The script:
```
#!/bin/bash
# Count occurences of pattern in files.
#
# Usage:
# count-per-file.sh SEARCH_PATTERN GLOB_EXPR
for file in "$2"; do
count=$(grep -a "$1" "$file" | wc -l)
if [ $count -gt 0 ]; then
echo "$file: $count"
fi
done
```
The problem is if I call it like so I don't know how to loop over the file list, so this outputs nothing:
```
count-per-file.sh str_needle *.c
```
I found [this answer](https://stackoverflow.com/a/5065321/797744) but it deals the glob pattern being the only argument to the script, whereas in my script the first argument is the search pattern, and the rest are the files expanded from the glob. | 2015/06/11 | [
"https://Stackoverflow.com/questions/30774600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797744/"
] | As suggested I used `shift` which seems to 'pop' the first argument. Here's my working script:
```
#!/bin/bash
# Count occurences of pattern in files.
#
# Usage:
# count-per-file.sh SEARCH_PATTERN GLOB_EXPR
search_pattern="$1"
shift
for file in "$@"; do
count=$(grep -aiE "$search_pattern" "$file" | wc -l)
if [ $count -gt 0 ]; then
echo "$file: $count"
fi
done
``` | You can use substring parameter expansion with an start index like this to skip the first n-1 values in `$@`
`"${@:n}"`
e.g.
```
for FILE in "${@:2}"
do
echo $FILE
done
```
**N.B.** Your script doesn't get a 'glob pattern' as the second argument.
The shell that calls your script expands the glob to a space separated list of files *before your script sees it* and passes this to your script as the parameter list. This is why you can use [standard substring range expansion](http://wiki.bash-hackers.org/syntax/pe#substring_expansion). |
74,226,657 | When I use the `<Link>` tag in NextJs to navigate between pages it doesn't rerun my scripts after changing pages. It only runs the scripts after the first page load or when I press reload. When using plain `<a>` tags instead, it works fine because the page reloads after each navigation. As far as I can tell this happens because the `<Link>` tag makes it a Single-Page Application and doesn't refresh the page when navigating between pages.
I would greatly appreciate anyway to have it rerun the scripts when navigating between pages or to have it refresh the page without using just plain `<a>` tags and losing the Single-Page Application functionality.
This code doesn't refresh the page
```
<Link href="/page1">
<a>Page 1</a>
</Link>
<Link href="/page2">
<a>Page 2 </a>
</Link>
```
This code does refresh the page
```
<a href="/page1">Page 1</a>
<a href="/page2">Page 2 </a>
```
I load in all my scripts using a scripts component
```
export default const MyScripts = () => {
return (
<Script
strategy="afterInteractive"
type="module"
src="/scripts/myScript.js"
onReady={() => {
console.log("Ready")
}}
/>
)
}
```
One thing I've noticed is that the above `onReady` function fires each time I change pages. Maybe someone knows how to run the `myScript.js` from the `onReady`. | 2022/10/27 | [
"https://Stackoverflow.com/questions/74226657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19677826/"
] | The capturing group that participated in the match was different. In the first case, it was Group 1, in the second case, it was Group 2.
Also, note that the non-capturing group is superfluous, remove it.
To fix the immediate issue, you can use `r'\1\2\3'` as replacement:
```py
re.sub(r'avenue(\d+)|road(\d+)|lane(\d+)',r'\1\2\3','road12')
```
However, it seems extracting is much simpler here:
```py
m = re.search(r'(?:avenue|road|lane)(\d+)','road12')
if m:
print(m.group(1))
```
See the [regex demo](https://regex101.com/r/m1e8mr/1).
*Details*:
* `(?:avenue|road|lane)` - either `avenue`, `road`, or `lane`
* `(\d+)` - Group 1: one or more digits. | Would this work? The part that changes, avenue, road or lane can go in the non capturing group, then get the following number:
```py
re.sub(r'(?:avenue|road|lane)(\d+)',r'\1','road12')
``` |
23,664,726 | Ok so I have 3 sets of data like this:
Now I'd like to retrieve information about each pair
1. Product - Warehouse (I have 1000 records)
2. Warehouse - TransferNumber
3. Product - TransferNumber - Quantity
The final result I'm expecting is Product - Warehouse - Quantity.
It is bizarrely designed, but I want to pull all records from product warehouse to grab the quantity.
As I wanted to grab everything in ProductWarehouse, I tried to left outer join, it is supposed to return 1000 records but in reality it gives me 1500? Why it gives me more records? | 2014/05/14 | [
"https://Stackoverflow.com/questions/23664726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597281/"
] | require('child\_process').spawn;
================================
Running a Gulpfile from a different directory is quite simple with [Node's `child_process#spawn` module](http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options).
Try adapting the following to your needs:
```js
// Use `spawn` to execute shell commands with Node
const { spawn } = require('child_process')
const { join } = require('path')
/*
Set the working directory of your current process as
the directory where the target Gulpfile exists.
*/
process.chdir(join('tasks', 'foo'))
// Gulp tasks that will be run.
const tasks = ['js:uglify', 'js:lint']
// Run the `gulp` executable
const child = spawn('gulp', tasks)
// Print output from Gulpfile
child.stdout.on('data', function(data) {
if (data) console.log(data.toString())
})
```
gulp-chug
=========
Although using `gulp-chug` is one way to go about this, [it has been blacklisted by `gulp`'s maintainers](https://github.com/gulpjs/plugins/issues/93#issuecomment-42715640) for being...
>
> "execing, too complex and is just using gulp as a globber"
>
>
>
The [official blacklist](https://github.com/gulpjs/plugins/blob/master/src/blackList.json#L99) states...
>
> "no reason for this to exist, use the require-all module or node's require"
>
>
> | Maybe this would help someone too, so I'll give this a shot. I don't know specifically what the OP intends to do but the question is similar to my problem which my solution is to access the other gulp file in another way like using a project's pre-build event, for example:
```
cd $(SolutionDir)\ProjectThatHasTargetGulpFile
gulp theTaskNeedToRun
```
Considering that Gulp and NodeJs is properly installed in the machine (can run in cmd). |
46,408,073 | I have the following tables. As Canada day is July 1st and my data source is in business days only. Notice that July 1st is missing from TABLE\_A (name: `conm`) which is my source table.
```
CREATE TABLE [dbo].[comn]
(
CONM varchar(48),
valuedate datetime,
closeprice decimal(5,2)
)
GO
INSERT INTO comn VALUES ('SAPUTO INC', '2016-06-27', 37.66);
INSERT INTO comn VALUES ('SAPUTO INC', '2016-06-28', 38.34);
INSERT INTO comn VALUES ('SAPUTO INC', '2016-06-29', 38.48);
INSERT INTO comn VALUES ('SAPUTO INC', '2016-06-30', 38.37);
INSERT INTO comn VALUES ('SAPUTO INC', '2016-07-04', 38.12);
INSERT INTO comn VALUES ('SAPUTO INC', '2016-07-05', 38.59);
INSERT INTO comn VALUES ('SAPUTO INC', '2016-07-06', 38.75);
GO
```
I also have TABLE\_B (`businessdaysCAN`) with all Canadian holidays.
```
CREATE TABLE [dbo].[businessdaysCAN]
(
valuedate datetime,
isholidayCA decimal(5,2)
)
GO
INSERT INTO businessdaysCAN VALUES ('2016-02-15',1);
INSERT INTO businessdaysCAN VALUES ('2016-03-25', 1);
INSERT INTO businessdaysCAN VALUES ('2016-05-23', 1);
INSERT INTO businessdaysCAN VALUES ('2016-07-01', 1);
INSERT INTO businessdaysCAN VALUES ('2016-08-01', 1);
INSERT INTO businessdaysCAN VALUES ('2016-09-05', 1);
INSERT INTO businessdaysCAN VALUES ('2016-10-10', 1);
GO
```
I would like to have an output table such as when there is a Canadian holiday, I have the holiday date in my final table with the price of the day before.
```
CONM valuedate closeprice
------------------------------------------------
SAPUTO INC 2016-06-27 00:00:00.000 37.66
SAPUTO INC 2016-06-28 00:00:00.000 38.34
SAPUTO INC 2016-06-29 00:00:00.000 38.48
SAPUTO INC 2016-06-30 00:00:00.000 38.37
SAPUTO INC 2016-07-04 00:00:00.000 38.12
SAPUTO INC 2016-07-05 00:00:00.000 38.59
SAPUTO INC 2016-07-06 00:00:00.000 38.75
``` | 2017/09/25 | [
"https://Stackoverflow.com/questions/46408073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8670543/"
] | Use [calculated properties](https://technet.microsoft.com/en-us/library/ff730948.aspx) to create the split fields and exclude the original `Unit` field:
```
Import-Csv $file -Header Unit, IP, Hostname |
Select-Object -Property @{n='Unit';e={$_.Unit.Substring(0,4)}},
@{n='Town';e={$_.Unit.Substring(5)}}, * -Exclude Unit
``` | Or you can recreate object :
```
Import-Csv $file -Header Unit, IP, Hostname | %{
[pscustomobject]@{
Unit=$_.Unit.Substring(0,4)
Town=$_.Unit.Substring(5)
IP=$_.IP
Hostname=$_.Hostname
}
}
``` |
35,852,286 | I am really new to JavaScript and Node JS. I have various image URLs that I want to buffer. I have tried the request npm module but want a lower level library for what I want to achieve.
For example:
<http://assets.loeildelaphotographie.com/uploads/article_photo/image/128456/_Santu_Mofokeng_-_TOWNSHIPS_Shebeen_Soweto_1987.jpg>
I see lots of [examples](https://stackoverflow.com/a/9578403/5884189) that suggest using the [request module](https://www.npmjs.com/package/request) or examples that save files to disk. However, I cannot find an HTTP GET request example that simply buffers the image so I can pass to another function. It needs to have an "end" event so I upload the buffered image data with confidence in another step. Is there a sample pattern or "how to" on this someone could provide? Thanks! | 2016/03/07 | [
"https://Stackoverflow.com/questions/35852286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5884189/"
] | This is the native way:
```
var http=require('http'), imageBuffer;
http.get(
'http://www.kame.net/img/kame-anime-small.gif',
function(res) {
var body=new Buffer(0);
if (res.statusCode!==200) {
return console.error('HTTP '+res.statusCode);
}
res.on('data', function(chunk) {
body=Buffer.concat([body, chunk]);
});
res.on('end', function() {
imageBuffer=body;
});
res.on('error', function(err) {
console.error(err);
});
}
);
// Small webserver serving the image at http://127.0.0.1:4567
http.createServer(function(req, res) {
res.write(imageBuffer || 'Please reload page');
res.end();
}).listen(4567, '127.0.0.1');
```
and using request (`encoding:null` for binary response):
```
var request=require('request'), imageBuffer;
request({
uri: 'http://www.kame.net/img/kame-anime-small.gif',
encoding: null
}, function(err, res, body) {
if (err) {
return console.error(err);
} else if (res.statusCode!==200) {
return console.error('HTTP '+res.statusCode);
}
imageBuffer=body;
});
// Small webserver serving the image at http://127.0.0.1:4567
require('http').createServer(function(req, res) {
res.write(imageBuffer || 'Please reload page');
res.end();
}).listen(4567, '127.0.0.1');
``` | Here's a simple example using the built-in streaming that the http response has:
```
var http = require('http');
var fs = require('fs');
var file = fs.createWriteStream("test.png");
var request = http.get("some URL to an image", function(response) {
response.pipe(file);
});
```
I ran this myself and successfully downloaded an image from an external web site and saved it to a file and then loaded the file into the browser to see the same image. |
8,072,933 | ```
public class SieveGenerator{
static int N = 50;
public static void main(String args[]){
int cores = Runtime.getRuntime().availableProcessors();
int f[] = new int[N];
//fill array with 0,1,2...f.length
for(int j=0;j<f.length;j++){
f[j]=j;
}
f[0]=0;f[1]=0;//eliminate these cases
int p=2;
removeNonPrime []t = new removeNonPrime[cores];
for(int i = 0; i < cores; i++){
t[i] = new removeNonPrime(f,p);
}
while(p <= (int)(Math.sqrt(N))){
t[p%cores].start();//problem here because you cannot start a thread which has already started(IllegalThreadStateException)
try{
t[p%cores].join();
}catch(Exception e){}
//get the next prime
p++;
while(p<=(int)(Math.sqrt(N))&&f[p]==0)p++;
}
//count primes
int total = 0;
System.out.println();
for(int j=0; j<f.length;j++){
if(f[j]!=0){
total++;
}
}
System.out.printf("Number of primes up to %d = %d",f.length,total);
}
}
class removeNonPrime extends Thread{
int k;
int arr[];
public removeNonPrime(int arr[], int k){
this.arr = arr;
this.k = k;
}
public void run(){
int j = k*k;
while(j<arr.length){
if(arr[j]%k == 0)arr[j]=0;
j=j+arr[k];
}
}
}
```
Hi I'm getting an `IllegalThreadStateException` when I run my code and I've figured it's because I am trying to start a thread that has already been started. So how could I kill
or stop the thread each time, to get around this problem? | 2011/11/09 | [
"https://Stackoverflow.com/questions/8072933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1014888/"
] | You could implement Runnable instead and use new Thread( $Runnable here ).start() or use a ExecutorService to reuse threads. | ThreadPools can be used for delivering tasks to set number of threads. When initiating you set the number of threads. Then you add tasks for the pool. And after you can block until all tasks have finished processing. [Here](http://www.java2s.com/Code/Java/Threads/Threadpooldemo.htm) is some sample code. |
11,593,091 | Ho to check gems ready to update, without update them? | 2012/07/21 | [
"https://Stackoverflow.com/questions/11593091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537135/"
] | If you are not using bundler, just run `gem outdated` and it will give you a list of outdated gems.
Example of output:
```
$ gem outdated
acts_as_tree (2.7.1 < 2.9.1)
addressable (2.4.0 < 2.7.0)
bcrypt (3.1.12 < 3.1.13)
bootsnap (1.4.5 < 1.4.6)
bootstrap (4.3.1 < 4.4.1)
brakeman (4.7.2 < 4.8.0)
cancancan (1.17.0 < 3.0.2)
chart_js (1.1.0 < 1.1.1)
coffee-rails (4.2.2 < 5.0.0)
combustion (0.6.0 < 1.1.2)
database_cleaner (1.8.2 < 1.8.3)
...
``` | `gem outdated` will give you a list of outdated gems including version number you currently have and the latest version number.
Then to update:
* `gem update GEMNAME` to update a specific gem
or just
* `gem update` to update all gems to the latest stable version |
7,473,536 | I have uploaded the file.css file on server with filezilla and also with cpanel.
But when i browse the website the css has no impact.
I changed: padding-left: 10px; If i see the Page view source i see that the older file is there.
What can be the reason for that ? | 2011/09/19 | [
"https://Stackoverflow.com/questions/7473536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884995/"
] | Try doing a hard refresh. CTRL Shift R. That should force any cached files to clear. Chances are that's the problem, unless the file isn't uploading. If you see the new file listed in Filezilla then it's a cache issue. | Did you replace/overwrite the existing css file?
It sounds like maybe the old one wasn't overwritten - in which case you'll have to do that for the changes to take effect.
Are you using a CMS? Some of them have Cache features where it may take time for those changes to be reflected unless you hard refresh. |
13,011,394 | What's the best way to sum two or more lists even if they have different lengths?
For example I have:
```
lists = [[1, 2], [0, 3, 4], [5]]
```
and the result should be:
```
result = [6, 5, 4]
``` | 2012/10/22 | [
"https://Stackoverflow.com/questions/13011394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1003123/"
] | You can use [`itertools.izip_longest()`](http://docs.python.org/library/itertools.html?highlight=itertools#itertools.izip_longest), and use a `fillvalue` equal to `0`
```
In [6]: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
Out[6]: [6, 5, 4]
```
for Python < 2.6:
```
In [27]: ml = max(map(len, lists))
In [28]: ml #length of the longest list in lists
Out[28]: 3
In [29]: [sum(x) for x in zip(*map(lambda x:x+[0]*ml if len(x)<ml else x, lists))]
Out[29]: [6, 5, 4]
``` | The best I came up with is the following:
```
result = [sum(filter(None, i)) for i in map(None, *lists)]
```
It's not so bad, but I have to add NoneTypes and then filter them in order to sum up. |
55,126,381 | I'm using the latest version of Laravel. Fresh project. Just created the make:auth function.
My goal was to add additional fields to the registration field. The original model only requires name, email and password. I'm using SQLite and PHP 7.1.19
I wanted to add first name, last name and age. Somehow I'm getting the error shown below.
Could someone elaborate on what I'm doing wrong?
```
Symfony\Component\Debug\Exception\FatalThrowableError : syntax error, unexpected 'use' (T_USE) at /Users/sebastiaan/Documents/Code/auth/auth-example/database/migrations/2014_10_12_000000_create_users_table.php:3
1| <?php
2|
> 3| use Illuminate\Support\Facades\Schema;
4| use Illuminate\Database\Schema\Blueprint;
5| use Illuminate\Database\Migrations\Migration;
6|
7| class CreateUsersTable extends Migration
8| {
9| /**
Exception trace:
1 Illuminate\Filesystem\Filesystem::requireOnce("/Users/sebastiaan/Documents/Code/auth/auth-example/database/migrations/2014_10_12_000000_create_users_table.php")
/Users/sebastiaan/Documents/Code/auth/auth-example/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:448
2 Illuminate\Database\Migrations\Migrator::requireFiles()
/Users/sebastiaan/Documents/Code/auth/auth-example/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:90
Please use the argument -v to see more details.
```
This is how the migration file is looking right now.
```
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('firstname');
$table->string('lastname');
$table->integer('age');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
``` | 2019/03/12 | [
"https://Stackoverflow.com/questions/55126381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11192429/"
] | Namespace and use statements are not supported in PHP versions < `5.3`
Please check your php version using `<?php echo phpversion(); ?>` and check if its lower than 5.3
Otherwise the class looks good. If you had whitespaces at the start before the starting php tag, you would receive a different error like
>
> Namespace declaration statement has to be the very first statement or after any declare call in the script
>
>
>
which seems not the case as well.
Update :
Another way it can happen is due to some characters just before use statement. For example this code :
```
<?php
test
use \App\User;
class....
?>
```
If you observe the presence `test` word before the use statement by mistake this would cause the same error.
Coming back to how this is relevant here :
If you have copied your migration class from some website in case, you may have copied some unnoticeable white space characters as well. I will suggest do a backspace before use statement and check for such whitespaces. If you open this file in VIM editor, you might see such cases as well. | ```
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
```
} |
3,221 | If I would like to keep my emacs settings and packages in another computer or after a format **is there a way to avoid having to install all the packages from the beginning?**
I don't just mean saving the `.emacs` as to have the customizations but also the packages that come with it. I was wondering **if I copy and save my elpa file and then paste it in a new PC is there going to be any problem?**
Do the packages install files also in other folders of a system, so the aforementioned technique may cause problems, or is this a good way to keep your Emacs always with you? | 2014/11/07 | [
"https://emacs.stackexchange.com/questions/3221",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/2248/"
] | >
> If I would like to keep my emacs settings and packages in another computer or after a format is there a way to avoid having to install all the packages from the beginning?
>
>
> I don't just mean saving the .emacs as to have the customizations but also the packages that come with it. I was wondering if I copy and save my elpa file and then paste it in a new PC is there going to be any problem?
>
>
>
I posted [an answer](https://emacs.stackexchange.com/a/3239/115) on [Synchronize packages between different machines](https://emacs.stackexchange.com/q/408/115) describing how I manage installation of packages from scratch when I want to install emacs on a new machine.
On the new machine, you simply need to copy your emacs customizations. *Make sure that the `my-packages` list and the `setup-packages.el` that I explain in detail in my above referenced answer are also copied to the new machine.*
>
> Are the packages install files also in other folders of a system so to cause the aforementioned technique problems or is this a good way to keep your Emacs always with you?
>
>
>
Till now I haven't faced a situation like that. You would have to review what packages you have installed and where they save stuff that you would want to port to a new machine. Let me take `multiple-cursors` package as an example. By default, it creates a file `.mc-lists.el` in `.emacs.d`. But that is not a problem as I copy my whole emacs setup folder (`.emacs.d`) when porting my emacs customization to a new machine. | Providing you will be using the same version of Emacs, you can duplicate your .emacs.d with all compiled / packages in-place.
This is also true of keeping your .emacs.d in version control.
Personally I would recommend this method.
There is a current trend of using require-package (in various forms) which will implicitly install a package.
This is useful if you use many versions of Emacs, although a compiled .elc isn't always incompatible across point releases and re-compiling a broken package is relatively trivial.
The drawback of tools like require-package, is when a package (or version) or repository isn't available. This has happened to me often enough to be a problem. |
18,873,125 | When I have list of ids that I want to update their property the `updated_at` field in the database doesn't seem to change, here is what I mean :
```
ids = [2,4,51,124,33]
MyObj.where(:id => ids).update_all(:closed => true)
```
After this update is executed `updated_at` field doesn't change. However when I enter rails console with `rails c` and do this :
```
obj = MyObj.find(2)
obj.closed = false;
obj.save!
```
After this statement `updated_at` field changes value. Why is this? I'm relying on this `updated_at` field in my app as I'm listening to the updates and doing whole app flow when this happens?
**Edit**
I just found out from `dax` answer that :
```
Timestamps
Note that ActiveRecord will not update the timestamp fields (updated_at/updated_on) when using update_all().
```
I don't want to be updating one record at a time, is there a way around this? without resorting to sql level? | 2013/09/18 | [
"https://Stackoverflow.com/questions/18873125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190623/"
] | Updates all, This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations. Values passed to update\_all will not go through ActiveRecord's type-casting behavior. It should receive only values that can be passed as-is to the SQL database.
As such, it does not trigger callbacks nor validations - and timestamp update is made in a callback.update\_at is a call back for reference <http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all> | If anyone is interested I did make a gist that outlines how to roll it yourself.
<https://gist.github.com/timm-oh/9b702a15f61a5dd20d5814b607dc411d>
It's a super simple implementation just to get the job done.
If you feel like there is room for improvement please comment on the gist :) |
44,535,994 | Here is my JSON CODE
```
<?php
require '../db_connect.php';
if (isset($_GET['username']) && isset($_GET['password']))
{
$myusername = $_GET['username'];
$mypassword = $_GET['password'];
$sql = "SELECT * FROM user_registration WHERE (username = '$myusername' or email = '$myusername' or phone = '$myusername')";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0){
$response["VerifiedMember"] = array();
$row = mysqli_fetch_array($result);
$VerifiedMember = array();
$id=$row['id'];
$phone=$row['phone'];
$reg_type=$row['register_type'];
$stored_salt = $row['salt'];
$stored_hash = $row['hashed_password'];
$check_pass = $stored_salt . $mypassword;
$check_hash = hash('sha512',$check_pass);
if($check_hash == $stored_hash){
$VerifiedMember['user_id'] = $id;
$VerifiedMember['first_name']=$row['first_name'];
$VerifiedMember['phone']=$row['phone'];
array_push($response["VerifiedMember"], $VerifiedMember);
if(!empty($phone)&& $reg_type==1){
$sql="select * from user_otps where user_id='".$id."'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_array($result);
if($row['verified']==0)
{
//no product found
$response["success"] = 0;
$response["message"] = "failure";
// echo no users JSON
echo json_encode($response);
}
else
{
//no product found
$response["success"] = 1;
$response["message"] = "success";
// echo no users JSON
echo json_encode($response);
}
}
}
else{
//no product found
$response["success"] = 1;
$response["message"] = "success";
// echo no users JSON
echo json_encode($response);
}
//echo json_encode($response);
}
else{
//no product found
$response["success"] = 0;
$response["message"] = "invalid";
// echo no users JSON
echo json_encode($response);
}
}
else{
//no product found
$response["success"] = 0;
$response["message"] = "invalid";
// echo no users JSON
echo json_encode($response);
}
}
?>
```
Here is Android Code
```
public class NewLogin extends ActionBarActivity {
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
public static final String USER_NAME = "USERNAME";
String username;
String password;
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
class loginAccess extends AsyncTask<String, String, String> {
String access;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
@Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String url = "www.sample.com/home_webservice.php";
JSONObject json = null;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("TESS :: ", json.toString());
String status = json.getString("VerifiedMember");
Log.d("Success Response :: ", status);
if (status.equals("VerifiedMember")) {
Intent i = new Intent(NewLogin.this, NEWClass.class);
startActivity(i);
}
else if
(json.getString("VerifiedMember").trim().equalsIgnoreCase("failed"))
{
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
Intent i = new Intent(NewLogin.this, NEWClass.class);
startActivity(i);
}
}
}
```
Here's an example of the JSON I'm getting back:
{"VerifiedMember":[{"user\_id":"23","first\_name":"karan","phone":""}],"success":1,"message":"success"}
Unable to go new Activity after Login I m getting all users details correctly in LOG file bt not going to next activity
please help me to solve this
thank you in advance.. | 2017/06/14 | [
"https://Stackoverflow.com/questions/44535994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6808152/"
] | ```
public class NewLogin extends ActionBarActivity {
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
public static final String USER_NAME = "USERNAME";
String username;
String password;
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
class loginAccess extends AsyncTask<String, String, String> {
String access;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
@Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String url = "http://uat.ziplife.in/mobileapp/login_webservice.php";
JSONObject json = null;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("TESS :: ", json.toString());
JSONObject jsonObject =new JSONObject(response);
String status=jsonObject .getString("success")
if(status.equals("1)
{
Intent i = new Intent(NewLogin.this, NEWClass.class);
startActivity(i);
}
else if
{
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
Intent i = new Intent(NewLogin.this, NEWClass.class);
startActivity(i);
}
}
}
``` | Check Below Tutorial For JSON Parsing in Android,
<http://www.androidhive.info/2012/01/android-json-parsing-tutorial/>
```
JSONObject jsonObject =new JSONObject(response);
if(jsonObject.getString("message").equalsIgnoreCase("success"))
{
//start your activity
}else
{
// Give a Message
}
``` |
28,628,978 | I put a box shadow around the main #container div and although the #footer div is inside the #container div, the shadow is not displayed around #footer
Fiddle here: <http://jsfiddle.net/tfua7ebw/>
Can you please help me?
Thank you.
HMTL code:
```
<div id="container">
<div id="banner">
</div><!--end of banner-->
<div id="menubar">
<div id="nav">
<ul>
<li><a href="#">HOME </a></li>
<li><a href="#">FACILITATI</a></li>
<li><a href="#">LOCATIE</a></li>
<li><a href="#">GALERIE</a></li>
<li><a href="#">TARIFE</a></li>
<li><a href="#">CONTACT</a></li>
<li><a href="#"><strong>OFERTE</strong></a>
<ul>
<li><a href="#">SEMINARII </a></li>
<li><a href="#">REVELION 2015 </a></li>
<li><a href="#">CRACIUN 2015 </a></li>
</ul>
</li>
</ul><!--end menu ul-->
</div>
</div><!--end of menubar-->
<div id="content">
<div id="content_text">spozitie in orice perioada a anului noua camere duble si un apartamespozitie in orice perioada a anului noua camere duble si un apartamespozitie in orice perioada a anului noua camere duble si un apartamespozitie in orice perioada a anului noua camere duble si un apartame.</div>
<div id="poze1"><div id="content_div1"><img src="images/apart.jpg" width="233" height="154" />spozitie in orice perioada a anului noua camere duble si un apartame</div>
<div id="content_div1"><img src="images/ski.jpg" width="233" height="154" />spozitie in orice perioada a anului noua camere duble si un apartame</div>
<div id="content_div1"><img src="images/conf.jpg" width="233" height="154" />spozitie in orice perioada a anului noua camere duble si un apartame</div></div>
</div><!--end of content-->
<div id="footer"><p>spozitie in orice per</p>
<img src="images/fbb.jpg" width="102" height="34" />
</div><!--end of footer-->
</div><!--end of container div -->
```
CSS code:
```
<style type="text/css">
body {
margin-left: 0px;
margin-top: 0px;
background-color: #FFC;
font-family: "Roboto Slab";
background-image: url(images/fulg.jpg);
background-repeat: repeat;
}
#container {
padding: 0px;
height: auto;
margin-left: auto;
margin-right: auto;
width: 100%;
border-top-width: 0px;
border-right-width: 0px;
border-bottom-width: 0px;
border-left-width: 0px;
width: 800px;
box-shadow: 3px 3px 2px #000;
}
#banner {
margin: 0px;
padding: 0px;
height: 328px;
width: 800px;
background-image: url(images/banner_original.jpg);
background-repeat: no-repeat;
}
#menubar {
margin: 0px;
width: 800px;
height: 30px;
text-align: center;
vertical-align: middle;
background-color: #663200;
border-top-width: 1px;
border-top-style: solid;
border-right-style: none;
border-bottom-style: solid;
border-left-style: none;
border-top-color: #FC0;
border-bottom-color: #FC0;
border-bottom-width: 1px;
}
#nav ul {
list-style-type: none;
padding: 0px;
margin: 0px;
position:relative;
}
#nav ul li {
display: inline-block;
text-align: center;
vertical-align: middle;
padding: 0px;
margin: 0px;
}
#nav ul li a:hover {
background-color: #FFCC00;
color: #663200;
}
#nav ul li a{
padding: 0px;
margin: 0px;
display: block;
padding-left: 20px;
padding-right: 20px;
text-decoration: none;
text-align: center;
color: #FC0;
line-height: 30px;
}
#nav ul li:hover > ul {
display: block;
}
#nav ul li:hover {
background-color: #FFCC00;
}
#nav ul ul {
background-color: #FFCC00;
color: #663200;
padding: 0px;
position: absolute;
display: none;
right: 0;
top: 100%;
}
#nav ul ul li {
display: block;
}
#nav ul ul li a{
color: #663200;
}
#nav ul ul li a:hover{
background-color: #FFCC00;
}
#nav ul li:hover a{
color: #663200;
}
#nav ul ul li:hover a{
background-color: #DFB300;
}
#content {
padding: 0px;
height: auto;
width: 800px;
background-color: #663200;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-left: 0px;
font-size: 15px;
font-family: "Roboto Slab";
}
#content_text {
padding: 15px;
color: #FC0;
text-align: center;
}
#content_div1 {
width: 227px;
font-family: "Roboto Slab";
color: #FC0;
text-align: center;
display: inline-block;
vertical-align: top;
padding-right: 18px;
padding-bottom: 10px;
}
#poze1 {
text-align: center;
padding-left:9px;
}
#content_div1 img {padding-bottom:15px;}
#footer {
padding: 0px;
margin: 0px;
background-color: #663200;
border-top-width: 1px;
border-top-style: solid;
border-top-color: #FC0;
font-family: "Roboto Slab";
color: #FC0;
font-size: 14px;
vertical-align: middle;
height: 50px;
width: 800px;
float: left;
}
#footer img {float:right; padding-top:7px; padding-right:100px}
#footer p { padding-left:330px; float:left;}
</style>
``` | 2015/02/20 | [
"https://Stackoverflow.com/questions/28628978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4587041/"
] | Try removing **float: left;** from **footer** div css.
It will help. I tried that. | Try this.. may this will help you,
change `box-shadow` style in #container
<http://jsfiddle.net/sympbqx9/2/> |
20,046,806 | ```
public void activityStarter(Class<?> cls){
Intent intent = new Intent( ?, cls);
startActivity(intent);
}
```
What should be passed (see the ? mark) in order start a new activity (another java class I have in the same package, say MyActivity)? | 2013/11/18 | [
"https://Stackoverflow.com/questions/20046806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2964784/"
] | ```
NSMutableDictionary *tempDict = [[yourArray objectAtIndex:1] mutableCopy];
[tempDict setObject:@"New Name" forKey:@"Name"];
[yourArray replaceObjectAtIndex:1 withObject:tempDict];
``` | You should replace your object once you get index of object.
```
[arrayOfData replaceObjectAtIndex:yourIndex withObject:yourObject];
``` |
44,463,509 | I have next code which gets http code when url has been opened directly:
```
require 'net/http'
require 'uri'
def visit_page(url, response_code: false)
@browser.goto(url)
if response_code
page_status_code(url)
end
end
def page_status_code(url)
uri = URI.parse(url)
connection = Net::HTTP.new(uri.host, uri.port)
# If SSL.
# connection.use_ssl = true
# connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = connection.request(request)
response.code
end
```
In scenario it looks next:
```
response_code = page.visit_page('https://www.google.com', response_code: true)
puts response_code
```
And how I can apply this to get http code if I click on link?
```
page.link_element(text: 'lorem ipsum').click
``` | 2017/06/09 | [
"https://Stackoverflow.com/questions/44463509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4389785/"
] | Yes. This is called concatenation and is a fundamental part of string building in any language. In PHP this is accomplished with the `.` concatenation operator.
```
"string etc ".some_func()." continuation of string"
```
Note you can use single or double quotes. | ```
<?php
$title = the_title();
$field['url'] = "<iframe src='http://xxx.xx/=$title' width='640' height='360' allowscriptaccess='always' allowfullscreen='true' scrolling='no' frameborder='0'></iframe>;"
?>
``` |
60,549,566 | The following function is designed to block macrotasks, by repeatedly creating microtasks using `await`.
But why does it cause a stack overflow?
I thought `await` would put the recursive call on a microtask, and therefore empty the stack (clearly I was wrong).
```js
const waitUsingMicroTasks = async (durationMs, start = performance.now()) => {
const wait = async () => {
let elapsed = (performance.now() - start)
if(elapsed < durationMs) await wait()
}
await wait()
}
waitUsingMicroTasks(1000)
```
Whereas this - which I thought was almost equivalent - does not cause a stackoverflow:
```js
const waitUsingMicroTasks = async (durationMs, start = performance.now()) => {
const wait = async () => {
let elapsed = (performance.now() - start)
if(elapsed < durationMs) Promise.resolve().then(wait)
}
await wait()
}
waitUsingMicroTasks(1000)
``` | 2020/03/05 | [
"https://Stackoverflow.com/questions/60549566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38522/"
] | This recursive function is resolving entirely within the same microtask.
A new microtask is created when an `await` is encountered, you're correct. But the `await` operator needs to have a Promise or value in order to implicitly wrap it in a new Promise and attach callbacks. This means the value being `await`ed *needs to be evaluated first* before it can be scheduled as a microtask.
However, each execution of `wait` can't obtain a Promise to `await` before calling the next `wait`. So actually the stack is overflowing synchronously with no microtask being scheduled. You never actually obtain a Promise, because each Promise is dependent on the next one to be evaluated - each `wait()` call happens synchronously after the last one before any `await`s are resolved.
You might be able to force a microtask by `await`ing some value that does not need recursive calls to be evaluated:
```
const waitUsingMicroTasks = async (durationMs, start = performance.now()) => {
const wait = async () => {
let elapsed = await (performance.now() - start)
if(elapsed < durationMs) await wait()
}
await wait()
}
waitUsingMicroTasks(1000)
```
In your second example, this problem does not exist because you explicitly create a Promise and attach `wait` as a callback to it. This way, `wait` is not immediately executed (like with the `await`) but it is called when the Promise.resolve() microtask is run, some time later. | There are no blocking tasks done in the function. So it will keep executing the next recursion almost immediately, and since there is no recursion escape results in stack overflow.
Introducing a time consuming tasks like console log into the code and it will run fine.
```
let count=0;
const waitUsingMicroTasks = async (durationMs, start = performance.now()) => {
const wait = async () => {
let elapsed = (performance.now() - start);
console.log(++count);
(elapsed < durationMs) && (await wait());
}
await wait();
}
waitUsingMicroTasks(1000)
``` |
6,705,743 | Hello I am new to `affineTransform` in java. I want to use it to shear some GUI I have to use later.
For now I just wanted to test a sample code but i cannot explain its output.
Here is the code
```
package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass{
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
jf.getContentPane().add(new MyCanvas());
jf.setSize(600, 600);
jf.setVisible(true);
}
}
class Left extends JPanel {
Left(){
setPreferredSize(new Dimension(450,450));
setBorder(BorderFactory.createLineBorder(Color.green));
setBackground(Color.gray);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
AffineTransform at = new AffineTransform();
g2.setTransform(at);
g2.drawRect(getWidth()/2 - 10, getHeight()/2 - 10, 20, 20);
}
}
class MyCanvas extends JPanel {
MyCanvas()
{
setBorder(BorderFactory.createLineBorder(Color.red));
setLayout(new FlowLayout(FlowLayout.CENTER));
add(new Left());
}
}
```
The rectangle I want to draw in the `Left` class show appear in the center right?? But its coming shifted to left.. It seems its taking its coordinates with relative to the outer frame. If I remove the `g2.setTransform(at);` it comes normal.. Can you explain me why?? | 2011/07/15 | [
"https://Stackoverflow.com/questions/6705743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/808216/"
] | The `setTransform` method is intended only for restoring the original `Graphics2D` transform after rendering. That being said, you should ***never*** apply a new coordinate transform on top of an existing transform because the `Graphics2D` might already have a transform that is needed for other purposes, such as rendering Swing components. Your code exemplifies this point. To add a coordinate transform, use the `transform`, `rotate`, `scale`, or `shear` methods. | Expanding on @littel's [answer](https://stackoverflow.com/questions/6705743/problems-with-affinetransform/6707085#6707085), you can compare the current [transform](http://download.oracle.com/javase/6/docs/api/java/awt/geom/AffineTransform.html) to the identity as the frame is resized using the example below. Note that only the translational components vary: `dx = 75.0` is half the difference between the width of `MyCanvas` and `Left`, while `dy` includes the vertical offset of `Left` and the size of the green border.
```
Identity: AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
Identity: AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
Current: AffineTransform[[1.0, 0.0, 75.0], [0.0, 1.0, 201.0]]
Current: AffineTransform[[1.0, 0.0, 75.0], [0.0, 1.0, 1.0]]
```

```
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.geom.AffineTransform;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new GridLayout(0, 1));
jf.add(new MyCanvas());
jf.add(new MyCanvas());
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
}
class MyCanvas extends JPanel {
MyCanvas() {
setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
setPreferredSize(new Dimension(600, 200));
setBorder(BorderFactory.createLineBorder(Color.red));
add(new Left(), BorderLayout.CENTER);
}
}
class Left extends JPanel {
Left() {
setPreferredSize(new Dimension(450, 100));
setBorder(BorderFactory.createLineBorder(Color.green));
setBackground(Color.gray);
System.out.println("Identity: " + new AffineTransform());
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
System.out.println("Current: " + g2.getTransform());
g2.drawRect(getWidth() / 2 - 10, getHeight() / 2 - 10, 20, 20);
}
}
``` |
365 | When you reach 10k rep, you get to see other users deleted answers. I just think it's dishonest as a system to call a feature "delete," but show that to totally random strangers in the backroom. Due to the nature of the rep, given enough time, all of the regular users would eventually reach 10k rep, no matter how insensitive or jerk they are.
There's usually a good reason why people hit "delete" to their own work. They regret writing something totally bullshit or maybe they spoke too much about their own work that they shouldn't have.
First of all, is there really a practical reason why 10k rep user should view self-deleted answers?
Does the benefit really outweigh the creepiness? (Imagine if total strangers could see your deleted messages in Gmail?)
What suggestions could we make to change it?
Borrowing from the email metaphor, I think it makes sense for users to "empty trash" so the items gets seriously deleted. Imho, however the deletion is implemented is not important. It could be a soft delete, SQL Delete, or physical destruction of metal plates as long as the user or the 10k rep user no longer sees the deleted item.
What are the workarounds, if we can't change the behavior?
The least we could do is stop calling it "delete" if it's actually not a "delete." Call it "hide from public" or "actually not delete" or something.
Related user voice:
* [Remove ability for 10k+ users to view self-deleted posts (declined)](https://web.archive.org/web/20090414190815/http://stackoverflow.uservoice.com:80/pages/general/suggestions/96223-remove-ability-for-10k-users-to-view-self-deleted-posts)
* [Implement "empty trash," or rename "delete" to "hide from public"](http://stackoverflow.uservoice.com/pages/1722-general/suggestions/234454-implement-empty-trash-or-rename-delete-to-hide-from-public-)
**Edit**: Recovery of a *deleted-but-good answer* is a practical benefit for the community, but I see that as creepy dangerous feature. IMHO, each user *should* have the rights to take back his or her perfectly good answer, and that the protecting privacy outweighs the benefit or creepiness.
I understand that it's all possible to find things out from Google cache or wherever, but why promote this as default behavior? As 10k rep user, I see others deleted answers by default. @codinghorror wrote:
>
> But like any version control system, deletions are illusory.
>
>
>
Anything and everything that's implemented by human is more or less illusory including phone system and the medical records. Should the government start tapping into phone lines and scanning for words? Remember, this is a question of *should* had we given the opportunity to design a system. | 2009/06/28 | [
"https://meta.stackexchange.com/questions/365",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/3827/"
] | This is nothing like email. You are posting info to a public forum, if anything it is more like NNTP. In that regard the 'CABAL' of the NTP admins could view everything including deletes. Anyone who captured the post pre delete sees it too (one very good reason the admins have to be able to see the deletes if they need to).
It's public, deal with it or don't post.
Does SO even restrict bots like the Wayback Machine?
Responding to more of your comments:
You have no rights except attribution. Again if this is a problem for you *don't post here*. Designing a system that allows very easy posting of content basically requires the people running it to look at what happened after the event. Since in SO case the 'admin like' status of 10K users is made very clear (asnd is basically necessary, the sort of paid for moderation required to do it only via 'official' people is prohibitive) if you have a problem with said status of those people you just shouldn't post anything you might not want deleting. | I'm not sure how many answers are actually un-deleted - it seems of much greater benefit to restore deleted *questions* - since it cascade-deletes other peoples answers (which they may have worked hard on)
Perhaps one solution could be - when an answer is deleted, the edit-history is destroyed, and only the current revision is kept.
This would allow someone, if they really want, to make something go away by editing the post to say "Opps", then deleting.. It wouldn't be an advertised feature, just an potentially useful side-effect. For the most part, people would just click delete and it can be viewed and restored if needs-be..
That said, when you post anything on the internet, it's pretty much there to stay - what if Google cached the embarrassing answer? What if the data-dump (an impossible to destroy torrent) was performed while the post was visible? |
24,636,372 | I have a HEALPix map that I have read in using healpy, however it is in galactic coordinates and I need it in celestial/equatorial coordinates. Does anybody know of a simple way to convert the map?
I have tried using `healpy.Rotator` to convert from (l,b) to (phi,theta) and then using `healpy.ang2pix` to reorder the pixels, but the map still looks strange.
It would be great if there was a function similar to `Rotator` that you could call like: `map = AnotherRotator(map,coord=['G','C'])`. Anybody know of any such function??
Thanks,
Alex | 2014/07/08 | [
"https://Stackoverflow.com/questions/24636372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1026674/"
] | I found another potential solution, after searching off and on for a few months. I haven't tested it very much yet, so please be careful!
Saul's **Solution 2**, above, is the key (great suggestion!)
Basically, you combine the functionality of `healpy.mollview` (`gnomview`, `cartview`, and `orthview` work as well) with that of the `reproject_to_healpix` function in the `reproject` package (<http://reproject.readthedocs.org/en/stable/>).
The resulting map is suitable for my angular scales, but I can't say how accurate the transformation is compared to other methods.
**-----Basic Outline----------**
**Step 1:** Read-in the map and make the rectangular array via `cartview`. As Saul indicated above, this is also one way to do the rotation. If you're just doing a standard rotation/coordinate transformation, then all you need is the `coord` keyword. From Celestial to Galactic coordinates, set `coord = ['C','G']`
```
map_Gal = hp.cartview(map_Cel, coord=['C','G'], return_projected_map=True, xsize=desired_xsize, norm='hist',nest=False)
```
**Step 2:** Write a template all-sky FITS header (as in the example below). I wrote mine to have the same *average* pixel-scale as my desired HEALPix map.
**Step 3:** Use `reproject.transform_to_healpix`
`reproject` includes a function for mapping a "normal" array (or FITS file) into the HEALPix projection. Combine that with the ability to return the array created by healpy.mollview/cartview/orthview/gnomview, and you can rotate a HEALPix map of one coordinate system (Celestial) into another coordinate system (Galactic).
```
map_Gal_HP, footprint_Gal_HP = rp.reproject_to_healpix((map_Gal, target_header), coord_system_out= 'GALACTIC', nside=nside, nested=False)
```
It comes down, essentially, to those two commands. However **you'll have to make a template header**, giving the pixel scale and size corresponding to the intermediary all-sky map you want to make.
**-----Full Working Example (iPython notebook format + FITS sample data)------**
<https://github.com/aaroncnb/healpix_coordtrans_example/tree/master>
The code there should run very quickly, but that's because the maps are heavily degraded. I did the same for my NSIDE 1024 and 2048 maps, and it took
about an hour.
**------Before and After Images------**
[](https://i.stack.imgur.com/eaPjp.png)
[](https://i.stack.imgur.com/ui7F6.png) | This function seems to do the trick (reasonably slow, but should be better than the for loop):
```
def rotate_map(hmap, rot_theta, rot_phi):
"""
Take hmap (a healpix map array) and return another healpix map array
which is ordered such that it has been rotated in (theta, phi) by the
amounts given.
"""
nside = hp.npix2nside(len(hmap))
# Get theta, phi for non-rotated map
t,p = hp.pix2ang(nside, np.arange(hp.nside2npix(nside))) #theta, phi
# Define a rotator
r = hp.Rotator(deg=False, rot=[rot_phi,rot_theta])
# Get theta, phi under rotated co-ordinates
trot, prot = r(t,p)
# Interpolate map onto these co-ordinates
rot_map = hp.get_interp_val(hmap, trot, prot)
return rot_map
```
Using this on data from `PyGSM` gives the following:
`hp.mollview(np.log(rotate_map(gsm.generated_map_data, 0,0)))`
[](https://i.stack.imgur.com/mNtwc.png)
Upon rotation of `phi`:
`hp.mollview(np.log(rotate_map(gsm.generated_map_data, 0,np.pi)))`
[](https://i.stack.imgur.com/Wc0zq.png)
Or rotating `theta`:
`hp.mollview(np.log(rotate_map(gsm.generated_map_data, np.pi/4,0)))`
[](https://i.stack.imgur.com/YqCJc.png) |
17,195,279 | I need to use an existing C library in a C++ project.
My problem is the C existing library uses FILE\* as streams, is there a standard compliant way to use FILE\* streams to put or to get from C++ streams?
I tried seeking FILE\* in the C++11 standard, but it appears only if few examples.
```
-
```
EDIT, example.
We have a function which write in a FILE\*:
fputs(char const\*, FILE\*)
We have an output C++ stream:
auto strm = std::cout;
Can I, in a standard compliant way, to use fputs to write to strm?
You can also think a similar input example with a C function that reads from a FILE\* and a input C++ stream. | 2013/06/19 | [
"https://Stackoverflow.com/questions/17195279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876111/"
] | The C++ standard, with very few exceptions says that C functionality is all included. Certainly all the stadnard C `FILE *` functionality is supported [obviously subject to general support for `FILE *` on the platform - an embedded system that doesn't have a 'files' (e.g. there is no storage) in general will hardly have much useful support for `FILE *` - nor will C++ style `fstream` work].
So, as long as you don't try to mix reading/writing to the same file from both C++ `fstream` and C `FILE *` at the same time, it should work just fine. You will need to close the file between C++ and C access, however. | As far as I understand, doing so is [non-portable and non-standard](http://stdcxx.apache.org/doc/stdlibug/34-2.html). Whether it works in practice or not is another question. I would create wrapper classes around your legacy code, or use FILE\* streams directly like in C - they are not that bad. :) |
1,616,876 | I have a new laptop (2 months old) with the following specs
* AMD Ryzen 4700
* AMD Radeon Graphics
* 8GB RAM 1200GHz
* 500GB storage SSD
and, most of the time, it boots very quickly (i'd say a few seconds) and runs perfectly. Sometimes, however, when it boots with low battery (maybe <20%) it does that incredibly slowly, and it also runs slowly when it's on. After a few restarts however it works fine.
Why is that?
Ps. It runs with Windows 10 | 2021/01/12 | [
"https://superuser.com/questions/1616876",
"https://superuser.com",
"https://superuser.com/users/1261142/"
] | Adobe removed the flash player download link from their website in 2021. Even if you have a spare copy of the installer on your computer, it still won't work as it's an "online installer" that retrieves a copy of the latest version from Adobe's website, which Adobe also deleted in 2021 so the installers Adobe provided for free download in 2020 won't work in 2021.
However I managed to get [an offline installer](http://gitlab.com/desbest/flash-player) that works for Windows, Mac, Linux, ActiveX, NPAPI and PPAPI. No internet connection is needed and it's version 32.0.0.465 the latest version.
I tried running the offline installer in 2021 and it works for me, even after Windows Update pushed an update that uninstalls Flash from the computer. You can check if Flash is installed by going to Control Panel, getting off category view. Click Flash to check the flash version, if there's no flash option then it's not installed.
The mainstream web browsers Edge, Chrome, Opera and Firefox removed support for all NPAPI plugins (chrome 45 in 2015, firefox 52 in 2017) and in 2021 they stopped their exception for Flash (chrome 87, firefox 85). So if you want a web browser that supports flash (by supporting NPAPI), use [Basilisk](https://github.com/darktohka/FlashPatch) web browser. Basilisk also supports XUL extensions that Firefox no longer supports.
So it looks like Adobe added a kill switch to Flash so the installed software would stop working after a certain date, being 12th January 2021 12/01/21. All flash embeds would be replaced with this image.

I've found 2 solutions to this.
Solution 1: FlashPatch
======================
FlashPatch is a free software that patches the flash player already installed on your computer.

Flashpatch says to run the file as administrator, but for me I didn't need to.
It can now patch any version of flash, so it'll work with older versions, not just 32.0.0.465 for chrome (PPAPI), firefox and safari (NPAPI) and for Internet Explorer (ActiveX).
[Download FlashPatch](https://github.com/darktohka/FlashPatch)
[I have the latest version of flash as an offline installer here.](http://gitlab.com/desbest/flash-player)
Solution 2: Edit mms.cfg
========================
The kill switch adobe uses, changes the `EnableAllowList` value in `mms.cfg` from `0` to `1` by force, so even if you change it to `0` Flash will ignore it after 12/01/21 and still keep it as `1`. What this means is that instead of flash being enabled for all websites, you now have to whitelist every website you want flash to run on.
On your computer you need to edit the `mms.cfg` file.
This file can be found under:
* `/Library/Application Support/Macromedia/mms.cfg` for Mac OS X
* `C:\Windows\System32\Macromed\Flash\mms.cfg` for 32 bit Windows
* `C:\Windows\SysWOW64\Macromed\Flash\mms.cfg` for 64 bit Windows
Make sure add these lines to the file with the website to whitelist, and modify them to suit the domains to whitelist. You can have multiple `AllowListUrlPattern` lines.
```
# Enable running flash on
# only whitelisted websites
# the 12/02/21 killswitch forces this to 1
AllowListPreview=1
# Pattern to enable Your Legacy Flash Web App:
# AllowListUrlPattern=file:
# AllowListUrlPattern=*://ferryhalim.com*
# AllowListUrlPattern=*://*.ferryhalim.com
```
For good measure, you can also add
```
# Disable Automatic Updates
AutoUpdateDisable=1
SilentAutoUpdateEnable=0
# Error reporting
ErrorReportingEnable=0
# Disable prompts to uninstall Flash Player
EOLUninstallDisable = 1
# duplicate actionscript console output
# in browser's console for javascript
# TraceOutputEcho=0
```
You cannot have a `*` wildcard for the domain/dns name or TLD, but you can for the `host` and `subdomain`, so you don't need to have 2 lines for `http` and `https` or a new line for every subdomain.
Refresh the page or restart your web browser and it should work. Technical documentation on how to use `AllowListUrlPattern` is on Page 37 of [this adobe pdf](https://www.adobe.com/content/dam/acom/en/devnet/flashplayer/articles/flash_player_admin_guide/pdf/latest/flash_player_32_0_admin_guide.pdf). | I spent many hours on this and eventually found *my ideal solution*. After that, I found out other people are suggesting something very similar. However, I am still posting it since I am sure it will help some people, because of some details and because I am providing a working sample.
What I did is setting up a portable version of 32-bit Google Chrome for Windows equipped with last time-bomb-free version of PPAPI (Pepper) Adobe Flash.
Here it is a step-by-step description:
1. Download Google Chrome Portable 87.0.4280.88 32-bit from [PortableApps.com](https://sourceforge.net/projects/portableapps/files/Google%20Chrome%20Portable/) - please note that the latest version will not work. Some people say you need a version older than 88.0.4324.96
2. Install it and execute it. Navigate to chrome://settings/content and enable Flash
3. Install Flash Player PPAPI 32.0.0.371 (not a more recent one) downloading it from [web.archive.org](http://web.archive.org/web/20200516003347if_/http://fpdownload.macromedia.com/pub/flashplayer/latest/help/install_flash_player_ppapi.exe) or [other archived copy](https://mega.nz/file/5gsRyYDS#ayvwSx5DH3VIhCxXSrx_F8idEn9FHNBNv044dwkhQmM). When asked, disable every update of course.
4. Browse to folder C:\Windows\System32\Macromed\Flash (or C:\Windows\SysWOW64\Macromed\Flash on 64-bit Windows) and copy files:
* pepflashplayer32\_32\_0\_0\_371.dll
* manifest.json
5. Paste these two files into GoogleChromePortable\Data\profile\PepperFlash\32.0.0.371\ (new folder) and rename the dll as pepflashplayer.dll
When everything's done, you can visit Flash websites allowing them with usual per-site temporary setting.
A note about step 3: I performed it in a VirtualBox environment, so I am not sure if it will work on an updated computer. In this case, I suggest you find an old computer or use a virtualized Windows 7. Just to be clear: the final product works on any PC (i.e. updated Windows 10 non-virtual machine).
If you don't want to go through all above steps, you can [download a copy I uploaded here (87 MB)](https://mega.nz/file/x90QkS7I#m_v96jS_IbCs-oL0ZiYvktuONffP_M2hulY5jKb0rA0). This is a careful copy I created where only above steps where performed.
And of course, I recommend you use it only for trusted websites, since you are running a no-more-supported software on top of an outdated browser. I believe it has its use cases, though. My use case is the opportunity to open the settings for an old Netgear Stora NAS through its Flash-only interface.
[](https://i.stack.imgur.com/wNdKV.gif) |
37,803,940 | am getting an error like
```
Unknown column 'code' in 'where clause'
SELECT * FROM `payment` WHERE `code` = 'ORD00023'
```
even though i had used joined method for joining of payment table and services table.Here iam finding the solution of previous row value but its not getting.
this is my model
```
public function order_balance($order_code)
{
$this->db->query("
SELECT p1.*
, p2.balance AS previous_balance
FROM payment p1
JOIN payment p2
ON p1.order_id = p2.order_id + 1
AND p1.customer_id = p2.customer_id
LEFT
JOIN services s
ON p1.customer_id = s.customer_id
ORDER BY p1.id DESC
");
$query = $this->db->get_where('payment p1', array('code' => $order_code));
return $query;
}
```
this is my table payment
```
id order_id customer_id amount actual_amount paid_amount balance type
25 11 16 100.00 50.00 50.00 Cash
26 12 16 200.00 100.00 100.00 Cash
27 13 16 150.00 100.00 50.00 Cash
28 14 16 300.00 250.00 50.00 Cash
29 14 16 170.00 100.00 70.00 Cash
30 15 16 100 170.00 70.00 100.00 Cash
31 16 16 400 500.00 300.00 200.00 Cash
```
this is table services
```
id code customer_id particulars
11 ORD00011 16 phone
12 ORD00012 16 gdf
13 ORD00013 16 ghgfh
14 ORD00014 16 tv
15 ORD00015 16 ghfg
16 ORD00016 16 tv
17 ORD00017 16 gdfg
18 ORD00018 16 desk
19 ORD00019 16 gdf
```
Here i have joined the payment table and services table but still not getting
see my table
```
id order_id customer_id amount actual_amount paid_amount balance type
50 31 16 650 750.00 250.00 500.00 Cash
51 1 16 100 600.00 300.00 300.00 Cash
52 2 16 100 400.00 200.00 200.00 Cash
53 3 16 800 1000.00 600.00 400.00 Cash
54 4 15 400 400.00 300.00 100.00 Cash
55 5 15 500 600.00 575.00 25.00 Cash
56 6 16 350 750.00 600.00 150.00 Cash
```
in this table the customer\_id of `16` having the previous row value of balance 25 and am getting like this but i want the last customer\_id `16` balance value as the previous customer\_id `16` value.
for example my result should look like this
```
id order_id customer_id amount actual_amount paid_amount balance type
56 6 16 350 750.00 600.00 400.00 Cash
``` | 2016/06/14 | [
"https://Stackoverflow.com/questions/37803940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5064637/"
] | Did you want this?
```
$this->db->query("SELECT p1.*, p2.balance AS previous_balance FROM payment p1 INNER JOIN payment p2 ON p1.order_id = p2.order_id + 1 AND p1.customer_id = p2.customer_id LEFT JOIN services s ON p1.customer_id = s.customer_id AND s.code = ? ORDER BY p1.id DESC", array($order_code));
``` | This is showing error because you are missing alias of table name, in which column code is available. replace code
```
$query = $this->db->get_where('payment p1', array('code' => $order_code));
```
with
```
$query = $this->db->get_where('payment p1', array('services.code' => $order_code));
```
or
```
$query = $this->db->get_where('payment p1', array('s.code' => $order_code));
``` |
10,825,619 | I think everyone's (mostly beginner of CI users) facing difficulties in pagination using with active record.
In CI's official documents, there is no clear statements explains how to use pagination class object in active record. My problem is; can not define current page and set it to SQL statement. Therefore, when program fetches data from MySQL with pagination, all page navigates first 0 and `$config['per_page'];`. I mean if I set to `per_page=20`, all pages link's fetches 0,20 of MySQL rows.
**My SQL Statement is:**
```
$this->db->query("SELECT b.*, a.adCampaignTitle FROM ads a, sms b WHERE b.`smsAd_ID`=a.ad_ID LIMIT " . $config['per_page'])->result();
```
**My Pagination Class properties :**
```
$this->load->database();
$config['base_url'] = 'http://localhost/index.php/admin/index/page/';
$config['total_rows'] = $this->db->count_all('sms');
$config['per_page'] = 2;
$this->pagination->initialize($config);
```
If somebody help me to how-to-initialize and set to **current page** into SQL part I will be very glad ... | 2012/05/30 | [
"https://Stackoverflow.com/questions/10825619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1405703/"
] | Assuming you have *Manage Jenkins > Configure Global Security > Enable Security* and *Jenkins Own User Database* checked you would go to:
* *Manage Jenkins > Manage Users > Create User* | You need to *Enable security* and set the security realm on the *Configure Global Security* page (see: [Standard Security Setup](https://wiki.jenkins.io/display/JENKINS/Standard+Security+Setup)) and choose the appropriate Authorization method (*Security Realm*).
[](https://i.stack.imgur.com/XEvgU.png)
Depending on your selection, create the user using appropriate method. Recommended method is to select *Jenkins’ own user database* and tick *Allow users to sign up*, hit Save button, then you should be able to create user from the Jenkins interface. Otherwise if you've chosen external database, you need to create the user there (e.g. if it's Unix database, use credentials of existing Linux/Unix users or create a standard user using shell interface).
See also: [Creating user in Jenkins via API](https://stackoverflow.com/q/17716242/55075) |
446,627 | I have a data table with product images that I want to filter depending on who I send the spreadsheet to. The pictures are still visibly stacked on top of each other.
How do I set up my sheet so that when rows/products are hidden (via data filter), their corresponding pictures are also hidden? | 2012/07/09 | [
"https://superuser.com/questions/446627",
"https://superuser.com",
"https://superuser.com/users/144869/"
] | * You can also use the Select button and select all the pictures by dragging a box around all pictures. Then right click properties etc., or
* Select one picture and hit `CTRL`+`A` (select All), then right click properties etc.
Excel seems to understand that when selecting one picture and you press Select all (`CTRL`+`A`), you want to select all pictures. | I had the same issue with Excel 2016 and used a combination of answers to solve this:
1. Ctrl+G or F5
2. Select Special, then 'Objects' and click 'OK'
3. Right-click on one of the images and click Size and Properties
4. Select 'Move and size with cells' from 'Properties' and close
5. Done
HOWEVER ONLY filtering works, sorting doesn't work properly. I have three columns with images. If I sort the one in the middle A-Z, the right column will sort properly, but not the left one. The left one is either missing images or overlapping again. |
57,238,602 | This long question can be combined into one simple sentence: **How do I set a border of a table selectively (bottom or top) without impacting its tr or td elements?** I thought it would be as simple as changing the border of any element. I was wrong.
**The rest of the question explains where I need this and what I have tried so far.**
Here is a simplified description of the HTML markup:
There are three divs with three tables. I want to make them look as a single table. The three divs are required for reasons not relevant here.
If I use the following:
```js
$('#tbl1').css('border-bottom', 'none');
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<table id="tbl1" border="1" style="width:400px;" >
<thead>
<tr>
<td>Head Row 1, cell 1</td>
<td>Head Row 1, cell 2</td>
<td>Head Row 1, cell 3</td>
</tr>
<tr>
<td>Head Row 2, cell 1</td>
<td>Head Row 2, cell 2</td>
<td>Head Row 2, cell 3</td>
</tr>
</thead>
</table>
</div>
<div id="div2" >
<table id="tbl2" style="width:400px;" border="1">
<tbody>
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
<td>Row 1, cell 3</td>
</tr>
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
<td>Row 1, cell 3</td>
</tr>
</tbody>
</table>
</div>
<div id="div3" >
<table id="tbl3" border="1" style="width:400px;">
<tfoot>
<tr>
<td>Foot Row 1, cell 1</td>
<td>Foot Row 1, cell 2</td>
<td>Foot Row 1, cell 3</td>
</tr>
<tr>
<td>Foot Row 2, cell 1</td>
<td>Foot Row 2, cell 2</td>
<td>Foot Row 2, cell 3</td>
</tr>
</tfoot>
</table>
</div>
```
it takes the lower border of all cells in the first table and not just the table's bottom-border. If I use:
```js
$('#tbl1' + ' tr:last-child').css('border-bottom', 'none')
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<table id="tbl1" border="1" style="width:400px;" >
<thead>
<tr>
<td>Head Row 1, cell 1</td>
<td>Head Row 1, cell 2</td>
<td>Head Row 1, cell 3</td>
</tr>
<tr>
<td>Head Row 2, cell 1</td>
<td>Head Row 2, cell 2</td>
<td>Head Row 2, cell 3</td>
</tr>
</thead>
</table>
</div>
<div id="div2" >
<table id="tbl2" style="width:400px;" border="1">
<tbody>
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
<td>Row 1, cell 3</td>
</tr>
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
<td>Row 1, cell 3</td>
</tr>
</tbody>
</table>
</div>
<div id="div3" >
<table id="tbl3" border="1" style="width:400px;">
<tfoot>
<tr>
<td>Foot Row 1, cell 1</td>
<td>Foot Row 1, cell 2</td>
<td>Foot Row 1, cell 3</td>
</tr>
<tr>
<td>Foot Row 2, cell 1</td>
<td>Foot Row 2, cell 2</td>
<td>Foot Row 2, cell 3</td>
</tr>
</tfoot>
</table>
</div>
```
it does take the bottom border of the last row of the first table but retains the bottom-border of the table itself.
The above problems, of course, are repeated for handling the situation for the lowest two tables.
My goal is to have all traces of borders joining the tables be removed so that I can assign one thick or any other type of border to one table as the table-separator. So, to clarify further:
The bottom border of the first table and the top border of the second table as well as the corresponding borders of the tr and tds of the corresponding rows must be removed.
The top border of third table and the bottom border of the second table as well as the corresponding border of the tr and tds of the corresponding rows must be removed.
After this I can set any border I want to act as a table separator.
The middle table will be scrollable so I will be placing a new bottom border on the top table and a new top-border on the bottom border.
The solution must be as generic as possible to accommodate any possible table layout but with the restriction that a row is a tr and that each table will have at least one tr. | 2019/07/28 | [
"https://Stackoverflow.com/questions/57238602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9158613/"
] | The character class `[\S^\n*.$]` matches 1 time any of the listed, that is why it does not math `2019-07:27`.
If you want to match `2019-07-27_2313hr_19sec` you could match the "date like" format and follow the match by matching 0+ times a non whitespace char `\S*`
```
\d{4}[-/:._]\d{2}[-/:._]?\d{2}\S*
```
[Regex demo](https://regex101.com/r/QxZG2d/1) | [Python demo](https://ideone.com/xXQLpl)
For example
```
import re
date_time_reg_exp = re.compile(r'\d{4}[-/:._]\d{2}[-/:._]?\d{2}\S*')
s = ("2019-07:27 22:04:38.635317100 -0700\n"
"2010/08/26\n"
"2019-07-27_2313hr_19sec\n"
"2019-07.27")
print(re.findall(date_time_reg_exp, s))
```
Result
>
> ['2019-07:27', '2010/08/26', '2019-07-27\_2313hr\_19sec', '2019-07.27']
>
>
> | The negation operator needs to be the first character to create a negated character class. To do what you attempted, maybe try `[^\s\n]`. There is no way for a character class to be partially negated (if you think about it, what would that mean?) - it's either an enumeration of allowed characters, or an enumeration of disallowed characters starting with the negation operator `^`. |
160,870 | I've worked with a company for some time and we had a few interview seasons. I've participated in two of them so far. Anyways, since the pandemic, I've honestly felt less inclined (maybe lazy) to want to do any interviews any more. Anyways, they had a hold on the third interview season a few months ago and during that time I've become accustomed to my new work environment.
I never really liked interviewing and always found the process quite stressful. I also feel somewhat disconnected with the company so having to put my best face (or in this case best voice) has become a chore. Going through the company's dribble and trying to get people interested in the company, it just goes against my very nature if I've gotten somewhat less enthusiastic. In any case, this season we are getting set up to do interviews again but I have not drummed up the courage to excuse myself. Our organization is pretty large and we have over 100 people helping with interviews in the department alone.
I missed the training for the new interviewing process because I was too busy taking care of my day to day tasks, though I am familiar with my Organization's interviewing process, I imagine its quite similar to what we have done in the past but probably with a few modifications.
I don't really know how to excuse myself from interviewing this season. I don't really want to come off as disengaged although I know I am and at the same time I really don't want to let my organization down and not be 100% available to them. I'd really prefer if I get off the interviewer's list, I know its completely voluntary but excusing myself just seems like you have no company spirit or care about the organization, which just feels so selfish. Is there a way that I can communicate to the interview organizer's that I would like to excuse myself this year without sounding bad? Unfortunately, I just got scheduled to do an interview. I have been so busy that I forgot to send out a notice to please not schedule me but because I have so many conflictions I haven't communicated my intent so they scheduled me now. Advice would be appreciated. | 2020/07/23 | [
"https://workplace.stackexchange.com/questions/160870",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/78879/"
] | >
> has become a chore
>
>
>
Well, work isn't fun - that's kind of why they have to pay people to do it.
That said there's no harm in asking to be taken out of consideration to act as an interviewer - assuming it's not something that would be considered a core part of your role of course.
I'd probably avoid alluding to the reason being that you're feeling disillusioned or disengaged with the company or similar though, if you want to address that and rectify it (and it's probably worth doing if the situation continues) this isn't the way.
This:
>
> I missed the training for the new interviewing process because I was too busy taking care of my day to day tasks
>
>
>
Provides a couple of options though - you could say that you don't feel like you should be conducting interviews while your training is out of date, of course this might just lead them to either arrange catch-up training or say that it's not a problem. What is probably better is to focus on the second part - that you're busy with day to day tasks, and say that you feel that you need to be giving your main tasks and responsibilities your full focus at this point in time. After all this is *really* what they are paying you to be doing - and it protects you from accusations of being work-shy, since the reason you're bowing out of interviewing is so you can do *more* work. | Well, not everybody is good at everything. You should talk to your manager and explain that you want to e left out from the interviewing, *if possible*.
As a reasoning, present the following:
* you had the initiative and good will to learn and to get involved and to make yourself useful;
* you found out that this is not really for you, *the way you see it*.
I learned that presenting hard decisions is not very easy to swallow. Leave the other person to make the decisions for you.
---
The worst case that I see is that your manager will not want to exclude you from interviewing. In this case you must make some decision about your life, and we cannot help you. Either you do it your way, and the boss gets angry, or you accept the boss's way and you remain angry. |
1,587,723 | im beginning in Objective-C development and as i can see in the development blogs(about Objective-C) like w3schools.com we dont have such type of sutes to learn Objective-c language , can any one known the such type of Sites to Learn objective-c language .. please let me know-- | 2009/10/19 | [
"https://Stackoverflow.com/questions/1587723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/185590/"
] | <http://cocoaheads.byu.edu/resources> | In addition to the above-listed resources, I've found a lot of good stuff on <http://www.cocoadevcentral.com/> |
31,534,082 | This is my sample string (this one has five words; in practice, there may be more):
```
$str = "I want to filter it";
```
Output that I want:
```
$output[1] = array("I","want","to","filter","it");
$output[2] = array("I want","want to","to filter","filter it");
$output[3] = array("I want to","want to filter","to filter it");
$output[4] = array("I want to filter","want to filter it");
$output[5] = array("I want to filter it");
```
What I am trying:
```
$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output[$len][] = $text; // last element
$output[1] = $text_exp; // first element
```
This gives me the first and the last arrays. How can I get all the middle arrays? | 2015/07/21 | [
"https://Stackoverflow.com/questions/31534082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1712287/"
] | more generic solution that works with any length word:
```
$output = array();
$terms = explode(' ',$str);
for ($i = 1; $i <= count($terms); $i++ )
{
$round_output = array();
for ($j = 0; $j <= count($terms) - $i; $j++)
{
$round_output[] = implode(" ", array_slice($terms, $j, $i));
}
$output[] = $round_output;
}
``` | You can use a single for loop and if conditions to do
```
$str = "I want to filter it";
$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output1=$text_exp;
$output2=array();
$output3=array();
$output4=array();
$output5=array();
for($i=0;$i<count($text_exp);$i++)
{
if($i+1<count($text_exp) && $text_exp[$i+1]!='')
{
$output2[]=$text_exp[$i].' '.$text_exp[$i+1];
}
if($i+2<count($text_exp) && $text_exp[$i+2]!='')
{
$output3[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2];
}
if($i+3<count($text_exp) && $text_exp[$i+3]!='')
{
$output4[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2].' '.$text_exp[$i+3];
}
if($i+4<count($text_exp) && $text_exp[$i+4]!='')
{
$output5[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2].' '.$text_exp[$i+3].' '.$text_exp[$i+4];
}
}
``` |
56,129,953 | How to print this dynamically?
```
data = {
"name": "EU",
"size": 10,
"nodes": [
{
"name": "England",
"size": 2,
"nodes": [
{
"name": "Center",
"size": 1,
"nodes": [
{
"name": "main street",
"size": 0.5,
"nodes": []
}
]
},
{
"name": "Vilage",
"size": 1,
"nodes": []
}
]
},
{
"name": "Germany",
"size": 4,
"nodes": []
}
]
}
```
and I need somehow dynamically print it like this
```
EU 10
EU - England 2
EU - England - Center 1
EU - England - Center - main street 0.5
EU - England - Vilage 1
EU - Germany 4
```
This is the code that i have closest what I need
```js
var data = { "name": "EU", "size": 10, "nodes": [ { "name": "England", "size": 2, "nodes": [ { "name": "Center", "size": 1, "nodes": [ { "name": "main street", "size": 0.5, "nodes": [] } ] }, { "name": "Vilage", "size": 1, "nodes": [] } ] }, { "name": "Germany", "size": 4, "nodes": [] } ] }
function printValues(obj) {
for (var key in obj) {
if (typeof obj[key] === "object") {
printValues(obj[key]);
} else {
console.log(obj[key]);
}
}
}
printValues(data)
```
This is what I get
 | 2019/05/14 | [
"https://Stackoverflow.com/questions/56129953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9127066/"
] | You were on the right track - you can indeed use recursion to walk the data structure. What you also need is to get the `name` property and build up a the start of each line from each `name` encountered. You can ferry that information using a second parameter to the recursive function. Then you need to recursively call the function for each child node and pass all the `name`s encountered so far:
```js
const data = { "name": "EU", "size": 10, "nodes": [ { "name": "England", "size": 2, "nodes": [ { "name": "Center", "size": 1, "nodes": [ { "name": "main street", "size": 0.5, "nodes": [] } ] }, { "name": "Vilage", "size": 1, "nodes": [] } ] }, { "name": "Germany", "size": 4, "nodes": [] } ] }
function printValues(data, prefix = []) {
//make a copy of the prefix instead of mutating it
let location = prefix.concat(data.name);
console.log(location.join(" - "), data.size);
data.nodes.forEach(child => printValues(child, location))
}
printValues(data)
``` | One way is to use recursion on the nodes list:
I'm outputting the results with console.log.
Changed thanks to comment by VLAZ.
```js
var data = { "name": "EU", "size": 10, "nodes": [ { "name": "England", "size": 2, "nodes": [ { "name": "Center", "size": 1, "nodes": [ { "name": "main street", "size": 0.5, "nodes": [] } ] }, { "name": "Vilage", "size": 1, "nodes": [] } ] }, { "name": "Germany", "size": 4, "nodes": [] } ] }
function printValues(prefix,obj) {
if (typeof obj !== "object") return;
prefix = prefix?(prefix+" - "+obj.name) : obj.name;
console.log(prefix+" "+obj.size);
for (var key in obj.nodes) {
printValues(prefix,obj.nodes[key]);
}
}
printValues("",data);
``` |
1,309,926 | I'm developing a web app specifically for mobile phones, and I've run into a doozy of a problem. On the Blackberry emulator I've installed, everything works fine. But when I run my Openwave or Nokia N60 emulators, I can't log into my app any more. When I check the logs, I find that the reason is that ALL of the $\_POST variables are empty.
I've run through just about everything I can think of that would be the problem, and I'm still stuck. I've tried all three of the DOCTYPEs that Wikipedia lists, on the off chance that that's it, I've tried sending all kinds of different headers, and I'm just stumped.
My last idea is that perhaps my form code itself is wrong? I enclose a table in my form, and all the examples I've seen enclose a paragraph with the form.
I.e. In the examples I see:
```
<form>
<p>
... stuff ...
</p>
</form>
```
And I have:
```
<form action="/" method="POST" class="formic">
<table class="mobile-form">
<tr>
<td colspan="2" class="label required">Email address</td>
</tr>
<tr>
<td colspan="2" class="data"><input type="text" name="email" class="text" /></td>
</tr>
<tr>
<td colspan="2" class="label required">Password</td>
</tr>
<tr>
<td><img src="/images/exclamation.png" class="error_icon" value="/images/exclamation.png" /></td>
<td class="data"><input type="password" name="password" class="text" /></td>
</tr>
<tr>
<td colspan="2" class="data field-error">You must enter a password.</td>
</tr>
<tr>
<td colspan="2" class="label required">Sign in to:</td>
</tr>
<tr>
<td colspan="2" class="data">
<select name="aspect">
<option value="web">Web interface</option>
<option selected="selected" value="mobile">Mobile interface</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="hidden" name="saved_aspect" value="0" />
<label>
<input type="checkbox" name="saved_aspect" checked="checked" value="1" />
Save interface choice on this computer.
</label>
</td>
</tr>
<tr>
<td colspan="2" class="submit"><input type="submit" name="" class="submit" value="Log in" /></td>
</tr>
</table>
</form>
```
Could that be it? Where would I find the documentation/specifications that would demonstrate this? | 2009/08/21 | [
"https://Stackoverflow.com/questions/1309926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8327/"
] | Show us the code for the input button (and general form). I think I've had this problem before, and the button wasn't of type 'submit' (or some other very very stupid mistake like that). | Does the behavior change if you post to a page rather than the root of the site? |
13,435,023 | I came across this question:
There are two persons. There is an ordered sequence of n cities, and the distances between every pair of cities is given. You must partition the cities into two subsequences (not necessarily contiguous) such that person A visits all cities in the first subsequence (in order), person B visits all cities in the second subsequence (in order), and such that the sum of the total distances travelled by A and B is minimized. Assume that person A and person B start initially at the first city in their respective subsequences.
I looked for its answer and the answer was:
Let c[i,j] be the minimum distance travelled if first person stops at city i and second at city j. Assume i< j
c[0,j]= summation of (d[k,k+1]) for k from 1 to j-1
c[i,j] = min(c[k,j]+ d[k,i]) if i!=0 where 0
The solution can also be seen at question 10 [here](http://courses.csail.mit.edu/6.006/fall10/handouts/dpproblems-sol.pdf)
Now, my problems are:
1. This solution has no definition for i=1 (as then k has no value).
2. Now, suppose we are finding c[2,3]. It would be c[1,3]+ d[1,2]. Now c[1,3] means person
B visited 0, 2 and 3 and person A remained at 1 or person B visited 2 and 3 and A
visited 0 and 1. Also, c[2,3] means A visited just 2/ 0,1,2 /0,2 /1,2. So,
```
c[1,3] = min(d[0,1]+ d[2,3], d[0,2]+ d[2,3])
c[2,3] = min(d[0,1]+ d[1,2], d[0,2]+ d[1,3], d[1,2]+d[0,3], d[0,1]+d[1,3])
```
As can be seen the solutions are not overlapping.
To put it in other way, 2 is already covered by B in c[1,3]. So if we include c[1,3] in c[2,3] it would mean that 2 is visited by both A and B which is not required as it would just increase the cost.
Please correct me if I am wrong. | 2012/11/17 | [
"https://Stackoverflow.com/questions/13435023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648290/"
] | Q:: Two-Person Traversal of a Sequence of Cities: You are given an ordered sequence of n cities, and the distances between every pair of cities. Design an algorithm to partition the cities into two subsequences (not necessarily contiguous) such that person A visits all cities in the first subsequence (in order), person B visits all cities in the second subsequence (in order), and the sum of the total distances travelled by A and B is minimised. Assume that person A and person B start initially at the first city in their respective subsequences.
Here is how I understood the solution ::
Let us say the cities are number from 1 to n. We recurse on C(i, j), the minimum distance traveled if person A ends at city i and person B ends at city j. Assume without loss of generality i < j.
Let C(0, n) denote that person A does not visit any city, while person B visits all the cities from [1, n].
Hence, C(0, j) = d(1,2) + d(2,3) + .... + d(j-1, j) (B starting from city 1, going in order till city j).
C(i, j), where i is not 0 = minimum of following two cases :
case 1 : person A starts and stops at city i. In which case, C(i, j) = distance travelled by person B, travelling to all cities from 1 to j in order, skipping city i = d(1,2) + d(2,3) + ... + d(i-1, i+1) + d(i+1, i+2) + ... + d(j-1, j)
case 2 : person A starts at some city before i, and hence there is a city k which he travels just before going to city i (second last city in his traversal). In this case, C(i, j) = minimum {C(k, j) + d(k, i)} where k can vary from 1 to i-1.
The solution to the problem is minimum { C(i,n) } where i varies from 0 to n-1.
We can fill the DP matrix in row major order, as each calculation of C(i,j) requires either the distances d, or C(k,j) where k < i.
The running time of the algorithm will be O(n^3), as there are O(n^2) entries for which we do the calculation, and each calculation takes O(n) time.
Edit :: I think the solution given in the handout is missing case1. | You're right that the proposed solution is somewhat messy and incorrect.
The way to think about the problem is, as always, inductive: If I need to solve the problem of size n, how can I reduce it to smaller problems (0,..., n-1). If you'd like to solve this problem for size n, you note that one of the players needs to take the node n into their path.
The C[i, j] function is a helper function denoting as you described "minimal cost with A stopping at i and B stopping at j".
To arrive to the state C[i,j] player B had to come to j from j-1, unless of course j-1 = i. In the case that j-1 = i, then j had to come from some k < i. Therefore the function C[i, j] can be described as follows:
```
C[i,j] = {
C[i,j-1] + d[j-1,j] (if i < j-1)
min C[k,i] + d[k,j] for 0 <= k < i (if i = j-1)
}
```
With this setting your base case is simply C[0, 1] = d[0,1].
Your final answer is then min C[k, n] for 0 <= k < n. |
30,721 | I recently switched from Textpad to Notepad++. Overall, I have found N++ to generally be superior, but one of the few things I have been looking for since the beginning that I have not found is the ability to extend the current selection to the next blank line.
In Textpad, this is done with `ctrl` + `shift` + `up` or `ctrl` + `shift` + `down`. | 2009/08/27 | [
"https://superuser.com/questions/30721",
"https://superuser.com",
"https://superuser.com/users/7548/"
] | By default `Ctrl` `[` and `Ctrl` `]` move up and down "paragraphs".
So `Ctrl` `Shift` `[` and `Ctrl` `Shift` `]` will do what you want.
To edit the shortcut, go to *Settings > Shortcut Mapper > Scintilla Commands* and edit the SCI\_PARA\* commands. | It's simply `shift` + `up/down` without pressing `control`. |
62,904,386 | I would be using kotlin regex engine.
There are a lot of other questions posted about matching unescaped quotes, but I'm struggling to implement my specific case.
Some example text:
```
"the Five Aggregates (from Sanskrit \"skandha\") (Buddhism)"
```
I want to match the whole pattern with something like
```
\"[^"]*\"
```
where `[^"]` is anything that isn't a `"`, however this is also matching the `\"` so I'm getting matches of
```
"the Five Aggregates (from Sanskrit \"
```
and
```
\") (Buddhism)"
```
So essentially I want to match `"[^unescapedquote]*"`
I tried to use an answer from a previous post like `"[^(?!<\\)"*]"`
But this didn't give me any matches. | 2020/07/14 | [
"https://Stackoverflow.com/questions/62904386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10326441/"
] | That's probably because the element scrolling is not the body. Take as example this snippet. I am binding the scrolling to the body, but since the element scrolling is the and not the body, the element won't be triggered. You should check out your style and your dom.
```js
document.body.addEventListener('scroll', () => {
console.log('Hi')
const elem = document.createElement('div');
elem.innerText = 'Hi';
document.body.appendChild(elem);
});
```
```html
<html>
<body>
<main style="height: 3000px">
<div>Hello</div>
<div>This</div>
<div>Is</div>
<div>A</div>
<div>Test</div>
</main>
</body>
</html>
``` | i faced this problem during last project you need to fill the quotation of html
the solution is
```js
import HomeModule from "./home";
HomeModule.init();
document.getElementById("app").innerHTML = `<div class="page__inner"><main class="main main_width-limit"><header class="main__header"><div class="main__header-inner"><div class="main__header-group"><ol class="breadcrumbs"><li class="breadcrumbs__item breadcrumbs__item_home"><a class="breadcrumbs__link" href="/"><span class="breadcrumbs__hidden-text">Tutorial</span></a></li><li class="breadcrumbs__item" id="breadcrumb-1"><a class="breadcrumbs__link" href="/ui"><span>Browser: Document, Events, Interfaces</span></a></li><li class="breadcrumbs__item" id="breadcrumb-2"><a class="breadcrumbs__link" href="/event-details"><span>UI Events</span></a></li><script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Tutorial","item":"https://javascript.info/"},{"@type":"ListItem","position":2,"name":"Browser: Document, Events, Interfaces","item":"https://javascript.info/ui"},{"@type":"ListItem","position":3,"name":"UI Events","item":"https://javascript.info/event-details"}]}</script></ol><div class="updated-at" data-tooltip="Last updated at 2nd December 2019"><div class="updated-at__content">2nd December 2019</div></div></div><h1 class="main__header-title">Scrolling</h1></div></header><div class="content"><article class="formatted" itemscope="" itemtype="http://schema.org/TechArticle"><meta itemprop="name" content="Scrolling"><div itemprop="author" itemscope="" itemtype="http://schema.org/Person"><meta itemprop="email" content="iliakan@gmail.com"><meta itemprop="name" content="Ilya Kantor"></div><div itemprop="articleBody"><p>The <code>scroll</code> event allows to react on a page or element scrolling. There are quite a few good things we can do here.</p>
<p>For instance:</p>
<ul>
<li>Show/hide additional controls or information depending on where in the document the user is.</li>
<li>Load more data when the user scrolls down till the end of the page.</li>
</ul>
<p>Here’s a small function to show the current scroll:</p>
<div data-trusted="1" class="code-example" data-autorun="true" data-prism-highlighted="1">
<div class="codebox code-example__codebox">
<div class="codebox__code" data-code="1">
<pre class="line-numbers language-javascript"><code class=" language-javascript">window<code class="token punctuation">.</code><code class="token function">addEventListener</code><code class="token punctuation">(</code><code class="token string">'scroll'</code><code class="token punctuation">,</code> <code class="token keyword">function</code><code class="token punctuation">(</code><code class="token punctuation">)</code> <code class="token punctuation">{</code>
document<code class="token punctuation">.</code><code class="token function">getElementById</code><code class="token punctuation">(</code><code class="token string">'showScroll'</code><code class="token punctuation">)</code><code class="token punctuation">.</code>innerHTML <code class="token operator">=</code> window<code class="token punctuation">.</code>pageYOffset <code class="token operator">+</code> <code class="token string">'px'</code><code class="token punctuation">;</code>
<code class="token punctuation">}</code><code class="token punctuation">)</code><code class="token punctuation">;</code></code><span class="line-numbers-rows"><span></span><span></span><span></span></span></pre>
</div>
</div>
</div><p>In action:</p>
<p>Current scroll = <b id="showScroll">43.20000076293945px</b></p>
<p>The <code>scroll</code> event works both on the <code>window</code> and on scrollable elements.</p>
<h2><a class="main__anchor" name="prevent-scrolling" href="#prevent-scrolling">Prevent scrolling</a></h2><p>How do we make something unscrollable?</p>
<p>We can’t prevent scrolling by using <code>event.preventDefault()</code> in <code>onscroll</code> listener, because it triggers <em>after</em> the scroll has already happened.</p>
<p>But we can prevent scrolling by <code>event.preventDefault()</code> on an event that causes the scroll, for instance <code>keydown</code> event for <kbd class="shortcut">pageUp</kbd> and <kbd class="shortcut">pageDown</kbd>.</p>
<p>If we add an event handler to these events and <code>event.preventDefault()</code> in it, then the scroll won’t start.</p>
<p>There are many ways to initiate a scroll, so it’s more reliable to use CSS, <code>overflow</code> property.</p>
<p>Here are few tasks that you can solve or look through to see the applications on <code>onscroll</code>.</p>
</div></article><div class="tasks formatted"><h2 class="tasks__title" id="tasks"><a class="tasks__title-anchor main__anchor main__anchor main__anchor_noicon" href="#tasks">Tasks</a></h2><div class="task tasks__task"><div class="task__header"><div class="task__title-wrap"><h3 class="task__title"><a class="main__anchor" href="#endless-page" name="endless-page">Endless page</a></h3><a class="task__open-link" href="/task/endless-page" target="_blank"></a></div><div class="task__header-note"><span class="task__importance" title="How important is the task, from 1 to 5">importance: 5</span></div><div class="task__content"><p>Create an endless page. When a visitor scrolls it to the end, it auto-appends current date-time to the text (so that a visitor can scroll more).</p>
<p>Like this:</p>`
```
it is work correctly
[the result of scrolling](https://i.stack.imgur.com/3LIqr.png) |
4,634,376 | Is there any way to use regex match on a stream in python?
like
```
reg = re.compile(r'\w+')
reg.match(StringIO.StringIO('aa aaa aa'))
```
And I don't want to do this by getting the value of the whole string. I want to know if there's any way to match regex on a srtream(on-the-fly). | 2011/01/08 | [
"https://Stackoverflow.com/questions/4634376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492162/"
] | This seems to be an old problem. As I have posted to a [a similar question](https://stackoverflow.com/questions/13004359/regular-expression-on-stream-instead-of-string), you may want to subclass the Matcher class of my solution [streamsearch-py](https://github.com/gitagon/streamsearch-py) and perform regex matching in the buffer. Check out the kmp\_example.py for a template. If it turns out classic Knuth-Morris-Pratt matching is all you need, then your problem would be solved right now with this little open source library :-) | The answers here are now outdated. Modern Python `re` package now supports [bytes-like](https://docs.python.org/3/glossary.html#term-bytes-like-object) objects, which have an api you can implement yourself and get streaming behaviour. |
99,930 | I typically do 5 or 6 minute long exposure with digital.
With film, technical specs usually go up to 2 minutes. Is the formula available for computing longer exposure? | 2018/07/12 | [
"https://photo.stackexchange.com/questions/99930",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/8312/"
] | The information you require is available on the Ilford website:
<https://www.ilfordphoto.com/wp/wp-content/uploads/2017/06/Reciprocity-Failure-Compensation.pdf>
It differs depending on the film in use, and as always, reciprocity and "correct" exposure are a little inexact, but there are factors listed there to help calculate exposure durations. | In short, you can expose film as long as you want - multiple hours, if you like - but colour may shift (on colour film) and you may not see a doubling of time equal one stop of additional exposure (*reciprocity failure*). As mentioned in the other posts, Ilford will have a table and some guidelines as to how its films suffer reciprocity failure, and you can do your own further experiments to see what happens.
For really long-exposure photographs such as star trails, with film, it's done in a single exposure rather than stacking multiple exposures as it's done with digital (which is necessary there due to sensor noise artifacts).
You'll need to tinker, but you can absolutely do it. Bracket your exposures, to be sure. |
28,780,422 | The aim is to have skeleton spec `fun.spec.skel` file which contains placeholders for `Version`, `Release` and that kind of things.
For the sake of simplicity I try to make a build target which updates those variables such that I transform the `fun.spec.skel` to `fun.spec` which I can then commit in my github repo. This is done such that `rpmbuild -ta fun.tar` does work nicely and no manual modifications of fun.spec.skel are required (people tend to forget to bump the version in the spec file, but not in the buildsystem). | 2015/02/28 | [
"https://Stackoverflow.com/questions/28780422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188533/"
] | Assuming the implied question is "How would I do this?", the common answer is to put placeholders in the file like `@@VERSION@@` and then `sed` the file, or get more complicated and have autotools do it. | I found two ways:
a) use something like
```
Version: %(./waf version)
```
where `version` is a *custom* `waf` target
```
def version_fun(ctx):
print(VERSION)
class version(Context):
"""Printout the version and only the version"""
cmd = 'version'
fun = 'version_fun'
```
this checks the version at rpm build time
---
b) create a target that modifies the specfile itself
```
from waflib.Context import Context
import re
def bumprpmver_fun(ctx):
spec = ctx.path.find_node('oregano.spec')
data = None
with open(spec.abspath()) as f:
data = f.read()
if data:
data = (re.sub(r'^(\s*Version\s*:\s*)[\w.]+\s*', r'\1 {0}\n'.format(VERSION), data, flags=re.MULTILINE))
with open(spec.abspath(),'w') as f:
f.write(data)
else:
logs.warn("Didn't find that spec file: '{0}'".format(spec.abspath()))
class bumprpmver(Context):
"""Bump version"""
cmd = 'bumprpmver'
fun = 'bumprpmver_fun'
```
The latter is used in my pet project [oregano @ github](https://github.com/drahnr/oregano) |
53,375,545 | j is destroyed when the function calls return
k is destroyed at the end of the enclosing brackets
If i pass in 9 for j, k is created and will be assigned 81
Returning k will set func1 which is a reference to an integer = k
Returning will immediately terminate the function
My question is, are k and j terminated at the return statement?
If they are func1 should reference nothing...
But i have tried to run this code and it works...
```
int& func1(int j){
int k = j*j;
return(k);
}
``` | 2018/11/19 | [
"https://Stackoverflow.com/questions/53375545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10466720/"
] | >
> and it works...
>
>
>
No, it *appears* to work. The moment you try to access the reference returned by `func1` you enter the Undefined Behavior realm. At that point all bets are off, it could've printed out 42, printed out nothing, crash, eat your CMOS battery etc. | >
> If they are func1 should reference nothing...
>
>
>
You are correct. Try using the reference some more time and you will see:
```
#include <iostream>
int& func1(int j) {
int k = j * j;
return(k);
}
int main() {
int& addr = func1(9);
for (int i = 0; i < 10; ++i) {
std::cout << addr << '\n';
}
}
```
Output:
```
81
2758456
2758456
2758456
2758456
2758456
2758456
2758456
2758456
2758456
``` |
34,633,064 | I want to have articles next to each other, as much as the browser width allows it. Each article has a fixed width. This attempt does not work each span takes 100% width. I guess because the elements inside the spans are making the trouble, but how to fix this?
```css
span {
width: 200px;
}
```
```html
<span>
<h2>Article 1</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 2</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 3</h2>
<p>Content for article 3. Bla bla bla bla bla and some more bla...</p>
</span>
``` | 2016/01/06 | [
"https://Stackoverflow.com/questions/34633064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2420037/"
] | Best thing is to wrap `inline` elements inside `block` elements
best option is to use a `div` element which is `block` which takes a full `width` by default once you add a width it will work perfectly
```css
div {
border: 1px solid red;
/*width:200px*/
}
```
```html
<div>
<h2>Article 1</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</div>
```
by default span is a `inline` element you can see in the first example which doesnt take any `width` you will need to set it to `display:inline-block`
here is the default demo
```css
span {
border: 1px solid red;
}
```
```html
<span>
<h2>Article 1</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 2</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 3</h2>
<p>Content for article 3. Bla bla bla bla bla and some more bla...</p>
</span>
```
```css
span {
width: 200px;
display:inline-block;
border:1px solid red;
}
```
```html
<span>
<h2>Article 1</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 2</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 3</h2>
<p>Content for article 3. Bla bla bla bla bla and some more bla...</p>
</span>
```
If you doeswant the spacing between `inline` element you can use `float` but dont forget to clear the `float`
```css
span {
width: 200px;
float: left;
border: 1px solid red;
}
```
```html
<span>
<h2>Article 1</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 2</h2>
<p>Content for article 1. Bla bla bla bla bla and some more bla...</p>
</span>
<span>
<h2>Article 3</h2>
<p>Content for article 3. Bla bla bla bla bla and some more bla...</p>
</span>
``` | Add `display: block;` to your span's class, or better use div.
Also check this article on w3c schools: [HTML Block and Inline Elements](http://www.w3schools.com/html/html_blocks.asp) |
6,621,591 | I am converting my HTC file to jquery plugin.
In my HTC file i am using below Microsoft.Fade.
```
progid:DXImageTransform.Microsoft.Fade(duration=0.15,overlap=1.0)
```
It is IE only thing. So i want optional thing for other browsers.
Is there any optional thing for this. | 2011/07/08 | [
"https://Stackoverflow.com/questions/6621591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834818/"
] | Use the fadeOut or fadeIn function:
<http://api.jquery.com/category/effects/fading/> | On jQuery, There are several option to fade.
To certain opacity level, on certain time.
```
$("div").fadeTo(1000, 15);
```
or fade Out completely
```
$("#div").fadeOut(1000);
```
or fade in
```
$("#div").fadeIn(1000);
``` |
202,749 | I've got an USB pen drive and I'd like to turn it into a bootable MBR device. However, at some point in its history, that device had a GPT on it, and I can't seem to get rid of that. Even after I ran `mklabel dos` in `parted`, `grub-install` still complains about
```
Attempting to install GRUB to a disk with multiple partition labels. This is not supported yet..
```
I don't want to preserve any data. I only want to clear all traces of the previous GTP, preferably using some mechanism which works faster than a `dd if=/dev/zero of=…` to zero out the whole drive. I'd prefer a termina-based (command line or curses) approach, but some common and free graphical tool would be fine as well. | 2015/05/11 | [
"https://unix.stackexchange.com/questions/202749",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/20807/"
] | If you don't want to fiddle with `dd`, `gdisk` can do:
```
$ sudo gdisk /dev/sdb
GPT fdisk (gdisk) version 0.8.8
Partition table scan:
MBR: protective
BSD: not present
APM: not present
GPT: present
Found valid GPT with protective MBR; using GPT.
Command (? for help): ?
b back up GPT data to a file
<snip>
w write table to disk and exit
x extra functionality (experts only)
? print this menu
Command (? for help): x
Expert command (? for help): ?
a set attributes
<snip>
w write table to disk and exit
z zap (destroy) GPT data structures and exit
? print this menu
Expert command (? for help): z
About to wipe out GPT on /dev/sdb. Proceed? (Y/N): Y
GPT data structures destroyed! You may now partition the disk using fdisk or
other utilities.
Blank out MBR? (Y/N): Y
```
Verify:
```
$ sudo gdisk /dev/sdb
GPT fdisk (gdisk) version 0.8.8
Partition table scan:
MBR: not present
BSD: not present
APM: not present
GPT: not present
Creating new GPT entries.
Command (? for help):
``` | You could do it with [`wipefs`](http://manpages.ubuntu.com/manpages/bionic/en/man8/wipefs.8.html):
>
> **wipefs** can erase filesystem, raid or partition-table signatures (magic strings) from the
> specified device to make the signatures invisible for libblkid. wipefs does not erase the
> filesystem itself nor any other data from the device.
>
>
> |
67,116,880 | I am not able to run project created under WSL2. I am getting this error. Does anyone have idea what could cause it?
```
Abnormal build process termination:
C:\WINDOWS\system32\wsl.exe --distribution Ubuntu-20.04 --exec /bin/sh -c "cd /home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server && /usr/lib/jvm/java-11-openjdk-amd64/bin/java -Xmx700m -Djava.awt.headless=true -Djdt.compiler.useSingleThread=true -Dpreload.project.path=/home/jakub/test -Dpreload.config.path=/mnt/c/Users/Z004506P/AppData/Roaming/JetBrains/IntelliJIdea2021.1/options -Dcompile.parallel=false -Drebuild.on.dependency.change=true -Dio.netty.initialSeedUniquifier=-636684381209623859 -Djps.in.wsl=true -Dfile.encoding=windows-1252 -Duser.language=en -Duser.country=US -Didea.paths.selector=IntelliJIdea2021.1 '-Didea.home.path=/mnt/c/Program Files/JetBrains/IntelliJ IDEA 2021.1' -Didea.config.path=/mnt/c/Users/Z004506P/AppData/Roaming/JetBrains/IntelliJIdea2021.1 -Didea.plugins.path=/mnt/c/Users/Z004506P/AppData/Roaming/JetBrains/IntelliJIdea2021.1/plugins -Djps.log.dir=/mnt/c/Users/Z004506P/AppData/Local/JetBrains/IntelliJIdea2021.1/log/build-log '-Djps.fallback.jdk.home=/mnt/c/Program Files/JetBrains/IntelliJ IDEA 2021.1/jbr' -Djps.fallback.jdk.version=11.0.10 -Dio.netty.noUnsafe=true '-Djava.io.tmpdir=//wsl$/Ubuntu-20.04/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/test_77f155f7/_temp_' -Djps.backward.ref.index.builder=true -Dtmh.instrument.annotations=true -Dkotlin.incremental.compilation=true -Dkotlin.incremental.compilation.js=true -Dkotlin.daemon.enabled '-Dkotlin.daemon.client.alive.path=\"C:\Users\Z004506P\AppData\Local\Temp\kotlin-idea-13948257364742160812-is-running\"' -classpath /home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jps-launcher.jar org.jetbrains.jps.cmdline.Launcher '/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/netty-buffer.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/nanoxml-2.2.3.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/maven-resolver-transport-file-1.3.3.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jna-platform.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/oro-2.0.8.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/slf4j.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/log4j.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/lz4-java-1.7.1.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jna.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/maven-resolver-provider.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/annotations.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/resources_en.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/commons-lang3-3.10.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/util.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/maven-resolver-connector-basic-1.3.3.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jps-builders-6.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/asm-all-9.1.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/forms_rt.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/guava.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jps-builders.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/zip-signer.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jdom.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/intellij-deps-fastutil-8.5.2-6.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/plexus-utils-3.3.0.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/javac2.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/qdox-2.0.0.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/commons-logging-1.2.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/trove4j.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/forms-1.1-preview.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jps-javac-extension-1.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/aether-dependency-resolver.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/http-client.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/maven-resolver-transport-http-1.3.3.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/idea_rt.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/netty-codec-http.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jps-model.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/gson-2.8.6.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-stdlib-jdk8.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/platform-api.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jasper-v2-rt.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/ant-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/java-guiForms-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/eclipse-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/eclipse-common.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/java-langInjection-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/groovy-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/groovy-constants-rt.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/maven-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/aspectj-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/gradle-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/devkit-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/javaFX-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/javaFX-common.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/javaee-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-jps-plugin.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-stdlib.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-stdlib-jdk7.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-stdlib-jdk8.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-reflect.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-plugin.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-jps-common.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/kotlin-common.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/javaee-jpa-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/javaee-appServers-websphere-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/javaee-appServers-weblogic-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/groovy-grails-jps.jar:/home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/groovy-grails-compilerPatch.jar' org.jetbrains.jps.cmdline.BuildMain 192.168.203.193 57615 867865da-6270-418c-bb35-8dcdf1591467 /home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server"
Build process started. Classpath: /home/jakub/.cache/JetBrains/IntelliJIdea2021.1/compile-server/jps-IU-211.6693.111/jps-launcher.jar
Error connecting to 192.168.203.193:57615; reason: connection timed out: /192.168.203.193:57615
io.netty.channel.ConnectTimeoutException: connection timed out: /192.168.203.193:57615
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe$1.run(AbstractNioChannel.java:261)
at io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98)
at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:170)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at java.base/java.lang.Thread.run(Thread.java:834)
Exiting.
``` | 2021/04/15 | [
"https://Stackoverflow.com/questions/67116880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12804925/"
] | In my case, setting correct Shell path of WSL 2.0 distro in Intelij's terminal settings path helped. Instead of `wsl.exe` set whole path for your distro ( I took path from [Windows Terminal](https://learn.microsoft.com/en-us/windows/terminal/install)).
In my case, when I'm using Ubuntu 20.04, changing from `wsl.exe` to `C:\WINDOWS\system32\wsl.exe -d Ubuntu-20.04` did the trick. | Had the same issue.
All the mentioned PowerShell commands, including the ones on the JetBrains site, didn't really help.
But what eventually did the trick was that Windows Defender's "Inbound Rules" panel. Had to just find all the Restrictive rules (i.e. the ones with "Action: Block") for both "idea64.exe" and "IntelliJ IDEA" and disable them.
Works like a charm. |
19,737,692 | I have a NSArray of NSDictionaries, in this array there are several values which I do not want to show in the UITableView, I would like to know how to avoid returning these cells in the **tableView:cellForRowAtIndexPath:**
I have tried to `return nil;` but this has caused me errors.
This is what my code looks like
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomInstallCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomInstallCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.selectionStyle = UITableViewCellSelectionStyleGray;
currentInstallDictionary = [sortedItemsArray objectAtIndex:indexPath.row];
NSNumber *tempDP = [currentInstallDictionary objectForKey:@"dp"];
NSInteger myInteger = [tempDP integerValue];
if (myInteger == 0) {
return cell;
}
return nil; // gives error
}
```
any help would be appreciated. | 2013/11/02 | [
"https://Stackoverflow.com/questions/19737692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748343/"
] | This method must return a cell. It cannot return nil. The best thing to do is filter your list before you load your table and use the filtered array when dequeueing cells. | The UITableView is only asking for a cell because you told it to ask. Your implementation of the [UITableViewDataSource](https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITableViewDataSource) protocol implements the two methods:
* [numberOfSectionsInTableView:](https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDataSource/numberOfSectionsInTableView%3a)
* [tableView:numberOfRowsInSection:](https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDataSource/tableView%3anumberOfRowsInSection%3a)
In those methods you determine how many cells should appear on screen. As Brian Shamblen answered, if you don't want that data to appear in the table view, some how ignore (filter, delete, whatever) that data when you calculate the number of sections and rows. If you do so, no "extra" cells will be requested. |
3,968,197 | Hi I'm a grad student and I was re reading the lecture notes my professor from a previous semester posted for algebraic number theory.
The lecture notes state: "If $O\_K$ is a number field and $I$ is an ideal of $O\_K$, then $N(I)$ is defined as $N(I) = |O\_K : I|$."
I took this definition to mean, if $N(I) = n$ then there are $n$ elements $a\_1, a\_2, \cdots a\_n \in O\_K$ such that every element of $a \in O\_k$ is of the form $i + a\_j$ where $i \in I$, and $1 \leq j \leq n$.
Later on the lecture notes state:
"Let $\gamma \in O\_K$, and $\{\beta\_1, \cdots \beta\_n \}$ be an integral basis of $O\_K$. Let $$\gamma\beta\_j = \sum\_{k = 1}^n a\_{j,k}\beta\_k, \, \, \, \, \, j = 1, 2, \cdots, n,$$
then \begin{equation\*} \begin{bmatrix}
\gamma \beta\_1 \\
\vdots \\
\gamma \beta\_n
\end{bmatrix} = A\begin{bmatrix}
\beta\_1 \\
\vdots \\
\beta\_n
\end{bmatrix}, \, \, \, \, \, A = [a\_{j,k}] \in \mathbb{Z}^{n \times n} \end{equation\*}
Let $I=\langle \gamma \rangle$.
Now $N(I) = |O\_K :I| = |det(A)|$."
So I'm having trouble seeing why $|O\_K :I| = |det(A)|$? | 2020/12/31 | [
"https://math.stackexchange.com/questions/3968197",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/723878/"
] | As pointed out in the comments, $f$ is not continuous at $4$, since $\lim\_{x\rightarrow 4^{-}}f(x)=-8\neq f(4)$. Recall that $x\in D(f)$ is an isolated point of the domain if there exists $\delta> 0$ such that $[(x-\delta,x+\delta)\setminus \{x\}]\cap D(f)=\emptyset$. Check that this is not the case.
Now, differentiability $\Rightarrow$ continuity still holds for left-differentiability and left-continuity. As the function is not left-continuous, it cannot be left-differentiable at $x=4$. | The (one-sided) derivative at $4$ would be
$$ \lim\_{x\to 4} \frac{f(x) - f(4)}{x-4} = \lim\_{x\to 4} \frac{-2x - 8}{x-4} = \lim\_{x\to 4}\left(-2- \frac{16}{x-4} \right)$$
which doesn't exist. So $f$ is not differentiable at $4$, nor is it continuous at $4$: $$\lim\_{x\to 4} f(x) = -8 \neq f(4).$$
In order to define a meaningful notion of "the limit of $f(x)$ as $x$ approaches $a$" you need $a$ to be a limit/cluster point of the domain of $f$. So in particular if $a$ is an interior point then you can define the two-sided limit that you're used to. If $a$ isn't an interior point, but still a cluster point, then you can still talk about the limit as $x \to a$ but just be careful that some of the theorems you have seen might no longer apply if $a$ is not an interior point.
In this case, however, it is still true that if $f$ is differentiable at $a$ (with $a$ a cluster point) then $f$ is continuous at $a$. |
30,046,608 | I´m using a `Button` and `CheckBox` in my code. I want when the button is clicked to make the checkboxes visible, but when I click on this button, then this error is coming in logcat: `NullExceptionPointer` .
Here is the code:
```
public class FriendListActivity extends Activity {
SimpleCursorAdapter adapter;
ListView lvContacts;
Button b1;
CheckBox chk;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_friend_listview);
getcontacts();
b1 = (Button)findViewById(R.id.btn_invite);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((Button) v).isClickable()) {
int visible = 0;
chk.setVisibility(visible);
} else {
int invisible = 0;
chk.setVisibility(invisible);
}
}
});
}
@SuppressWarnings("deprecation")
protected void getcontacts() {
lvContacts = (ListView) findViewById(R.id.lv_friend_list);
ContentResolver cr = getContentResolver();
// Read Contacts
Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME }, null, null,
null);
// Attached with cursor with Adapter
adapter = new SimpleCursorAdapter(this, R.layout.activity_phonecontact,
c, new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { R.id.tv_name });
lvContacts.setAdapter(adapter);
}
}
```
Here Is Xml:
```
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1"
android:gravity="center_vertical">
<ImageView
android:id="@+id/img_frnd_list"
android:layout_width="0dp"
android:layout_weight="0.2"
android:layout_height="wrap_content"
android:background="@null"
android:contentDescription="@string/imageView_contact_image"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:src="@drawable/contactimage" />
<TextView
android:id="@+id/tv_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:paddingLeft="10dp"
android:text="@string/Contact_Name"
android:textSize="@dimen/contact_text_size" />
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2" >
<Button
android:id="@+id/btn_invite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/invite"
android:background="@color/orng"
android:textColor="@color/white">
</Button>
<CheckBox
android:id="@+id/chk_frnd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>
</FrameLayout>
</LinearLayout>
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30046608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4748373/"
] | `chk` variable is `null` So use **findViewById** to initialize it.
```
chk= (CheckBox)findViewById(R.id.chk_id);
``` | You did not initialize check box in your code. Please insert following code in onCreate method.
```
chk=(CheckBox)findViewwByid(R.id.chk_frnd);
``` |
43,593 | I walked into work yesterday and 2 colleagues were leaving an office that I share with a male colleague. When I entered the office it had been transformed to a Fairy princess themed room ( I share the office with a male) The theme was only in his work space and definitely for his benefit.
What should I do about it?
I am more concerned about the message it sends about the colleague and the fact that it was in a shared space and interfered with my access to the phone, computer and other equipment I need for the work I had to complete that day. In fact it was still there today. | 2015/04/02 | [
"https://workplace.stackexchange.com/questions/43593",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/33771/"
] | >
> What should I do about it?
>
>
>
Laugh, be part of the April 1 fun, then plan your "revenge" for next year.
Some offices have a culture of fun, and this sort of prank is perfectly appropriate. If your office is like that, the best thing is to go along with what appears like good, clean fun.
I've worked in companies like this before, and enjoyed it a lot. I miss those days. | The answer to the subject question is "if you have to ask, ***NO***". Interfering with ANYONE else's productivity is more rude than funny, and abusing innocent bystanders is right out -- unless you are in a position to authorize the list time, in a company culture which will accept it, **and** you have something that's genuinely amusing.
There was a radio story this week about one workplace that did a very thorough reset to 1950 or so -- typewriters, dial telephones, period-appropriate decor...expensive, and it did ruin the whole team's productivity until the office was put back to normal, but major style points, it was actually making a point relevant to the business, and it was authorized by management.
If you can't come up with something stylish and harmless, I'd strongly recommend against doing anything.
(I still wish we'd gotten around to dressing the mail-delivery robot as a manager...) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.