INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to extract a file name from a full path
In a C program, I have a file path in a string (specifically, this is the `exe` name stored in `argv[0]`). I would like to extract the file name and discard the directory path using MS Visual Studio 2005. Any built in function for that? | For reference, here's the code I implemented, supposedly Win/Unix compatible:
char *pfile;
pfile = argv[0] + strlen(argv[0]);
for (; pfile > argv[0]; pfile--)
{
if ((*pfile == '\\') || (*pfile == '/'))
{
pfile++;
break;
}
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "c, filenames"
} |
Wrapping Ruby With An Anonymous Module
There are several Ruby C API functions for running some Ruby code. Most just run the code in an isolated binding like `require` does. But some of them first _wrap the code in an anonymous module_ before running it. For example, `rb_load` takes an argument for whether you want this wrapping, `rb_eval_string_wrap` is just `rb_eval_string_protect` but with wrapping.
In C, the wrapping looks like this:
/* load in anonymous module as toplevel */
th->top_self = rb_obj_clone(rb_vm_top_self());
th->top_wrapper = rb_module_new();
rb_extend_object(th->top_self, th->top_wrapper);
What is the point of doing this? I've tested these functions alongside their unwrapped equivalents and the result is always the same. Is there some use-case I'm not seeing? | I should've done some more testing. It looks like this is a bug.
The point of wrapping code in an anonymous module is to not pollute the toplevel namespace with constants/methods defined in the code. `rb_load` does this wrapping properly, `rb_eval_string_wrap` does not. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c, ruby, ruby c extension"
} |
Differentiating $u(b, t) = u(b + ch, t + h)$
I'm a beginner in PDE, studying the introduction part of Strauss' Partial Differential Equations book.
I'm stuck in a trivial part that says:
> $u(b, t) = u(b + ch, t + h)$
>
> Differentiating this with respect to $h$ and putting $h = 0$, we get $0 = cu_x (b, t) + u_t (b, t)$
But I don't understand I how I can differentiate the expression $u(b, t) = u(b + ch, t + h)$ with respect to h. Can someone please help me? | You can use the chain rule:
$\frac{du}{dh} = \frac{\partial u}{\partial x}\frac{dx}{dh} + \frac{\partial u}{\partial y}\frac{dy}{dh}$
Where $x = b + ch$ and $y = t + h$,
This will give $\frac{du}{dh} = cu_x(b + ch, t + h ) + u_y(b + ch, t + h)$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "derivatives"
} |
Convert RGB to Grayscale in ImageMagick command-line
How do I convert a RGB image (3 channels) to a grayscale one, using the (r+g+b)/3 method? I look through an examples page: < but the desired method:
convert test.png -fx '(r+g+b)/3' gray_fx_average.png
gave me a wrong result - the resulted image has still 3 channels.
You can check this by running a command: `identify -format "%[colorspace] <== %f\n" *.png`. | `convert <img_in> -set colorspace Gray -separate -average <img_out>` gives the best result for any image for me. | stackexchange-stackoverflow | {
"answer_score": 129,
"question_score": 74,
"tags": "imagemagick, grayscale"
} |
Is it possible to make the scrollbars wider in 15.10?
I just installed Ubuntu 15.10 and I'm fairly pleased with it. Among other things, I'm pleased that the non-scrollbar scrollbars are gone, but the new ones are still too thin for me; I would rather lose a few px of real estate from my apps and win a scrollbar that I can actually click on without sniper precision.
Is it possible to make the scrollbars a bit wider without wrecking everything? | If you mean the thin GTK3 scrollbar, it is from the theme properties. This is for Ambiance.
1. Open `/usr/share/themes/Ambiance/gtk-3.0/gtk-widgets.css` for editing
gksu gedit
2. Go around line 1143 and change:
-GtkRange-slider-width: 10;
to
-GtkRange-slider-width: 20;
BTW, you can always take a adventure with try & fail :)
grep -rn scroll /usr/share/themes/Ambiance/ | stackexchange-askubuntu | {
"answer_score": 4,
"question_score": 6,
"tags": "scrollbar"
} |
Magnolia app which runs in frame
I'd like to create a magnolia app which will show content from extra page in the frame. I think it's possible, but cannot find any example how to do it. | Yes, it is indeed possible. What you are looking for is creation of custom app using `EmbeddedPageSubApp`. More details at documentation
If you want simple example, try to import and start this app. It should start simple JS game within your subapp.
Remember that any page you try to load in iframe will need to use same protocol as the main Magnolia app does or browser will most likely block it. In the example I gave, it would work only over `http`, but not over `https`, if you want to show something while people are connecting to your Magnolia over https, you would need to set `url` to be https too.
HTH,
Jan | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "magnolia"
} |
wxPython Frame with wx.CAPTION style, an upper left Icon and a closebox?
Needed is a fixed size frame with a title bar having only an icon, the title, and a close box. No minimize nor maximize box. Can it be done? | See < for the various styles available (sorry it's the wxwidgets ref...I couldn't find the wxPython version for some reason). You'd want to pass something like this to the frame's style parameter:
style = wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.CLIP_CHILDREN
I'm not sure if you need the last one or not. Since you're not including RESIZE_BORDER, they won't be able to resize it. Another way to stop resizing is to use the SetSizeHints() method.
EDIT: You probably need wx.CAPTION if you're on Windows | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, wxpython"
} |
Partial (or complete) flag varieties as GIT quotients of affine spaces
I am looking for presentations of partial or complete flag varieties as GIT quotients of affine ~~varieties~~ spaces. That is, for a choice of of dimensions $0=d_1<d_2<\dots<d_k = n$, I would like to find examples of an affine ~~variety~~ space $V/\mathbb{C}$, a reductive group G acting on V, and a linearization $L$ such that the GIT quotient $V//G$ is equal to the flag variety $Fl(d_1,d_2,\dots,d_k)$.
Of course $\mathbb{P}^{n-1}$ is an easy example for $Fl(1,n)$, where $V = \mathbb{C}^{n}$ and $G = \mathbb{C}^{\times}$. And the Grassmannian $Fl(k,n) = Gr(k, {n})$ can be constructed as a GIT quotient of the vector space $M_{k,{n}}$ of $k\times n$ matrices $Gr(k, {n}) = M_{k,{n}}//GL(k)$, where $GL(k)$ acts as matrix multiplication on the left.
Are there constructions that work for more general choices of $d_i$? Does anyone know of any other examples or have recommendations of where I might look for them? | If you're willing to quotient by a nonreductive group, then $M_n//B$ will get you the $GL(n)$ flag manifold. (People are usually afraid to do so, worrying that the ring of invariants won't be Noetherian, but this one is.)
That flag manifold is also available reductively. Let $V_0,V_1\ldots,V_n$ be a list of vector spaces with those dimensions, and let $Hom := \prod_{i=1}^n Hom(V_{i-1},V_i)$. If we quotient this by $GL(V_1)\times \cdots \times GL(V_{n-1})$, it forgets the actual maps and only remembers the images inside $V_n$, so the result is (or to be precise, can be chosen to be) the manifold of flags in $V_n$. I forget whom this is due to, but it's pretty old.
You can get some of this to work for symplectic and orthogonal groups, using the $O(V) \times Sp(W)$ action on $V\otimes W$; the reference I know is [[Lerman-Montgomery-Sjamaar]]( "\[Lerman-Montgomery-Sjamaar\]"). | stackexchange-mathoverflow_net_7z | {
"answer_score": 15,
"question_score": 11,
"tags": "ag.algebraic geometry, algebraic groups, geometric invariant theory, flag varieties"
} |
How to find out the valid values to use for authorized grant types in Spring Secrity
I want to allow a client to use a specific grant type, but cannot find the valid values to use in the client table in the documentation.
Any ideas? | Very good question - I struggled to find the values for hours.
Here is how to gather the different values. Every implementation of `AbstractTokenGranter` carries static field grant type `GRANT_TYPE`:
* `refresh_token` \- RefreshTokenGranter
* `authorization_code` \- AuthorizationCodeTokenGranter
* `implicit` \- ImplicitTokenGranter
* `password` \- ResourceOwnerPasswordTokenGranter
* `client_credentials` \- ClientCredentialsTokenGranter
The authorized grant types of a client can be found in the client instance via `ClientDetails.getAuthorizedGrantTypes`
And last but not least spring security oauth follows the specification here - so the grant types mentioned above match those mentioned in the spec. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 7,
"tags": "spring security, spring security oauth2"
} |
How to get an average pipe flow speed
If `myfile` is increasing over time, I can get the number of line per second using
tail -f | pv -lr > /dev/null
It gives instantaneous speed, not average.
How can I get the average speed (i.e the integral of the speed function `v(t)` over the monitoring time). | With `pv` 1.2.0 (December 2010) and above, it's with the `-a` option:
Here with both current and average, line-based:
$ find / 2> /dev/null | pv -ral > /dev/null
[6.28k/s] [70.1k/s]
With 1.3.8 (October 2012) and newer, you can also use `-F`/`--format` with `%a`:
$ find / 2> /dev/null | pv -lF 'current: %r, average: %a' > /dev/null
current: [4.66k/s], average: [ 218k/s]
Note that `tail -f` starts by dumping the last 10 lines of the file. Use `tail -n 0 -f file | pv -la` to avoid that bias in your average speed calculation. | stackexchange-unix | {
"answer_score": 16,
"question_score": 16,
"tags": "pipe, monitoring, tail, fifo, pv"
} |
Alternative to getKeys() of phpredis
My phpErrorLog tells me that `getKeys()` is deprecated.
[01-Oct-2020 16:44:02 Europe/Berlin] PHP Deprecated: Function Redis::getKeys() is deprecated in <pathToFile> on line xxx
I wonder what the alternative to getKeys is. Unfortunately I couldn't find anything there on google. | You should be able to use `keys` to resolve the issue. The documentation notes that `getKeys` is an alias for `keys` and will be removed in future versions of phpredis.
Reference: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, logging, redis, deprecated"
} |
ERROR: Supplied String module notation 'androidx.cardview.widget.CardView' is invalid
Here is my build gradle files
implementation 'com.google.firebase:firebase-analytics:17.2.0'
implementation 'com.google.firebase:firebase-database:19.1.0'
implementation 'com.github.jd-alexander:android-flat-button:v1.1'
implementation 'com.rengwuxian.materialedittext:library:2.1.4'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.firebaseui:firebase-ui-database:3.3.0'
implementation 'androidx.cardview.widget.CardView' | Change
implementation 'androidx.cardview.widget.CardView'
to
implementation 'androidx.cardview:cardview:1.0.0'
The `androidx.cardview.widget.CardView` is the name of the class to be used in the code and in the layout. `androidx.cardview:cardview:1.0.0` is the name of the library which contains the `CardView` component. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, gradle, android cardview, androidx"
} |
How do I assign an IBAction to a second ViewController?
I have this project with two ViewControllers. It´s very simple. In the second window I only want a button to perform an action (link to iTunes store). I´m adding the code to my .h and .m files, but it´s not possible to link the actions to my button in the second window. But I can into the first one… I swear that I surfed and searched but I can´t find an answer to something like this. Should be easy, shouldn´t it? Thanx everybody!! | If you create an `IBAction` in one ViewController, it will not be visible from the other. This is just the nature of ViewControllers. If you want to, you can make the second class inherit the methods and variables form the other. You can do this by replacing
@interface SecondViewController: UIViewController {
with
@interface SecondViewController: FirstViewController {
in SecondViewController.h
(and if you get an error, add `#import "FirstViewController.h"` at the very top of the class) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "xcode"
} |
Rename files with unreadable filenames in bulk
I've downloaded a few RAR files with a bunch of PDF files. Unfortunately, all the names of these files are in Russian. I can extract the RAR files perfectly, but then I end up with a lot of files which show question marks in Explorer instead of the original characters.
With Explorer (or other Windows tools) I cannot open or access these files. However, Total Commander or other shells allow me to access, open, or rename these files. The problem is that I would need to do this for each and every directory and file, which is very cumbersome.
Is there a tool that renames files and directories in bulk? I don't care what the result names are, as long as I can access the files to sort through them manually.
Other workarounds are, of course, more than welcome!
Thanks! | Instead of installing other Static Software Applications, you can use just the one that you have already mentioned: GHISLER_Christian's " _Total Commander_ " File-Management Software Utility.
Just select the Files that you want to rename:
 ∨ ( q → r)$ logically equivalent to the statement $(p∧q) → r$
I came across this problem, it asks to use logical equivalences (see image), show that $(p → r) ∨ (q → r)$ logically equivalent to the statement $(p ∧ q) → r$ (aka definition of biconditional)
After apply $p→q ≡ ¬p∨q$, I can't go any further can anyone show me any steps further?
Thank you
Image logical equivalences | $(p → r) ∨ ( q → r)=(¬p ∨ r) ∨ (¬q ∨ r)=¬p ∨ r ∨ ¬q ∨ r=(¬p ∨ ¬q) ∨ r=¬(p∧q)∨r=(p∧q) → r$ | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "discrete mathematics, logic, propositional calculus, boolean algebra"
} |
What kind of power supply do you run through a metal detector coil?
I am planning on building a decent metal detector out of a variety of existing components but although I understand the basic concept of most metal detectors involves the induction of current in a metal object by a coil on the detector, I am slightly confused on what type of power supply a metal detector needs. From what I have read, it sounds like it runs AC through the coils, but I haven't actually seen any sources say anywhere that it is explicitly alternating current, but describes something that sounds like alternating current but is called something else (Pulsed or something like that). Is it alternating current or is it something else that I'm not familiar with? I am not asking what AC or DC is, just what is used in a metal detector. Or does a metal detector typically use a combination of DC and AC, converting DC to AC and back again? | This is the simplest metel detector circuit I could find.
Note how it runs on a **battery** (B1 on the right). Batteries only deliver **DC** so the circuit is powered by DC.
But in order to detect metals, a coil is used (L1).
That coil together with C1 and IC1a forms an **oscillator**.
That oscillator applies AC to the coil.
Any metal objects near the coil will influence its value and that will change the frequency at which the oscillator runs. That oscillation signal can then be fed to a radio or some detection circuit which is not shown here.
So: the circuit is powered by DC
But it generates AC from that DC to make the metal detection work.
`.
All together, your code works like this:
SAMPLE_TEXT="hello.world.testing"
echo "$SAMPLE_TEXT"
OUT_VALUE=$(echo "$SAMPLE_TEXT" | cut -d'.' -f1)
# OUT_VALUE=$(cut -d'.' -f1 <<< "$SAMPLE_TEXT") <--- alternatively
echo "output is $OUT_VALUE"
Also, note I am adding quotes all around. It is a good practice that will help you in general.
* * *
Other approaches:
$ sed -r 's/([^\.]*).*/\1/g' <<< "$SAMPLE_TEXT"
hello
$ awk -F. '{print $1}' <<< "$SAMPLE_TEXT"
hello
$ echo "${SAMPLE_TEXT%%.*}"
hello | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "bash, unix, cut"
} |
New road bike: alloy dual pivot brakes work poorly
I recently bought a new road bike (a very entry model - Giordano Acciao) which has alloy dual pivot brakes. The brakes seem to work poorly, even though they are quite tight. If I squeeze the brake and push the bike forward it might still move - when riding this feeling is even worse, the brake just won't fixate the wheel to non-motion. How is that possible on a new bike? Is there something I can do and that I am missing and I should do? Shouldn't the brake stop the wheel completely?
Best regards | Entry level bikes are designed to be sold at a price point. What this means is, the parts are spec'd out to at least be functional at the lowest possible cost. In your case the brakes were the parts that are the least functional. They still work, but not great. The good news is that the brake pads are one of the cheapest upgrades you can make. With a minimum of tools and skill you can change the pads. Avoid buying pads at Walmart, Target etc as these are likely similar in quality to what you have. I would suggest you visit a local shop see what they carry and ask for the best brakes you can get in your price range. | stackexchange-bicycles | {
"answer_score": 6,
"question_score": 1,
"tags": "brakes"
} |
How do you upgrade a SQL Express Database to SQL Server Workgroup or Standard?
I have a website that was originally developed using a SQL Express database in the App_Data folder. Now I need to take upgrade it, without loosing any data, to SQL Server 2005 Workgroup or Standard.
Is there a guide on how to properly upgrade by Microsoft or another source? | When installing Workgroup or Standard it will upgrade the database server and the databases at the same time. Make sure you have a backup of your database (just in case). You can always backup the database and restore it to Workgroup or Standard as well.
Here's a guide: < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql server 2005, upgrade, sql server express"
} |
Can i call a vf page as popup from a custom link button from a standard sf page
I want to show a popup of list of cases without parentid and allow to select usign checkbox and the selected cases are added up in a related list. This popup would be availabe on clicking of link button
First question would be can i call a vf page as popup from a standard page? The rest i guess i can hande it in the VF page
Thanks Prady | Yes, you create a link button for the object in whose page layout the link will reside. As a source for the link button choose "Visual force page" and choose a page. Keep in mind that the vf page MUST use standardController for the same object (with or without extensions) or it will not show up in the list. Choose to show the page in a new window and later place the link button on the page layout. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "salesforce"
} |
Why erase cause an error on my mac? (c++)
My code works okay on my linux. Today when I was trying to compile it and test it on my mac, I got an segv error. And later I changed it to another method (not using `erase`), the error is gone. I guess that I must have done something wrong in using c++ `erase`. Any ideas?
## Before: (Why this one is not working now?)
vector<point> line::internalPoints() const
{
vector<point> pts = points();
pts.erase(pts.begin());
pts.erase(pts.end());
return pts;
}
## After:
vector<point> line::internalPoints() const
{
vector<point> pts;
vector<point> ptsTmp = points();
for (int i = 1; i < ptsTmp.size()-1; ++i)
{
pts.push_back(ptsTmp[i]);
}
return pts;
} | end() (and possibly begin() as well, if the vector is empty) don't point to an actual element. That means trying to erase it is undefined behaviour.
Possible duplicate of: erasing vector::end from vector | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "c++, macos"
} |
RAILS precision and scale of decimal is not working
I have set :precision => 8, :scale => 2 in decimal of migration but when i input 1923.423453 it is still 1923.4 . It should be 1923.42 ... right?
t.decimal :value , :precision => 8, :scale => 2 , :default => 0 | Apparently all sqlite options are dropped on migration.
Here's the lighthouse ticket targeting milestone 3.0.4 to fix this issue: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "ruby on rails"
} |
Prove that $\langle S \rangle = \bigcap_{S\subseteq H, H\le G}H$
Prove that $\langle S \rangle = \bigcap_{S\subseteq H, H\le G}H$ where $\langle S \rangle = \\{x_1, . . . , x_m \mid x_i \in S\cup S^-, m \in \mathbb{N} \\}$
I know how to prove that $\langle S \rangle$ is a subgroup of G by using the subgroup criterion but I'm not sure how to approach this question.
I'm guessing I will have to show $\langle S \rangle$ is composed of disjoint subsets of $H$ but I don't know how to begin.
Please can someone give me hint! | Let $K=\displaystyle\bigcap_{S\subseteq H, H\le G}H$.
Clearly $\langle S \rangle \subseteq H$ for all subgroups $H$ containing $S$. This implies that $\langle S \rangle \subseteq K$.
Since $\langle S \rangle$ is a subgroup that clearly contains $S$, one of the $H$'s in $K$ is $\langle S \rangle$, and so $K \subseteq \langle S \rangle$.
You also want to prove this characterization of $\langle S \rangle$:
> $\langle S \rangle$ is the smallest subgroup of $G$ that contains $S$, in the sense that if $H$ is a subgroup of $G$ that contains $S$, then $\langle S \rangle \subseteq H$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "group theory, normal subgroups"
} |
Can I use Redis strictly as a referenced assembly, compiled within my application?
I have a project that I'd like to use Redis with as an in-memory database that caches the database to disk. From all information I've gathered, it seems that Redis would be a great choice for my needs. The one issue is that it seems that before you can use Redis, you have to install it on your machine.
Can Redis be added to a .Net solution as a library and compiled as part of my single installation package, rather than as a separate application/service that must be installed on a users machine?
Basically, I'd like to use this like a localized database similar to SqlLite/Sql Server CE except with all of the features of Redis. Can this be done?
I suspect the answer is no but, if it isn't, how can I create a local database from within my project and open/close it from within my application? I can't find a straight answer on if this is possible or not and, if so, how to do it.
Thanks guys. | I'm going to assume you are talking about the Windows port of Redis. No you can not do this. In a Windows environment - Redis can run either as an app or a Windows Service. It is meant to be installed on a server and serve as a distributed cache / NoSQL database. If you do decide to use redis, I recommend using the StackExchange.Redis client.
If you are looking to have a local cache, then you can use the MemoryCache.aspx). Another option is to use SQL Server Express LocalDB. Neither of them have the same features of Redis. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": ".net, redis"
} |
Prove the inclusion-exclusion formula
We just touched upon the inclusion-exclusion formula and I am confused on how to prove this: $|A ∪ B ∪ C| =|A| + |B| + |C| − |A ∩ B| − |A ∩ C| − |B ∩ C| \+ |A ∩ B ∩ C|$
We are given this hint: To do the proof, let’s denote $X = A ∪ B$, then $|(A ∪ B) ∪ C| = |X ∪ C|$, and we can apply the usual subtraction rule (you will have to apply it twice).
That just made me even more confused. I was hoping someone can guide me through this, or explain | The "subtraction rule" is the inclusion-exclusion principle for two sets: $$|A\cup B| = |A| + |B| - |A\cap B|$$ Just apply the hint without thinking: $$\begin{align*} |A\cup B\cup C| & = |X\cup C| = |X| + |C| - |X\cap C| \\\ & = |A\cup B| + |C| - |(A\cup B) \cap C| \\\ & = |A| + |B| - |A\cap B| + |C| - |(A\cap C) \cup (B\cap C)| \\\ & = |A| + |B| + |C| - |A\cap B| - (|A\cap C| + |B\cap C| - |(A\cap C) \cap (B\cap C)|) \end{align*}$$ can you finish? (These were actually _three_ applications of said rule). | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "discrete mathematics, inclusion exclusion"
} |
Opening HTML link in new window
I've got a table that shows details about some products, which are stored in the database. These details are Item Name, Price and submit Date.
Item Name Price Submitted on
Laptop £30 12/04/10
guitar £5 12/05/10
If I click on Laptop I want to see all details such as Title, Price, Description, Picture, Contact name and email (all details are stored in the database) in a new windows.
I don't know if a PHP function will do it or maybe I need javascript?? I look on Google but I could find anything.
I hope you undestand my question | Here is how you open a link in a new window.
<a href="detailsPage.php?itemID=1234" target="_blank">Name of your Product</a> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, html, hyperlink, onclick"
} |
Holding on ImageView to change InputType of TextView - Android
I have EditText with InputType of password and one ImageView like a button. So I want when user hold his finger on that image, InputType of EditText to become normal text, and when user remove finger, InputType again to be password. So how can I do this? | ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setOnTouchListener(new View.OnTouchListener {
public onTouch(View v, MotionEvent event){
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
//set edittext to normal
}
else if (event.getAction() == MotionEvent.ACTION_UP
{
// set edittext to password
}
return true;
}
});
The above code should work, it might need a little tweaking - I can't test it at the moment. Should give you a good idea on how to handle it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, textview, imageview"
} |
'4 x DIMM' Confusion
I currently have an ASUS Maximus Formula with 4GB (2x2GB) DDR2 RAM and Q9400 running @3.6 GHz.
I am quite happy with CPU performance and I want to upgrade my graphics card and RAM as 4GB is not really enough for today's applications/ games. The problem is that on the specification of the motherboard it states '4 x DIMM, Max 8GB' and then it goes on to say 'Dual Channel memory architecture'. On the actual motherboard it is clear that there are 4 RAM slots, but I am just sceptical as to what it means by 'Dual Channel memory architecture' on the specification.
The question is, if I bought exactly the same model of RAM (two more 2GB sticks) would my motherboard actually support it? Also, my current RAM is overclocked @450 MHz, and if I started using quad channel configuration (4x2GB) instead of dual configuration (2x2GB) would that affect the overlooking at all? | Dual channel memory architecture deals with how the memory communicates with the memory controller. The dual-channel architecture expands the number of data wires available in the memory data bus from 64 to 128. This helps speed things up a bit. It doesn't have anything to do with how many sticks the board can hold.
The configuration you have is correct, and your board can support 4, 2GB sticks that are DDR2 1200*/1066/800/667 MHz.
Also, what graphics card are you looking to get? | stackexchange-superuser | {
"answer_score": 2,
"question_score": 1,
"tags": "memory"
} |
Xamarin Forms MapRenderer OnMapReady event equivalent for iOS?
I need an equivalent event for an iOS renderer:
public class MyMapRenderer : Xamarin.Forms.Maps.Android.MapRenderer
{
...
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
// need to do things here
}
...
}
Thanks | You can use MKMapViewDelegate_MapLoaded to handle your actions in iOS renderer:
public class CustomMapRenderer : MapRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
var nativeMap = Control as MKMapView;
nativeMap.MapLoaded += NativeMap_MapLoaded;
}
private void NativeMap_MapLoaded(object sender, EventArgs e)
{
Console.WriteLine("NativeMap_MapLoaded");
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "xamarin.forms, xamarin.ios, google maps sdk ios, custom renderer"
} |
extract digits between 2 patterns awk/egrep
I want to extract the variable number of digits between two patterns, eg:
correction:
blah blah.... AAM #6,blah blah
blah blah.... AAM #10 , blah blah
blah blah.... AAM #100 , blah blah
output: 6, 10 and 100
I need to extract numbers between `AMA #` and `,` | Assuming the two patterns the digits are supposed to be between are `AAM#` and `,`
`gawk 'match($0, /AAM #([[:digit:]]+)[[:space:]]*,/, a) {print a[1]}'` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "awk, grep"
} |
Удалить n символов в начале каждой строки в файле
Как удалить n символов в начале каждой строки в файле? | Как вариант:
lines = open(path, 'r').readlines()
with open(path, 'w') as fp:
for line in lines:
line = line[n:] # вот тут можно воткнуть любую обработку, например
fp.write(line) | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "python, python 3.x"
} |
Using Armadillo Sparse Matrices in MPI
I am trying to initialise Armadillo sparse matriix sp_mat within MPI as follows:
if(rank==0)
{ // some code for locations, values
sp_mat X(locations,values)
}
// this is where I want to use X
if(rank==0)
some_fun(X)
As you can see, Armadillo constructor is local to the `if block` and as such can not use it after `if block`. Putting the same question in another way:
extern sp_mat X
if(rank==0)
{ // some code for locations, values
sp_mat X(locations,values)
}
// this is where I want to use X
if(rank==0)
some_fun(X)
Using `extern sp_mat X` before `if block` also does not help (I got undefined reference error).
How can I initialise X and reuse it afterward? | Use (smart) pointers:
std::unique_ptr<sp_mat> X; // or std::shared_ptr<sp_mat> or sp_mat*
if (rank == 0) {
// some code for locations and values
X = std::unique_ptr<sp_mat>(new sp_mat(locations, values));
}
...
if (rank == 0)
some_fun(*X); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, mpi, armadillo"
} |
Flask to Numpy Image Conversion
I have been trying to send an image over javascript to a Flask server to draw bounding boxes on coordinates I received from my own API. How might I convert this to a numpy array?
I was thinking of using the cv2.imdecode feature, but I don't want to download that huge file on my server. Here is an example of the input string src i am sending to flask:
data:image/jpeg;base64,IMGDATA HERE
I believe that this string is base64 encoded, but I am not sure how to make this conversion in python. | I have done something similar to this. If you have your url, then you first have to decode the IMGDATA part of the src string, which is base64 encoded. So first you need to separate IMGDATA from the inputstring. This can be done using:
import base64
imgdata = imgsrcstring.split(',')[1]
decoded = base64.b64decode(imgdata)
Then you can use the PIL Libarary to convert the Bytes representation of the string to an image, which can then be converted to a numpy array:
from PIL import Image
from io import BytesIO
img = np.array(Image.open(BytesIO(decoded))) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, numpy, flask"
} |
get Max method for DateTime type
I am looking for an `Enumerable.Max` method that returns a `DateTime`, but it seems this method does not exist.
I tried using reflection to find it, but none of the results returned a `DateTime`:
Dim test = GetType(Enumerable).GetMethods(BindingFlags.Public Or BindingFlags.Static).
Where(Function(m) m.Name = "Max")
Is there such a method? | `Enumerable` has no `Max` method specified for `DateTime` type, but it has generic `Max(IEnumerable<TSource>)` method that can process objects of classes that implements `IComparable<T>` or `IComparable` interfaces, including `DateTime`.
So you can use this method:
class Program
{
delegate DateTime MaxDelegate(IEnumerable<DateTime> values);
static void Main(string[] args)
{
MaxDelegate d = Enumerable.Max<DateTime>;
var values = new DateTime[] { DateTime.MinValue, DateTime.Now, DateTime.MaxValue };
var result = d(values);
Console.WriteLine(result);
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -3,
"tags": "vb.net, datetime, reflection"
} |
How to cast an object from its base class into its subclass
I have a class `User` which is a subclass of class `PFUser`:
class User: PFUser {
var isManager = false
}
In one of my methods I receive a `PFUser` object and I want to cast it to a `User` object
func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
currentUser = user
}
Is this possible? | If it's an instance of `PFUser`, and not an instance of `User` stored in a variable of `PFUser` type, no it's not possible.
You can cast an instance of a class to one of its superclasses, but you cannot do the other way (unless the cast type is the actual instance type).
I suggest to implement an initializer in `User`, taking a `PFUser` instance as parameter - if that's possible.
However, although I never attempted to do so, I think inheriting from `PFUser` you'll just run into troubles, as my understanding is that this class is not designed to be inherited as it is for `PFObject`. I'd suggest looking into making `PFUser` a property of `User` \- that way you can just assign as needed. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 10,
"tags": "oop, object, swift"
} |
How to show timestamps in Chrome 103 console?
Google search's answer:

Actual settings:

I think things have changed since Google's answer to that question. | The checkbox has been moved to Settings.
Press `F1` from inside dev tools. Under the Console heading, you'll find `Show timestamps`.
!screenshot | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "google chrome"
} |
Showing that map $\phi(z)=z(z-1)$ is not covering projection
Map $\phi : \mathbb{C} - \\{0,1/2\\} \to \mathbb{C} - \\{-1/4\\}$ given by $\phi(z)=z(z-1)$ is not covering projection. Can someone give hint how to proceed. | **Hint**
For $z \in \mathbb C \setminus \\{0, -1/4\\}$, the inverse image of $z$ under $\phi$ includes two points. However, the inverse image of $0$ is equal to $\\{0,1\\}$ but $0$ has been excluded from the definition set of $\phi$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "algebraic topology"
} |
Working with SMS and ports in Android
1. Is it possible to find to which port was the SMS sent(as I understand getOriginatingAddress returns only number)?
2. How can I send SMS to a specific port from emulator?
The main problem is that port number and phone number which emulator has are the same. | Launch another instance of emulator. The port number is displayed in the window title.
To send SMS to custom port use this method. | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "android, sms"
} |
How to create a responsive subivew based on the minimise or drag the window for Mac OS X application?
I am trying to create an Mac OS X application and this application should be responsive based on the user minimise and drag of the window. I have tried using the auto lay out and was partially successful in doing that. This is what i have followed. I have added the constraints for auto layout as < But if i minimising the width of the window the subview is minimising the width shown in the following < Can any one guide me how to set the minimum size for the subview to get minimised. Thank you | I have done this by adding the width constraint and setting it greater than and lesser than. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "macos, autolayout"
} |
Get uptime in seconds or miliseconds on Unix like systems
I need a method which can give me the number of miliseconds or seconds, elapsed since the system was started. I could parse `/proc/uptime` , but i can't afford to lose performance over this I/0 and parsing.
I'm using Linux and C/C++. Maybe i can put some Qt/Boost, but is better to be something native. | Why cannot you afford reading `/proc/uptime`? It is _not a real file_ so reading it should be quick (there is no real i/o involved, since the `/proc/` filesystem contains pseudo-files). Did you benchmark its reading?
You might also call clock_gettime with `CLOCK_MONOTONIC`
NB. This is specific to Linux. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 1,
"tags": "c++, c, linux, unix"
} |
title bar in xfce panel
I have a netbook with Ubuntu Oneiric (11.10) installed with XFCE. Due to the limited vertical space available, I would like to have the title bar for a maximized window appear in the xfce panel. I use to be able to do this on Ubuntu 10.04 (GNOME2) with `maximus` and `window-picker-applet`. I'm not using GNOME Shell or Unity (including 2d) because they run too slow on my netbook.
I've looked at How do I enable the globalmenu / appmenu on Xfce or LXDE?. It doesn't help me though because it's only for getting the menu to appear in the panel (using `xfce4-appmenu-plugin`). Is there something similar but mimicking the title bar? It appears as though `xfce4-xfapplet-plugin` has been removed in Ubuntu 11.10.
Any help or suggestions would be greatly appreciated. | Not exactly what you are looking for but inorder to save space you could use xfce4-panel as wingpanel. `xfapplet` is somewhat dead project AFAIK. What you can do is make xfce4-panel as a wingpanel with minimal length and make it auto-increase. In order to make panel movable do this:
xfconf-query -c xfce4-panel -p /panels/panel-0/disable-struts -t bool -n -s true
And on panel preference, make panel length to minimal and enable auto-increase option:
!enter image description here
You can do this for as many panel you have.
I usually have a single panel on the right-hand corner with notification area, indicator, session-button and application-menu and windows button control on the left-hand corner.
Source | stackexchange-askubuntu | {
"answer_score": 3,
"question_score": 4,
"tags": "11.10, xfce, titlebar"
} |
univariate analysis using qplot function from ggplot2 package
X <- round(quantile(Retaildata$monthly_salary.x,c(.90,.92,.94,.96,.98,1)),0)
Y <- c('P90','P92','P94','P96','P98','P100')
library(ggplot2)
qplot(x=Y,y=X,label=X,geom = c('text','point'), hjust = -.25)
Why `P100` is shown on the leftmost side?
How do I take it to the last, i.e. to the right?
!qplot_graph | Try this:
set.seed(1)
X <- round(quantile(abs(rnorm(1000))*12500,c(.90,.92,.94,.96,.98,1)),0)
Y <- c('P90','P92','P94','P96','P98','P100')
# 'mixedsort' orders character strings containing embedded numbers so that
# the numbers are numerically sorted rather than sorted by character value
library(gtools)
Y <- factor(Y, levels=mixedsort(Y))
library(ggplot2)
qplot(x=Y,y=X,label=X,geom = c('text','point'), hjust = -.25)
.ready(function(){
$('#toggle').click(function(){
var hidden = $('.hidden');
if (hidden.hasClass('visible')){
hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
} else {
hidden.animate({"left":"75px"}, "slow").addClass('visible');
}
});
}); | You can have a function like this one :
$(document).ready(function(){
$('.toggle').click(function(e){
e.preventDefault();
$('.hidden').animate({"left":"100%"}, "slow");
$(this).next('.hidden').animate({"left":"0"}, "slow");
});
});
I use `.toggle` instead of `#toggle` since ID must be unique in the document.
Check this **Demo Fiddle** | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "javascript, jquery, html, css"
} |
Datetime format convert to monthyear in excel
I have a questions about excel.
Excel sheet1 has data like below
OrderDate
2016-04-30T12:30:05
2016-05-03T05:14:09
2016-05-05T03:21:12
2016-05-06T07:03:24
2016-05-06T16:10:44
2016-05-07T01:12:33
2016-05-07T05:29:30
2016-05-08T06:17:05
Based on above data I want to show month and year and filter format and in the next column outputlike below
OrderDate | FInalOrderdate
2016-04-30T12:30:05 | April2016
2016-05-03T05:14:09 | May 2016
2016-05-05T03:21:12 | May 2016
2016-05-06T07:03:24 | May 2016
2016-05-06T16:10:44 | May 2016
2016-05-07T01:12:33 |May 2016
2016-05-07T05:29:30 |May 2016
2016-05-08T06:17:05 |May 2016
Here I need to to give filter in finalorderdate column if I want to show may month data then it should show only may month data.
How to achive this task in excel file? | Try
1. Go to **Menu->Data->Data Tools->Text to Columns**
2. Click **Next**. Type **"T"** on **Others**
3. Click **Finish**.
4. Format the column using **Format Cells** on **Custom** using ' **mmm yyyy**. Just right click.
5. Go to **Menu->Data->Sort & Filter->Filter** | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "excel, csv"
} |
Does the mempool size equal roughly the unconfirmed transactions?
My `bitcoind` (`v0.13.0`) mempool size is currently 12k transactions as can be seen from:
`tail -f ~/.bitcoin/debug.log`
I find this number very surprising as I naively expected it to keep in line with the number of 'Unmatched transaction' as reported say by blockchain.info which currently shows 3k transactions.
What am I missing? | Every node owner can set their own policy for the mempool. The mempool is limited two-fold:
* With `-maxmempool=<n>` you can set an explicit limit of MB that it will not exceed. The default is 300MB.
* Transactions that don't surpass the `minRelayTxFee` are not added to your mempool.
As statoshi.info has the mempool at 145MiB and ~11k transactions, it appears likely that different settings on the `minRelayTxFee` seem to cause your and blockchain.info's divergent mempool size here. | stackexchange-bitcoin | {
"answer_score": 4,
"question_score": 3,
"tags": "bitcoind, blockchain.info, mempool"
} |
What Certification(s) to look for in Hard Drive destruction?
Many vendors exist to pick up old (enterprise) Hardware for recycling and offer services including sanitization and destruction (shredding).
The concern is that media could potentially still contain sensitive information (through data remanence or simply human error forgetting to sanitize the media before disposal).
Is there any certifications (e.g. ISO) that a vendor should possess to be entrusted with old storage media (especially hard drives and SSDs)? | You could look for a company that uses DoD 5220-22.M standards for data destruction : <
I use a company that says they meet that standard. | stackexchange-security | {
"answer_score": 1,
"question_score": 6,
"tags": "certification, disposal"
} |
How do you find an ethical, honest independent insurance broker in Canada?
I live in Toronto. I hope to buy a 20-year Term Life Insurance for my (gullible) mother of age 58 to replace her Permanent Life Insurance (which I believe that the evil insurance agent exploited her to buy), but how do I find an ethical, honest independent insurance broker?
I could approach, say, Manulife Financial or Desjardins directly, but was thinking to see some quotes from an independent insurance broker too. | How do you find an ethical, honest practitioner of any business?
One: Make a small transaction with them and see how they treat you. If they cheat you on something small, don't give them a chance with something big.
Two: Ask family and friends for recommendations.
Three: Get information from public sources, like web sites where people post reviews of businesses, consumer advocacy organizations, groups like the Better Business Bureau, etc. Personally I consider all these of questionable value as you're asking one stranger to advise you on the reliability of another stranger, but better than nothing. | stackexchange-money | {
"answer_score": 2,
"question_score": 0,
"tags": "canada, life insurance"
} |
How to subset an object based on the property values in an array in typescript/angular?
I am learning typescript. I wonder what is the best way to subset object based on the property values from another array.
For example, I have following object and array:
const Aobject =
{
"cities": [
{
"id": "city_id1",
"name": "NY"
},
{
"id": "city_id2",
"name": "BOS"
},
{
"id": "city_id3",
"name": "SF"
},
{
"id": "city_id4",
"name": "LA"
}
]
}
const Aarray = ["city_id2", "city_id3"]
Expected output (array):
[
{
"id": "city_id2",
"name": "BOS"
},
{
"id": "city_id3",
"name": "SF"
}
] | You can try this
result = [];
subSetArray() {
this.Aobject.cities.forEach(x => {
this.Aarray.forEach(z => {
if (x.id.includes(z)) {
this.result.push(x);
}
});
});
console.log(this.result);
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "angular, typescript, filter"
} |
Perform Action for x times in Objective-C (iOS)
I'm new to iOS-Developement and my question is if it is possible to run some action a fix set number of times.
I want to perform an action for exactly 20 times. | I dont really know what you want but it seems you are looking for
int i;
for(i=0;i<20;i++)
{
//do your action.
}
also if you want it to be performed in background and not on main queue you can use GCD or NSThread and put `for` inside GCD or NSThread. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "ios, objective c"
} |
'System.InvalidOperationException' occurred in Microsoft.Phone.ni.dll
I am making an app which records sounds.
When clicking the mike button it is supposed to move to a new page.
When I add a save button in the application bar of the new page and then run it, it throws this exception
'System.InvalidOperationException' occurred in Microsoft.Phone.ni.dll
If I don't add the save button it works fine | Google for Update 4 for visual studio 2012.Its size is about 2gb download and install the update and you're done
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "windows phone 8, invalidoperationexception, windows phone 8 sdk"
} |
what is AP time zone abbreviation
whenever I google times in other countries I get these (that's by my local date: Solar Hijri calendar)
For example "Time in USA" : Thursday, Shahrivar 22, 1397 **AP** (EDT)
"Time in India" : Friday, Shahrivar 23, 1397 **AP** (GMT+5:30)
and "Time in Iran" : Friday, Shahrivar 23, 1397 **AP** (GMT+4:30)
And the question is **AP** that I didn't find in time zone abbreviations listed on Wikipedia.
PS: according to here: < , shouldn't be **IRDT**? so why google shows me **AP**? | That's not a timezone descriptor. In this case "AP" means "Anno Persico" or "Anno Persarum", meaning "Persian year". See < < or < | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "time, calendar"
} |
Custom Seekbar View implementation
I am trying to implement a similar effect to this `SeekBar`:
HUMSlider for iOS
for an Android Application.
I know that I have to implement it using `Canvas`, but I am quite new to this.
I tried implementing a `View` for the graduation unit and then adding multiple instances from it in a `ViewGroup`. But I just can't get it right.
Any Help? | First approach would be to extend `SeekBar` class, overriding the drawing methods like `onDraw(Canvas canvas)`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android canvas, android custom view"
} |
Load md file remotely using fetch api and parse it on client/browser
I want to load an .md file using fetch API and I need to parse it using `marked`
I'm having trouble grabbing the file via fetch api, i'm getting nothing back with `response.blob()` and `response.arrayBuffer()`.
fetch('
.then(response => response.blob())
.then(result => console.log(result));
I want to then take the result and pass it to a react component to render it. I will be parsing it using marked (from npm).
Any help would be appreciated. | I assume you're getting the `No 'Access-Control-Allow-Origin' header is present on the requested resource.` error response. That is, you're making a cross-domain request and thus violating the Same-origin policy.
Basically, you need to enable Cross-Origin Resource Sharing (CORS) on your S3 Bucket. Exactly how to do it, you can read here.
Also, just as a quick test, you can prefix the URL you're trying to fetch with ` like this:
fetch('
.then(response => response.blob())
.then(result => console.log(result));
which should make the request succeed. This is just for testing, though. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "javascript, client, blob, markdown, fetch"
} |
jQuery returned through AJAX not showing any effect
I have two webpages. Page 1 is a form on whose submit, page 2 is loaded through jQuery (calls a php page and returns the output on the same page1 without load). I have session variables maintained to ensure no breaching is done. However, in a particular scenario, I want page 1 window to close and hence I pass the following code as o/p from page 2.
echo '<div style="background-color:#ffa; padding:5px"><font color=red>Multiple sessions of the same page are open. Please <a href="" onclick="window.close();">close</a> use the latest window for submission</font></div>';
echo '<script type="text/javascript">
function parent_close(){
parent.window.close();
}
setTimeout(parent_close,5000);
</script>';
however, it seems neither clicking the 'close' link closes the main window nor does the window automatically close in 5secs (which is what i actually desire)
Where am i going wrong? | The link should have a value in its href, not just an empty value, e.g:
href="#"
and not:
href=""
Also, the first argument to `setTimeout` should be enclosed in quotes, and you probably want the function to be invoked, not returned e.g:
setTimeout("parent_close()",5000); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, ajax"
} |
If a set is proper and non-empty then its boundary is non-empty
Please let me know if this proof looks good.
For the sake of contradiction, suppose that $E\ne \emptyset$ and $E\ne \mathbb{R}^n$, and that the boundary of $E$, $\partial E$, is empty. Since the closure of $E$, $\overline{E}$, is the union of the interior of $E$ and the boundary of $E$, i.e. $\overline{E}=E^\circ \cup \partial E$, $\overline{E}=E^\circ$. But $E^\circ$, the interior of $E$, is open by definition. Thus $\overline{E}$ is open. But this is impossible! Therefore, $\partial E$ is not empty. | As others have noted, you have only shown that $\partial E=\phi$ implies that $\bar E$ is open and closed. This means $\partial E=\phi \implies (\bar E=\phi \lor \bar E=R^n)$. Now if $\bar E=R^n$ and $E$ has empty boundary then $\phi= \partial E=\bar E\cap \overline { (R^n\backslash E}=R^n\cap \overline {R^n\backslash E}\supset R^n\backslash E,$ so $E=R^n$. Note that we can apply this result to any connected space, not just $R^n$. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "real analysis, general topology, analysis, proof verification"
} |
How to repalce column values using pandas , based on the words present in the cell
My df looks like ,
S2PName S2PName-Category
0 IDLY Food
98 IDLY 4 PARCEL Food
99 IDLY 2 PARCEL Food
100 IDLY 5 PARCEL Food
101 IDLY 3 PARCEL Food
114 IDLY 6 PARCEL Food
I would like to have my df as
S2PName S2PName-Category
0 IDLY Food
98 IDLY PARCEL Food
So i need to check for the words 'IDLY' **and** 'PARCEL' , irrespective of the number in between, and then rename as IDLY PARCEL , how can i achieve this using pandas ? | ### `replace`
df.replace('IDLY\s+\d+\s+PARCEL', r'IDLY PARCEL', regex=True)
S2PName S2PName-Category
0 IDLY Food
98 IDLY PARCEL Food
99 IDLY PARCEL Food
100 IDLY PARCEL Food
101 IDLY PARCEL Food
114 IDLY PARCEL Food
More generic
df.replace('(\w+)\s+\d+\s+(\w+)', r'\1 \2', regex=True)
S2PName S2PName-Category
0 IDLY Food
98 IDLY PARCEL Food
99 IDLY PARCEL Food
100 IDLY PARCEL Food
101 IDLY PARCEL Food
114 IDLY PARCEL Food | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas"
} |
In a BIBD, why is it the case that $r>\lambda$?
Given a BIBD $(v,b,r,k,\lambda)$, I'm trying understand the proof of Fisher's inequality, but I'm stuck at the step where the assertion $r>\lambda$ is made. But why? The only pieces of information I have is $vr=bk$ and $\lambda(v-1)=r(k-1)$. | Every point is in precisely $r$ blocks.
Every pair of distinct points is in precisely $\lambda$ blocks.
Since $\\{p,q\\}\subset S\implies p\in S$, it is unavoidable that $r\ge\lambda$.
Now suppose that $r=\lambda$. Then for any point $p$, occurring in $r$ blocks, every pair of points $\\{p,q\\}$ must appear in all $r$ blocks; so every other point uses the same $r$ blocks, and $b=r$ and $v=k$, making all blocks complete and the design degenerate. | stackexchange-math | {
"answer_score": 4,
"question_score": 1,
"tags": "combinatorics, combinatorial designs"
} |
parse error on input `in' Haskell
I would like to type Haskell source file this code from ghci
ghci> let x = 3; y = "!" in show x ++ y
and transform my code to this
x = 3
y = "!" in show x ++ y
but got an error message like
> parse error on input `in'
How can I avoid the error and fix my code? | The semicolon does not separate two independent assignments as you might expect from other languages; it serves as a replacement for a newline _and_ the following indentation.
let x = 3; y = "!" in show x ++ y
is the layout-free version of
let x = 3
y = "!"
in show x ++ y
where the indentation of `y = "!"` is significant. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "haskell"
} |
usb debugging not connected to pc
I have android device its `samsung galaxy GT-S5300` and version is _2.3.6_. I want to connect my device with computer for running the apps directly to device via eclipse.
I have installed the `samsung kies` on my system and i did the following setting on my phone but I **could not get connected with pc for debugging mode(Developing)**. **But the sd card is mounted to pc.**
1)Setting -> Application -> UnKnown sources ->enabled the option.
2)Setting -> Application -> Development-> USB debugging ->enabled the option.
But still not connected my device with pc for debugging mode.
How to get connected the device with pc for USB debugging mode? | Hey murali_ma,
Do this...
1. Open command prompt and type adb kill-server
2. then again type adb start-server
3. then adb install path of apk
i am sure you will get the success. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "android, usb"
} |
Elementary tweak with Pantheon in Lubuntu
I have installed elementary-desktop on my Lubuntu in VMWare. Now I wanted to install the numix circle icon pack and hence was trying to install Elementary tweak tools. I have added the versable/elementary-tweak-isis repositoryusing :
sudo apt-add-repository ppa:versable/elementary-tweak-isis
and then
sudo apt-get update
But whatevet I do it always says
unable to locate package elementary-tweaks
Please help | Try using this repository: ppa:mpstark/elementary-tweaks-daily
Type in the terminal:` sudo add-apt-repository ppa:mpstark/elementary-tweaks-daily sudo apt-get update sudo apt-get install elementary-tweaks `
I had the same issue and this worked for me on the first try. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 1,
"tags": "14.04, lubuntu, ubuntu tweak, elementary"
} |
MergAndroid Livecode - How to save on Android's Camera Roll?
I'm using this code to save an image in the Android's Camera roll, unfortunately to date without any luck.
put mergStoragePath("pictures") into a
put a & "/myphoto.jpg" into pathFile
put the long id of image "myPhoto" into longIDofImage
export longIDofImage to file pathFile as JPEG
All suggestions will be appreciate. | I think the problem here is that the media scanner isn't scanning the file. I have a command coming to do that `mergStorageScanFile`. However, to do what you want to do there's actually a built in LiveCode command `mobileExportImageToAlbum`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "android, livecode"
} |
How can I remove the first 30 second of 40 min video and add watermark also doing bulk using ffmpeg?
I was able to add watermark to multiple video using
for %%a in ("*.ts") do ffmpeg -i "%%a" -i logoCopy.png -filter_complex "overlay=main_w-overlay_w-40:40" "Logo\%%~na.mp4"
And now I'm trying to cut the first 30 second of the video and add watermark at the same time, I was able to cut the first 3o seconds using:
ffmpeg -i input.ts -ss 00:00:20 -map 0 -codec copy output.ts
Any one can help me combine the seouncd command to the first one? | Use
for %%a in ("*.ts") do ffmpeg -ss 30 -i "%%a" -i logoCopy.png -filter_complex "overlay=main_w-overlay_w-40:40" "Logo\%%~na.mp4" | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "ffmpeg, video conversion, video editing, mp4"
} |
Finding the direction in which the camera faces
I am able to get the current position the camera is in, i.e, its x,y,z co-ordinates in aframe.
In the below code, I am making my camera move forward.
function move_camera_forward(){
x=$("#cam").attr("position").x;
y=$("#cam").attr("position").y;
z=$("#cam").attr("position").z;
updated_pos=x+" "+y+" "+String(Number(z)-0.2);
$("#cam").attr("position",updated_pos);
}
But this moves the camera along z axis irrespective the direction the camera is facing. I want to move the camera based on the direction faced by the camera. If the camera is facing lets say 45 degrees, I want to update the three co-ordinates. For this I need to find out in which direction the camera is facing. How can I do this? Does it have something to do with fov? | I finally figured out how to do this. camera has a rotation attribute which gives me the angle of rotation. With this data and a bit of trigonometry, we can find the updated position. The below code moves the camera in the direction in which the user sees.
new_x = 0;
new_z = 0;
function move_camera_forward() {
x = $("#cam").attr("position").x;
y = $("#cam").attr("position").y;
z = $("#cam").attr("position").z;
radian = -($("#cam").attr("rotation").y) * (Math.PI / 180);
new_z = (new_z + (0.1 * Math.cos(radian)));
new_x = new_x + (0.1 * Math.sin(radian));
new_pos = new_x + " " + y + " " + (-new_z);
console.log(new_pos)
$("#cam").attr("position", new_pos)
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "aframe"
} |
Translating ObjC code to iOS Swift
if (self.advertisingSwitch.on) {
// All we advertise is our service's UUID
[self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] }];
}
else {
[self.peripheralManager stopAdvertising];
}
I have it translated in Swift as:
if self.advertisingSwitch.on {
self.peripheralManager.startAdvertising([CBUUID(string: TRANSFERSERVICEUUID)])
} else {
self.peripheralManager.stopAdvertising()
}
It is giving me the error: "cannot invoke StartAdvertising with argument list of type ([CBUUID])" | try this
if self.advertisingSwitch.on {
self.peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey:[TRANSFER_SERVICE_UUID]])
} else {
self.peripheralManager.stopAdvertising()
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, objective c, swift"
} |
Calling an overridden base method conditionally in C#
I've never really been poised with this question: But would it be a terrible crime to call base.SomeMethod() conditionally in an overridden method?
Example as in:
protected override void SomeMethod()
{
if( condition > 0 )
base.SuperMethod();
}
I'm aware that this may be considered bad practice but I've actually never read such a claim so far. | I can't think of a reason why this would be bad off the top of my head.
It'd be a lot worse to override the base method and copy the base method's functionality to conditionally call instead of just calling the base method. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 6,
"tags": "c#, inheritance"
} |
Why would a loaded PHP extension fail on class instantiation?
I have some code which is resizing images, using either Imagick or GD, depending what's available on the server.
I'm testing for availability of each using the `extension_loaded()` function.
if (extension_loaded('imagick')) {
$image = new Imagick();
...
}
I have one user reporting that they are receiving:
> Fatal error: Class 'Imagick' not found
What circumstances would result in the Imagick extension being loaded but the class not available? How should I be testing to make my code more robust? | 1: always do the checks in a case-insensitive manner (make the string lowercase before comparing it)
2: don't check for the library, check for features. Maybe it has a library version that's buggy or has other function names
3: **in php.ini you may disable some functions explicitly by name** so I think you should resort to point #2 and check with function_exists instead of extension_*
Also, take a look at `/var/log/apache2/errors` or the equivalent on that client's server to check for any internal error generated by the ImageMagick extension (segmentation fault or other types of low-level errors should get reported in there...) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "php, imagemagick"
} |
My brother and I have different pings
My brother and I use the same router, comcast internet, and are both using ethernet.
However, our pings are different:
!enter image description here
My ping is 15, however my brother's is 8. | It is very unlikely that these are "real" pings - what you are most likely seeing is an in-game ping, which - for many games - takes into account the speed of the computer being used.
There are also other possibilities - like you are connecting to different servers (using round-robin DNS or similar).
You might want to do some proper "Windows" pings to various IP addresses to see if it is a network problem (unlikely) or something else. If you suspect you might be going to different IP's, you would probably need a packet sniffer to ascertain where the packets are going. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "networking"
} |
Standard structure for multi-module java maven project
Is there a standard or de facto structure for maven web application project which consist of multiple modules or child projects? Let's say I want to package my domain objects and integration utilities as a distinct jars to keep things modular and reusable. How should the folder structure look like and how I specify another build dependent of those jars that even doesn't exist yet? | The maven folks have a reference for that...
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, maven, jar, build, dependencies"
} |
How to write a test case for a simple React component using Jest and Enzyme
I have a simple React component which looks like something as shown below:
export default class New_Component {
static propTypes = {
name: PropTypes.string.isRequired,
mobile: PropTypes.number.isRequired,
address: PropTypes.string.isRequired
};
}
render() {
return(
<div>
<h1>{this.props.name}</h1>
<h6>{this.props.mobile}</h6>
<p>{this.props.address}</p>
</div>
)
}
So,if I want to write a test case for the above component using **Jest** and **Enzyme** , what are the possible test cases that can be written for this component? Can someone please guide me? I am not able to figure out what are the possible test cases as I do not have any functions in this component so that I can check for the result of the function in an **expect()** function. | I believe it is ok not to write any unit test for that simple component and focus your short time on this earth writing end to end tests for example.
If your manager is monitoring the % coverage of test in your app, you can simply test that your component renders the `name`, `mobile` and `address`:
const wrapper = shallow(<New_Component
name="testName"
mobile="000000"
address="addressMobile"
/>);
expect(wrapper.find('h1').text()).to.equal('testName');
expect(wrapper.find('h6').text()).to.equal('000000');
expect(wrapper.find('p').text()).to.equal('addressMobile'); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, reactjs, jestjs, enzyme"
} |
What is the port Apple Screen Sharing listening?
I am using Chicken of VNC and iSSH to access my home Mac mini with Screen Sharing enabled. I can not sure which port the feature using,anyone could point it out? | HERE is a great table from Apple of all their most used ports. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 1,
"tags": "remote desktop"
} |
CouchDB View Empty space in search
I am trying to search in couchDb using temporary view in futon.
The view code is like this:
function(doc)
{
if(doc.Time Zone.value == "America/Los_Angeles")
{
emit([doc.owner, doc.source], null);
}
}
But when I try to sun this view, it give the following error: Error: compilation_error
Expression does not eval to a function. ((new String("function(doc) { if(doc.Time Zone.value == \"America/Los_Angeles\") { emit([doc.owner, doc.source], null); } }")))
I think this is because of a space in doc.Time Zone. If a remove this space it compiles but didn't give any values. Compiler dont want this empty space.
Please help me. | This is because the way you access your document's _Time Zone_ field is invalid.
The proper way to access that field would be
doc['Time Zone'].value
It is a basic JavaScript issue you're facing. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "javascript, view, couchdb"
} |
TypeScript: how to annotate parameter type as "any value of object"?
How I should to annotate parameter type as "any value of object" ?
class ExampleClass {
private static readonly MODES = {
DEVELOPMENT: 0,
PRODUCTION: 1,
TEST: 2
}
// Any Value of ExampleClass.MODES
constructor(mode: MODE[?]) {
}
}
In this case, values `0`, `1`, `2` are meaningless if to use `enum`, but as far as I know, we cannot use `enum` as class field. So let's consider the `some value of object` case in this question. | Tomas was very close, but let's go ahead and give the full answer. To get the type of values of `typeof MODES`, just index it by the type of all of its keys.
type ValueOf<T> = T[keyof T];
// Prevent widening of the types of the constants to `number`.
function asLiterals<T extends number, U extends { [n: string]: T }>(arg: U) {
return arg;
}
class ExampleClass {
private static readonly MODES = asLiterals({
DEVELOPMENT: 0,
PRODUCTION: 1,
TEST: 2
});
// Any Value of ExampleClass.MODES
constructor(mode: ValueOf<typeof ExampleClass.MODES>) {
}
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "typescript, types"
} |
ORACLE: How to get all column with GROUP by only 1 column?
I'm using ORACLE Database, How to get all column with GROUP by only 1 column (EMP_ID)?
Example I have table `ESD_RESULTS`
FIRST_NAME | LAST_NAME | EMP_ID | WRIST_STATUS | LFOOT_STATUS | DATE
Dodo | A | 0101 | Pass | Pass | 2016-01-18 10:00
Wedi | Wil | 0105 | Pass | Pass | 2016-01-18 10:05
Dodo | A | 0101 | Pass | Fail | 2016-01-18 10:11
What I want the data display is (Get the last data by date desc if EMP_ID same):
FIRST_NAME | LAST_NAME | EMP_ID | WRIST_STATUS | LFOOT_STATUS | DATE
Dodo | A | 0101 | Pass | Fail | 2016-01-18 10:11
Wedi | Wil | 0105 | Pass | Pass | 2016-01-18 10:05
I tried to use DISTINCT and GROUP by the data still show all. | One option is to use `ROW_NUMBER()` to identify the latest record for each employee:
SELECT t.FIRST_NAME,
t.LAST_NAME,
t.EMP_ID,
t.WRIST_STATUS,
t.LFOOT_STATUS,
t.DATE
FROM
(
SELECT FIRST_NAME, LAST_NAME, EMP_ID, WRIST_STATUS, LFOOT_STATUS, DATE,
ROW_NUMBER() OVER (PARTITION BY EMP_ID ORDER BY DATE DESC) rn
FROM ESD_RESULTS
) t
WHERE t.rn = 1 | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "oracle"
} |
Subscribe to data store changes in Workers KV
Cloudflare Workers KV is an eventually consistent data store. You can write values assigned to keys, and you can read values by key from it. But is there any possibility to listen to some key's value?
In a regular relational DB you can subscribe to changes of an individual row, but are there any similar options for KV? | There is currently no built-in listen.
You could poll keys for changes, which would probably only make sense if you had a small number of keys. (You can list keys to iterate over them.)
But, since you're the owner of your KV namespace, the best option is probably to wrap your write operations so that you notify some other service/queue that a change has been made. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "cloudflare, serverless, datastore, serverless architecture, cloudflare workers"
} |
Vue.js : transform v-model data
I am iterating through `items` in a checkbox. When I click on an item, it pushes each of those objects into the `newItem` array. However, I'd like to transform the new data in `newItem` to just be an array like this: `["age: 55", "age: 25"]...` how can I transform the data going into `newItem` to be shaped like that?
items: [{name:"Billy, age: 55, permission: true}, {name:"Mike, age: 25, permission: false}],
newItem: [],
<v-checkbox v-for="item in items" v-model="newItem"></v-checkbox> | You could use a computed property called `selectedAges` based on the `newItem` property :
computed:{
selectedAges(){
return this.newItem.map(item=>{
return "age: "+item.age;
})
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, vue.js, vuejs2, vue component, vuetify.js"
} |
JavaScript: Have we always been able to index into a string like it's an array?
I've always thought that if you want to access the nth character in a string called `str`, then you have to do something like `str.charAt(n)`. Today I was making a little dummy test page and by mistake, I accessed it with `str[n]` and to my surprise, it returned me the nth character of the string. I threw up this little purpose built page to exhibit this unexpected (to me) behaviour:
<!doctype html>
<html>
<body>
<script>
var str = "ABCDEFGH";
if (str[4] === str.charAt(4)) alert("strings can be indexed directly as if they're arrays");
var str2 = new String("ABCDEFGH");
if (str2[4] === str2.charAt(4)) alert("even if they're declared as object type String");
</script>
</body>
</html>
It wasn't always like this, was it? | No, that was not always possible.
If you run your code in an old enough browser, IE 7 for example, it won't be able to access the string like that. On those older engines, you'd have to use `.charAt(index)` instead. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, arrays, string, indexing"
} |
Does calling createUpload in aws devicefarm actually upload the file?
I'm switching from using the aws cli to the sdk so I can make some nicer scripts but it seems i'd still have to curl after calling createUpload. Is there a nicer way of doing this? Or something that does the upload in one? | `createUpload` just creates a S3 bucket with a pre-signed key, you still have to do a `put` to the bucket to actually upload anything, I don't think there is a single command that combines the two.
This is how I do it in Python:
upload = device_farm.create_upload(projectArn=project['arn'], name='spec.yml', type='APPIUM_WEB_PYTHON_TEST_SPEC')
response = requests.put(upload['upload']['url'], data= open('testspec.yml', 'rb'), headers={"Content-Type": "application/x-www-form-urlencoded"}) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "aws device farm"
} |
How to interpret open ended gliss notation on guitar
How would the notation below be interpreted?
What is this called on the guitar?
I'm calling it "glissando to nowhere in particular" in my mind. It resembles something I've seen in a jazz violin book before but I'm really not sure what it is called or how to do it on guitar.
.
If you are looking for reference, searching for _guitar slides_ will help you. | stackexchange-music | {
"answer_score": 4,
"question_score": 2,
"tags": "guitar, notation, technique, tablature"
} |
Get ID back after array sort?
How can I get my giving ID back after sorting the array?
`var distance = [];`
I loop through a JSON file and add the ID and the response (response is the distace between the current user location and the store location) to the array distance: `distance[item.properties.Nid] = response;`.
After each added new distance to the array I sort the array again:
sort_stores = function(stores){
stores = stores.filter(function(item){
return item !== undefined;
});
stores.sort(function(a, b){
return a - b;
});
console.log(stores);
};
But how can I get my ID `distance[item.properties.Nid]` back? When I log `stores` to my console, only the response is logging.. | Organise your data differently, so that your data has both the ID and the distance in one object.
So, store as follows:
distance.push( { Nid: item.properties.Nid, distance: response });
And sort with this function:
sort_stores = function(stores){
// NB: first step (filter out undefined) is not needed anymore
stores.sort(function(a, b){
return a.distance - b.distance; // add distance property
});
console.log(stores);
};
To get the distances you can do things like this:
firstDistance = stores[0].distance;
or loop:
for (var store of stores) {
console.log('Store ', store.Nid, ' is at ', store.distance)
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, arrays, json, sorting"
} |
JVM Heap Allocation
In our project we use Tomcat 7 server and we need to increase our Heap size up to 6 gb. Some processes in our project uses this memory.After our processes finished we apply garbage collection in our code. We follow memory allocation using Java VisualVM. There is a problem. When our processes finished, used heap size decreases but Heap size that JVM provide (6gb) doesn't decrease so our local computers have some difficulties to handle new processes.So my question is, is there a way to decrease Heap size to used heap size level? How can we manage that. I hope i can ask my situation clearly. Thanks in advice. | Eclipse release heap back to system
Above link helps us to solve our problem.
We add `-XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:MinHeapFreeRatio=5 -XX:MaxHeapFreeRatio=25 -Xms256m -Xmx4096m` to Tomcat VM arguments. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, memory management"
} |
I have just one OS in my laptop, why Have I 3 partitions?
I am QUITE new in this topcis. My laptop has only one OS, ubuntu 20.04
When I come to gparted, I saw 3 partitions and one unallocated.
1- /dev/sda1 ext4 => I read this should by my OS, (ext4 is for linux right?)
2- /dev/sda2 fat32 => what is that? this should be for dual boot with windows?
3- /dev/sda3 extended => 224.45 gb size --- --- (what is that?)
If a open number 3-
unallocated unallocated 1MiB
/dev/sda5 ext4 => linux again right? (224.45 GiB
unallocated unallocated
I show you a pictured..
Spend a year or two learning more about Linux and Ubuntu and if by that time you need more space you can wipe out `sda5` and reclaim it for Ubuntu. Deleting it now will not make Ubuntu run any faster and could leave you with a bricked system.
Your question is kind of broad: _"Here's a picture of what I have, I don't know what it means what should I do?"_. So far others not familiar with your system are speculating on how your system might be setup.
Over the next year or two try to read up on:
* BIOS (Basic Input Output System)
* CSM / Legacy Boot
* UEFI
In the meantime just use Ubuntu day to day and enjoy it. | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "boot, partitioning, boot partition"
} |
JS string destructuring: rest parameter returning inconsistent data
Consider the following examples
An old project:
const [x, ...y] = "text";
console.log(x) // "t"
console.log(y) // "ext"
A new project based on CRA:
const [x, ...y] = "text";
console.log(x) // "t"
console.log(y) // ["e", "x", "t"]
I'm not sure why `y` is returning a string (`"ext"`) for the old project, where it's an array of characters (`["e", "x", "t"]`) for the new project. Is it something to do with different JS versions?
Note: Both result were extracted after running webpack dev server. | in babel website you can see that your code based on es2015-loose convert to this code so output of this code is same with your old project
"use strict";
var _text = "text",
x = _text[0],
y = _text.slice(1);
console.log(x); // "t"
console.log(y); // "ext" | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "javascript, ecmascript 6, destructor, ecma, rest parameters"
} |
How to get a reference to a newly created Android activity
In my Android app, my main activity creates ActivityB, but I need to get a reference to that Activity so that I can later raise an event on it. I want to do something like:
var intent = new Intent(this, typeof(ActivityB));
intent.PutExtra("Param1", "Some Value");
ActivityB activityB = StartActivityForResult(intent, RATING_REQUEST_CODE);
.
.
.
activityB.SomeEvent();
But of course, this doesn't work because StartActivityForResult returns void, not an Activity.
How can I get a reference to the activity that I just created with StartActivityForResult? | > I need to get a reference to that Activity so that I can later raise an event on it
That's not how you do it in Android. Components are loosely coupled; activities do not hold onto other activities. Android destroys and recreates activities in a number of scenarios (rotating the screen, other configuration changes, process termination and restart). References from one activity to another would become obsolete.
A common approach is to use an event bus, such as `LocalBroadcastManager` or greenrobot's EventBus. Have Activity B subscribe for events on the bus, and have Activity A post events to the bus. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "android, android activity"
} |
Using jetty to install and run servlet tests programmatically
The jetty servlet container is quick and light enough to run in unit tests (indeed I do to serve up files).
It is possible to install actual servlets into it, programmatically (say in a test) and have it run them? | Yes. We do this on a regular basis with a number of tools. The simpest is probably HTTP-unit. When we deploy in jetty, we usually deploy larger parts of the application and run Selenium. HttpUnit is the simplest, but at some point your application complexity may warrant a more complete deployment. See the documentation section on embedding jetty | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "java, servlets"
} |
How can I restrict remote access to Elmah?
With Elmah installed on our dev web server .. can we restrict who remotely accesses it? Even f we hardcode the username/passwords (hashed?) or is it only via IP? | There are two settings, one is in `<elmah>`:
<elmah>
<security allowRemoteAccess="1"/>
</elmah>
The other is, if you allow remote access, you can use the `<location>` to control who accesses it:
<location path="elmah.axd">
<system.web>
<authorization>
<allow roles="Administrator"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
You can put this in the main web.config just after you `</runtime>` tag | stackexchange-stackoverflow | {
"answer_score": 28,
"question_score": 15,
"tags": ".net, asp.net, elmah"
} |
I edited /etc/passwd and have strange problems
I manually edited `/etc/passwd` for non-root user - yeah, I know this is bad. Unfortunately I saw this (SSH failing authentication after manual edit of /etc/passwd and /etc/shadow) very late. I already recovered `/etc/passwd` to previous state, but something strange is happening on the server, for example:
useradd some_user
doesn't create home directory for this user, and doesn't ask about it password, authorization for old user is not working. I hope someone already encountered such a problem. P.S. I use Debian | See the manpage for adduser:
useradd is a low level utility for adding users. On Debian, administrators should usually use adduser(8) instead. | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 0,
"tags": "linux, ssh, debian, users, passwd"
} |
Facebook Open Graph- Dynamic Title
I'm developing a social app that requires some Open Graph actions. I want the meta data tag for the title to be from my database because the name of my action title depends on the user choice.
Is it possible to get the title meta from database, rather than being hard coded? For instance:
<meta property="og:title" content="<?php echo $someTitle ?>" /> | Of course it is _possible_ – but how to you want to know _what_ content to put out _when_?
When Facebook scrapes your URL, your site’s user is not involved. So that means you have to transfer some info via the query string or something; and that would make them _different_ URLs, so you’ll end up with different OG objects as well. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, mysql, facebook opengraph"
} |
Why do Thunderbird Lightning notifications come late?
It seems that the Thunderbird integration to Ubuntu is taking some time, and I'm okay with that, I have workarounds for most things like keeping Thunderbird open in the notification area, but there is one thing: the Lightning notifications about events (not Ubuntu's native notifications, but rather Lightning's pop-up window notifications), which I set usually to one hour before the event starts, never appear on time. They do appear, but much later on, and when I see them it's usually after the event is finished. I checked if it's a timezone problem in Thunderbird or Ubuntu, but in both places the timezone is set correctly. Does anyone have an idea? Thanks in advance! | The problem was solved by an update. It works fine now. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 1,
"tags": "thunderbird, lightning"
} |
Is there a danger in electrolyzing NaCl?
To make $\ce{NaOH}$ one could electrolyze a solution of $\ce{NaCl}$ in water ($\ce{H2O}$) It would go like this:
$$\ce{2H2O_{(l)} + 2Cl-_{(aq)} + 2Na+_{(aq)} -> H2_{(g)} + Cl2_{(g)} + Na+_{(aq)} + 2OH-_{(aq)}}$$
After calculating a bit, I found that even just a few minutes of electrolyzing this at $10\ \mathrm{A}$ could be deadly.
Can anybody confirm this? | If the cell is mixed, you would make bleach, sodium hypochlorite and some free chlorine (and probably chew up your anode). Since the solution is not very basic, hypochlorite would probably disproportionate to chlorite, and that possibly to chlorate.
One mole of electrons is one faraday, about 96 500 coulombs. One ampere is one coulomb per second. Five minutes passes $(5\ \mathrm{min})(60\ \mathrm{s/min})(10\ \mathrm{C/s}) = 3000\ \mathrm{C}$ or $0.031\ \mathrm{F}$ in a reaction that requires two moles input for each mole of chlorine. $0.01554\ \mathrm{mol}$ chlorine or $350\ \mathrm{ml}$ at STP, tops. It wouldn’t be good for you. | stackexchange-chemistry | {
"answer_score": 3,
"question_score": 2,
"tags": "home experiment, safety, electrolysis"
} |
jQuery .on efficiency
Is the first .on function more efficient than second one ?
$( "div.container" ).on( "click", "p", function(){
});
$( "body" ).on( "click", "p", function(){
});
Regards | From the jQuery documentation itself about **jQuery: .on()** :
> jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So, "#myForm", "a.external", and "button" are all fast selectors. **Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document.** For example, instead of $( "body" ).on( "click", "#commentForm .addNew", addComment ) use $( "#commentForm" ).on( "click", ".addNew", addComment ). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "jquery, event handling, event bubbling"
} |
android,NDK, write logs to a file
I have this lines in my code (.c) :
#define LOGI(x...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,x)
#define LOGE(x...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,x)
I use them for outputing in LogCat, how to modify these lines to write messages to a file, or how can I get certain messages from LogCat in my code ? Thanks in advance. | If this is for debugging purpose, I use this macro:
#define WRITE_LOG(s, ...) do { \
FILE *f = fopen("/data/local/tmp/log.txt", "a+"); \
fprintf(f, s, __VA_ARGS__); \
fflush(f); \
fclose(f); \
} while (0)
It has the advantage of being totally independent from the Android SDK/NDK, which allows to debug native code without having to modify all your build system and includes in order to link on the logcat functions.
A small warning though: I've taken the habit of creating the file using `touch /data/local/tmp/log.txt` in adb-shell before launching the program, as in most cases the system prevents you from creating new files. And by the way, the location /data/local/tmp/ has the advantage of being accessible even without root privileges. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 3,
"tags": "android, logging, android ndk"
} |
how to extract raw html code using simplehtmldom
I am trying to extract raw html from a web-page using simplehtmldom. I was wondering if it is possible using that library.
For example, let's say I have this web page I am trying to extract data from.
<div class="class1">
<div class="class2">
<div class="class3">
<p>p1</p>
<h1>header here!</h1>
<p>p2</p>
<img src="someimage"></img>
</div>
</div>
</div>
My goal is to extract everything within div class3 including the raw html code so when I get the data I can enter it to a text box which allows input for source code so it is formatted the same way it is from the webpage.
I have looked at simplehtmldom manuals and did some searching but have yet to find a solution.
Thank you. | Using your example html string
$html = str_get_html('<div class="class1">
<div class="class2">
<div class="class3">
<p>p1</p>
<h1>header here!</h1>
<p>p2</p>
<img src="someimage"></img>
</div>
</div>
</div>');
// Find all divs with class3
foreach($html->find('div[class=class3]') as $element) {
echo $element->outertext;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "php, simple html dom"
} |
Nodal analysis in simple circuit
I have a circuit to solve: !enter image description here
!enter image description here
In this approach, I inferred the V1 from the parallel connection of voltage source. For the second node, I have applied the KCL.
I also tried to do it another way, by modifying the source E4 ( pushing it to the branch with G2 ) and then tried to apply nodal analysis.
Equation was like :
(G2+G1+G5)*V2=E4G2+E1G1-J
V2=(E4G2+E1G1-J)/(G2+G1+G5)
As You can see, both results differs by 'G5' in denominator. What is wrong? | If J5 is a current source, the voltage U will not depend on G5. The correct KCL at node 2 is:
$$(U - E_4)G_2 + (U - E_1)G_1 + J_5 = 0$$
Note that there is no G5 in the above expression. This is due to the fact that it is series with a current source.
Also, note that G3 is not in the above expression and this is because it is in parallel with a voltage source.
* * *
As an aside, this type of problem is easily solved by using superposition. Since there are three sources, there will be three terms in the superposition which are, by inspection:
$$U = E_1 \dfrac{G_1}{G_1 + G_2} + E_4 \dfrac{G_2}{G_1 + G_2} - \dfrac{J_5}{G_1 + G_2}$$ | stackexchange-electronics | {
"answer_score": 1,
"question_score": 0,
"tags": "voltage, resistors, circuit analysis"
} |
Show that there does not exist any analytic function for which $f\left(\dfrac{1}{n}\right)=\dfrac{1}{2^n}$
> Show that there does not exist any analytic function $f$ on the open disc for which $f\left(\dfrac{1}{n}\right)=\dfrac{1}{2^n}$.$\forall n\in \Bbb N$
Suppose such a function say $f$ exists then $f\left(\dfrac{1}{n}\right)=\dfrac{1}{2^n}$. By continuity of $f$ we have $\lim _{n\to \infty}f\left(\dfrac{1}{n}\right)=\lim_{n\to \infty}\dfrac{1}{2^n}\implies f(0)=0$
Also $f$ has a power series representation about $0$ i.e $f(z)=\sum_{n=0}^\infty \dfrac{f^n(0)}{n!}z^n;\forall z\in D$ where $D$ is open disc.
But I am failing to arrive at a contradiction from here.Please give some hints. | Suppose $f(z) = \sum_n a_n z^n$. You know that $a_0 = 0$.
Suppose $a_0,...,a_{k-1} $ are all zero. Then $\lim_{z \to 0} {f(z) \over z^k} = a_k$, and using the above formula, we can show that $a_k = 0$. Hence $f=0$ which is a contradiction.
Note that ${f({1 \over n}) \over {1 \over n^k}} = {n^k \over 2^n}$. This converges to zero as $n \to \infty$. | stackexchange-math | {
"answer_score": 10,
"question_score": 3,
"tags": "complex analysis, analytic functions"
} |
IOS: save an uimage when I press home button
In my app I should color some images but I have a problem
I have three viewcontroller, and I save my image in NShomedirectory/documents
When I color I'm in thirdViewController, when I change image with an IBAction I save it in NSHomedirectory, but if I'm coloring an image and I press home button , my image is not saved when I open a second time my app; (my app is not multitasking for some reason) is there a way to intercep home button press? | Following method is called when your app goes to background.
- (void)applicationDidEnterBackground:(UIApplication *)application
you can have image saving code in this method.
Check this link for more details - UIApplicationDelegate | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, uiimage, home directory"
} |
How to associate a row in a ListView with an object in collection?
I have a simple 3-column ListView. This control is programatically populated with data from a collection (a generic List) I'd like to use double click event on every row in this ListView to open another form. This form will display data which are in clicked row and will be also used to edit these data so I need access to proper object in collection. But I have no idea how to make a some sort of connection between a row in ListView and specific object in collection. | Use the `Tag` property, which exists exactly for that purpose.
From MSDN:
> Gets or sets an object that contains data to associate with the item.
To retrieve the data object, just cast the `Tag` property to the type of the object. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, winforms"
} |
Strange form behavior in IntelliJ's UI Designer
I'm using IntelliJ's UI designer and now I'm stuck as the designer has decided to chop off half of my form. In the UI Designer pane where it shows the components you have added to your form, I can clearly see all my components as expected. But in the main editor window where you see the form itself, IntelliJ has decided to chop off half of it!
Has anyone seen this behavior before and/or know how to resolve it? I have tried doing things like invalidating the cache and restarting IntelliJ several times (which worked once but the problem has come back and I can't seem to resolve it again). I fixed it the one time by restarting IntelliJ and then there was a little anchor to expand the form a little more to reveal the components that were in the white space, but that anchor no longer appears at the bottom of the form to expand.
I am using IntelliJ 9.0.3 Ultimate. | I found the anchors again used to make the form bigger. You can right click the form and choose "Expand Selection" (CTL+W) and then you can increase the size of the form in the editor. I'm not sure why it doesn't expand as you add more components automatically but this solution seems to do the trick. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, intellij idea"
} |
JS "inheritance" (code sharing) mechanism
I've recently been moving out of my comfort zone with JS, and come across a situation where it would make sense to share common functionality. What I've come up with is the following (concept only) code:
function subclass(parent, child) {
child.prototype = Object.create(parent.prototype)
}
function URL(str) {
this.value = str;
}
function HttpURL(str) {
this.value = str
}
subclass(URL, HttpURL)
URL.path = function() {
return this.value;
}
// ...
HttpURL.isSecure = function() {
this.value.substring(0, 8) === '
}
This code works as I expect it to work (making the "methods" on URL available on HttpURL, but not vice versa), but I wonder if it is "ethical" or if there is a better way of allowing this. | > a situation where it would make sense to share common functionality.
>
>
> subclass(URL, HttpURL)
>
Yes, that works and is the correct solution.
>
> URL.path = function() {
> return this.value;
> }
> HttpURL.isSecure = function() {
> this.value.substring(0, 8) === '
> }
>
>
> This code works as I expect it to work (making the "methods" on URL available on HttpURL, but not vice versa)
No. You want to make URL methods available on HttpUrl _instances_ , for which you would need to use the prototype:
URL.prototype.path = function() {
return this.value;
}
HttpURL.prototype.isSecure = function() {
this.value.substring(0, 8) === '
}
Otherwise they won't be inherited. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "javascript, inheritance, prototype"
} |
jQuery Address Plugin - Not allowing loading ajax?
I am trying to test the jQuery Address Plugin and it seems to not allow ajax to work in the change function.
I am using:
$.address.change(function(event) {
$('#content').load(event.value+' #content');
$.address.title(event.value);
});
$('a').click(function() {
$.address.value($(this).attr('href'));
});
While I can use event.value for other things, it just does not seem to let the .load() function work. Even trying a static URL in .load() does nothing. Is something in the plugin preventing this? I thought this was the point of the plugin! | Try using event.pathNames instead, I think you cant get this to work because you are not replacing the "/" from the value. Using event.pathNames you dont have to do that....
$('#content').load(event.pathNames+'.htm #content'); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, ajax, jquery plugins, deep linking"
} |
Overlapping backgrounds cause unwanted borderline
I'm trying to hide the borderline between the overlapping differently colored backgrounds. Has anybody a tip how to deal with this:
 | Dodge Tool can be great for these cases. Select it, set it to use a soft edge brush and set Exposure to something as high as 60%, but leave Protect Tones. Use it to lighten the gray areas, being careful to not lighten the image itself.
If the gray is still visible disable Protect Tones and do your best to keep away from the models, as it'll lighten the colors very quickly. | stackexchange-graphicdesign | {
"answer_score": 0,
"question_score": 2,
"tags": "adobe photoshop, tools, brush"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.