text:
Q: What makes the charge on a capacitor change? I have just realized that I actually do not have a through understanding of capacitors and hence, I am asking this basic question.
I was trying to understand how an astable multivibrator works using this source and I have come across the following part (diagram is in the link, and below):

...
The next significant thing which happens is when the voltage on
  the right hand plate of C1, and therefore TR2's base, approaches
  +0.6V.
TR2 begins to conduct.
The collector voltage of TR2, which by  now will have increased in
  value as C2 started to charge through R4, will fall and go down to
  +100mV.
The voltage across C2 can't change instantaneously so when the voltage
  at its right hand plate goes down the voltage at its left hand plate
  goes down by the same magnitude.  If TR2's collector voltage had risen
  to, say, +3V, then when it reduces to +100mV (a negative-going change
  of 2.9V) the left hand plate of C2, and the base of TR1, will also go
  2.9V more negative, but starting from +0.6V.
They will end up at –2.3V.  This will cut TR1 off.
...

So, as far as I understand, the following happens:
\$ C = Q / V \$ equation must hold for capacitors at all times. When we consider a particular capacitor, \$ C \$ is constant. This means that only \$ Q \$ and \$ V \$ may change in order to make the equation hold at all times.
However, there is a quirk with the capacitors. In a capacitor, \$ Q \$ cannot change instantaneously. That is, it takes time to change \$ Q \$.
Hence, when the voltage at one plate of a capacitor undergoes a sudden change (while the voltage on the other plate remains untouched), this event creates a situation where the equation \$ C = Q/V \$ does not hold. The reason is, \$ V \$ has changed, while \$ C \$ and \$ Q \$ are the same. (\$ Q \$ is the same because charge on a capacitor cannot change instantaneously)
However, we know that the equation \$ C = Q / V \$ must hold at all times. Hence, the capacitor responds this change by altering the voltage at its other plate, putting the equation \$ C = Q / V \$ in balance once again.
Here comes my question: Since the capacitor has changed V at its other plate in response to a sudden voltage change on the opposite plate, the equation \$ C = Q / V \$ is once again satisfied. However, we observe that the capacitor starts charging or discharging after this event.
Since the equation \$ C = Q / V \$ has been put in balance by the voltage change at the opposite plate, the reason for (dis)charging cannot be to balance the equation.
So if a capacitor does not (dis)charge in order to satisfy the equation \$ C = Q / V \$, then why does a capacitor (dis)charge?

A: The basic rule is you can't instantly change the voltage ACROSS a capacitor.
If you suddenly change the voltage on ONE PLATE then to maintain the voltage across the capacitor the other plate must instantly rise by the same amount.

A: This statement: -

In a capacitor, Q cannot change instantaneously. That is, it takes
  time to change Q

Is contradicted by this: -

the voltage at one plate of a capacitor undergoes a sudden change

Because: -
You cannot change the voltage instantaneously without infinite current being sunk into the capacitor. If infinite current is sunk (or sourced) by the capacitor then Q will change instantaneously.
The remainder of your question is based on this incorrect (or contradictory) premise.
Q = CV and the rate of change of Q (dQ/dt) = C dV/dt.
This of course equals current because rate of change of charge IS current.
Therefore if voltage changes instantly, dV/dt is infinite therefore current flow is infinite.

A: V is voltage across the capacitors plates, and that voltage can not be changed instantly. BUT potential of the plates can be changed instantly. When one plate of the capacitor, V1 ,is charged with some Q and because there is an electric field between plates, potential of other plate of the capacitor,V2, is instantly changed with same difference as first plate ( that makes V=V1-V2=Const.) When that process is done, the charge of the other plate V2 is going to flow through the resistor making a current with exponential form (because potential of that plate is falling down--that is discharge).
I hope this will help you to understand difference between voltage across capacitor and potentials of the plates, and what is discharge.
Charge of the capacitor is the same, if first plate of capacitor is connected to some voltage source via resistor (then you would have some current flow, and current is bringing charge to the plate of capacitor). At same time other plate is changing it potential making voltage across capacitor constant.

A: As Q=CV, the charge storage will depend upon the capacitance value which is factory built and specifies and also the voltage applied across its terminals.


text:
Q: How do I solve $\lvert \mathcal P(\{ 2,3,4 \}) \cap \{X : \lvert X\rvert = 2\} \rvert$ How do I solve $\lvert \mathcal P(\{ 2,3,4 \}) \cap \{X : \lvert X\rvert = 2\} \rvert$
I fail to understand how to define $ X: |X| = 2$ , I know that it is all the x's that contain 2 elements. for e.g.$ \{\{2,3\},\{2,4\} ,\{3,4\}\}$ is one of them. but I fail to understand how to check the intersection between both of them. I'd love to get a hint or a solution.

A: $\mathcal{P}(\{2,3,4\})$ contains the eight subsets of $\{2,3,4\}$.  The second set is the "set" (really proper class) consisting of all sets that contain exactly two elements.  Hence their intersection is the set containing all the subsets of $\{2,3,4\}$ that contain exactly two elements.

A: You are looking for the set of subsets of $\{2,3,4\}$ which contain two elements.
The intersection means that, of all possible size-2 sets in the universe, you are only looking for those that are also in the powerset.
$$\mathcal P\big(\{2,3,4\}\big)\cap\big\{X:\lvert X\rvert =2\big\} \;\equiv\; \Big\{X\in\mathcal P\big(\{2,3,4\}\big): \lvert X\rvert =2\Big\}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Double negation elimination in constructive logic How can I prove that the double negation elimination is not provable in constructive logic?
To clarify, double negation elimination is the following statement:
$$\neg\neg q \rightarrow q$$

A: There is an intuitionistic idea which becomes more valuable with the arrival of computational-mathematics. Roughly speaking in constructive logic or math, when you say "object A" exists you are saying "we know some way to build up A". This position implies the 'tertio excluso' rule $\neg(\neg q))\rightarrow q$  fails.
The classic example belongs to Brouwer (1925). We write the decimal expansion of $\pi$, and down to it the number $\rho=0.333\ldots$that we cut when the sequence $012346789$ appear in $\pi$ the first time. With the classical logic we say that $\rho$ is rational. If the sequence $012346789$ doesn't appear $\rho$ will be defined by $ \frac{1}{3}$. With the constructive approach you can't prove $\rho$ is rational before you find the first sequence $0123456789$ in $\pi$ or you have a proof that this sequence never appears in the decimal expansion of $\pi$.
But in constructive math you can prove that it is contradictory that $\rho$ is not rational. If we suposse $\rho$ isn't rational (equivalently, that we have a construction to tell apart $\rho$ of any rational number) then $\rho=0.3333\ldots 3$ must be impossible, and the sequence $0123456789$ doesn't appear in $\pi$. Therefore $\rho=\frac{1}{3}$ which is impossible too. Then it is contradictory that $\rho$ is not rational, but we don't have a proof that $\rho$ is rational.
EDIT:
My answer is complementary to other more formal answers. It goes to the main point to give up the $\neg(\neg q))\rightarrow q$. Essentially my answer is intuitionistic, no a formalism.

A: A very simple and efficient tree proof method (i.e. a tableau method without signed formulae) for intuitionistic logic has been published by Bell, DeVidi and Solomon in "Logical Options: An Introduction to Classical and Alternative Logics"
http://books.google.fr/books/about/Logical_Options.html?id=zUVYx-bTLgMC&redir_esc=y
Here is the tree counter-model for the formula $\neg \neg p \to p$, à la Bell $et{}~ al.$:
$$\underline{?(\neg \neg p \to p)}^{\surd}$$
          $$ ? p $$
          $$ \neg \neg p$$
          $$ \underline{? \neg p }^{\surd}$$
                $$ p $$
The tree show a Kripke counter-model where, in a locality expressed by a space between two horizontal lines, $p$ is not known to be true (i.e. is false in the locality), while $\neg \neg p$ is proved, i.e. is known to be true.  The symbol $?$ says that the formula is not known to be true, and it sticks the formula in the locality. The symbol $\surd$ says that the formula is deactivated. Every formula without $\surd$ or without $?$ can pass through any horizontal line (truth is persistent). For more details, see Bell et al.'s book.
This is very simple proof method to echo to the very nice explanation given by Zhen Lin. (I wish to thank Zhen Lin warmly for his post.)
Reading this page again, I must add that, contrarily to what Ben Millwood claimed, double negation elimination is not equivalent to the law of excluded middle, because if it is true that $(\neg A \lor A)$ implies $(\neg \neg A \to A)$ in intuitionistic logic, the converse is not intuitionistically provable. The fact that $(\neg \neg A \to A) \to (\neg A \lor A)$ is not an intuitionistic theorem contradicts the claim that double negation elimination is equivalent to the law of excluded middle.

A: There are two ways to go about this:

*

*Proof theory. We analyse the formal proofs in the inference system given, and show that there can be no formal proof of double negation elimination. This is difficult and depends a lot on the details of the inference system.

*Model theory. We construct a model of intuitionistic propositional logic in which double negation elimination is visibly false. This is much easier and less sensitive to details, but is conceptually more challenging.
First of all, what is a model of intuitionistic propositional logic? It is an algebraic structure $\mathfrak{A}$ equipped with constants $\top$ and $\bot$ as well as binary operations $\land$, $\lor$, $\to$, plus a partial order $\le$, such that the following soundness rule is valid: given formulae $\phi$ and $\psi$ in the language of intuitionistic propositional logic with propositional variables $x, y, z, \ldots$, if the sequent $\phi \vdash \psi$ is provable, then $\phi \le \psi$ in $\mathfrak{A}$ for all choices of $x, y, z, \ldots$ in $\mathfrak{A}$.
For example, $\mathfrak{A}$ could be a Heyting algebra, which is a algebraic structure satisfying some axioms. First of all $\mathfrak{A}$ is a (bounded) lattice:

*

*Unit laws:
\begin{align}
\top \land x & = x &
\bot \lor x & = x \\
x \land \top & = x &
x \lor \bot & = x
\end{align}

*Associativity, commutativity, and idempotence:
\begin{align}
(x \land y) \land z & = x \land (y \land z) &
(x \lor y) \lor z & = x \lor (y \lor z) \\
x \land y & = y \land x &
x \lor y & = y \lor x \\
x \land x & = x &
x \lor x & = x \\
\end{align}

*Absorption law:
\begin{align}
x \land (x \lor y) & = x &
x \lor (x \land y) & = x
\end{align}

One can then verify that $x \le y$ defined by $x \land y = x$ is a partial order on $\mathfrak{A}$ and that $\top$, $\bot$, $\land$, $\lor$ have their usual order-theoretic meanings. We then add some axioms for $\to$:

*

*Distributive law:
$$x \to (y \land z) = (x \to y) \land (x \to z)$$

*Internal tautology:
$$x \to \top = \top$$

*Internal weakening:
$$y \to (x \land y) = y$$

*Internal modus ponens:
$$x \land (x \to y) = x \land y$$

Exercise. Show that $y \le z$ implies $(x \to y) \le (x \to z)$, and $x \le ((x \land y) \to y)$ and $((x \to y) \land y) \le x$, and hence or otherwise that $x \land y \le z$ if and only if $x \le (y \to z)$.
Exercise. Verify the soundness rule for interpreting intuitionistic propositional logic in a Heyting algebra.
Proposition. Double negation elimination is not valid in intuitionistic propositional logic.
Proof. We construct a three-element Heyting algebra to falsify double negation elimination. Let $\mathfrak{A} = \{ \bot, \omega, \top \}$ and define the binary operations as below:
\begin{align}
\begin{array}{|r|ccc|}
\hline
\land & \bot & \omega & \top \\
\hline
\bot & \bot & \bot & \bot \\
\omega & \bot & \omega & \omega \\
\top & \bot & \omega & \top \\
\hline
\end{array} &&
\begin{array}{|r|ccc|}
\hline
\lor & \bot & \omega & \top \\
\hline
\bot & \bot & \omega & \top \\
\omega & \omega & \omega & \top \\
\top & \top & \top & \top \\
\hline
\end{array} &&
\begin{array}{|r|ccc|}
\hline
\to & \bot & \omega & \top \\
\hline
\bot & \top & \top & \top \\
\omega & \bot & \top & \top \\
\top & \bot & \omega & \top \\
\hline
\end{array}
\end{align}
Then, observe that $((\omega \to \bot) \to \bot) = \top$, but $\top \nleq \omega$. Therefore $(x \to \bot) \to \bot$ cannot be an axiom of intuitionistic propositional logic.
Remark. De Morgan's laws remain valid in this Heyting algebra. Find one which falsifies part of De Morgan's laws. (See this question.)


text:
Q: How to enable X-Forwarded-Proto for aws Classic Load Balancer I have an nginx (nginx-ingress in k8s) setup behind AWS CLB, and according to HTTP Headers and Classic Load Balancers and Listener Configurations for Classic Load Balancers, I should be able to receive X-Forwarded-Proto header in nginx.
But after going through CLB listener configuration, I don't see anything about this setting, I set it up to forward TCP port 443 and try checking $http_x_forwarded_proto inside nginx, the $http_x_forwarded_proto returns null

A: Can you check you are getting other headers?
In Values.yaml, enable use-forwarded-headers
 config:
    use-forwarded-headers: "true"


text:
Q: Checking for specific amino acids in specific positions in a multiple sequence alignment There is a similar question on Stack Overflow, but it is using the Linux terminal (Search for specific characters in specific positions of line). I would like to do a similar thing using python, and I cant quite work out what is the pythonic way to do this without having to manually write for the membership checks.

I would like to search for specific amino acids at specific positions of a multiple sequence alignment. I have defined the positions of the amino acid alignment in a list of indexes ,
e.g Index = [1, 100, 235, 500].

I have defined the amino acids I want in those positions also.
Res1 = ["A","G"]
Res2 = ["T","F"]
Res3 = ["S,"W"]
Res4 = ["H","J"]

I am currently doing something like this :
for m in records_dict:
    if (records_dict[m].seq[Index[0]] \
        in Res1) and (records_dict[m].seq[Index[1]] \
        in Res2) and (records_dict[m].seq[Index[2]] \
        in Res3) and (records_dict[m].seq[Index[3]]\
        in Res4)
    print m

Now, suppose I have a list of 40 residues I want to check, I know I have to write the lists of residues to check manually, but surely, there is an easier way to do this membership check using a while loop or something else.
Also, is there any way I could incorporate a system where if no sequences match all the 40 membership checks, I would get the 5 best sequences that are closest to matching all 40 checks, and an output such as sequence "m" has 30/40 matches and a list of what those 30 matches are, and which 10 didn't match?

A: I will assume you want to check if Res1 is at Index[0], Res2 at Index[1] and so on.
res = [Res1, Res2, Res3, Res4]
for m in records_dist:
    match = 0
    match_log = []
    for i in Index:
        if records_dict[m].seq[i] in res[i]:
            match += 1
            match_log.append(i)

With this little code, you're able to compute the number of match, and track the indexes where match occurs for each records_dist values.
If you want to check if ResX is at multiple position, or if you don't want to order the indexes list like the Res list, I'd define a dictionary of list where keys are ResX and values are list of indexes:
to_check = {}
to_check[Res1] = [index1, index2]
to_check[Res2] = [index1, ..., indexN]
...
to_check[ResX] = [indexI, ..., indexJ]

then, using
match_log = {}
for m in records_dist:
    match_log[m] = {}
    for res, indexes in to_check:
        match_log[m][res] = []
        for i in indexes:
            if records_dict[m].seq[i] in res:
                match_log[m][res].append(i)
        nb_match = len(match_log[m][res])

or in a more pythonic way, using filter:
match_log = {}
for m in records_dist:
    match_log[m] = {}
    for res, indexes in to_check:
        match_log[m][res] = filter(lamba i: records_dict[m].seq[i] in res, indexes)
        nb_match = len(match_log[m][res])


text:
Q: Sql Recursive Function only show nods that have specifik relation I have a Link structure table with ID and parentID.
ID, Parent, name
1,1
2,1
3,2
4,3
5,3

To this table I have a structure_article relation table
in this table I have relation between a Link and a article.
struture_article
structid, articleID
4,1000
4,1001
5,1002

Every article in that table have a supplier.
Now i am trying to create a recursive function that creates the tree
nods if i pick a specific supplier.
Article table
ArticleID, SUPPLIER ID
1000,1
1001,2
1002,2

If I pick articles with supplier 1 then I want the function to show me the tree structure that have articles from that supplier.
I have 20 suppliers and 300 links in the DB now i want only to show articles from the suppliers i pick. I don want any empty nods.
Is this even possible do create with a recursive function in Sql Server version 2008?
I tyied wiht this code the problem is that i get only nods that have articles connected
         WITH a
     AS (SELECT *
         FROM   structure
         WHERE  parent = 125

         UNION ALL
         SELECT m.*
         FROM   structure m
                JOIN a
                  ON m.parent = a.internidstructure)
SELECT *
FROM   a
WHERE  internidstructure IN (SELECT DISTINCT( internidstructure )
                             FROM   dbo.articles
                                    INNER JOIN dbo.structure_article
                                            ON dbo.articles.internidarticle =
dbo.structure_article.internidarticle
WHERE  ( dbo.articles.internidsupplier IN (SELECT
internidsupplier
                         FROM   site_sup
                         WHERE
internidsite = 1) ))
ORDER  BY parent,
          sortno

A: Try using a left join instead of an inner join.

A: I'm not sure to have understood your need but if you want to have a new tree table without nodes not linked to a supplier, this query can work.
WITH A AS
(
SELECT S.ID as ID, S.Parent as Parent, 1 as art_linked
FROM   structure S
       INNER JOIN dbo.structure_article SA
            ON S.ID = SA.structid
       INNER JOIN Article AR
            ON  AR.ArticleID = SA.ArticleID
WHERE  AR.SupplierID = 1

UNION ALL
SELECT S.ID, S.Parent, 0
FROM   structure S
       INNER JOIN A
              ON A.parent = S.ID
WHERE S.ID <> S.Parent
)

SELECT A.ID, A.Parent, MAX(A.art_linked)
FROM A
GROUP BY A.ID, A.Parent


text:
Q: Errno::EACCES in PicturesController#create I'm using the carrierwave-dropbox gem and using both win 10 & mac os x with my rails app but on windows (and not Mac) I get this error when trying to upload (the upload occurs, it doesn't write to the app db on localhost).
Errno::EACCES in PicturesController#create
Permission denied @ unlink_internal C:/Users/name/apps/dropbox/public/uploads/tmp/1448853449-5268-0532/IMG_7871.JPG

I've read articles about permissions and I have tried changing those but with no success - is there anything else recommended I should try?

A: Did you try changing the permission of the uploads directory this way?:
chmod -R 666 C:/Users/name/apps/dropbox/public/uploads
chmod -R 666 C:/Users/name/apps/dropbox/public/uploads/tmp

If not, try it. Because the issue is related to the permission of the files inside the uploads directory.


text:
Q: Objective C Update RESTful Webservice I have a web service that allows me to update records on in our database.
The columns in the table are as follows:

*

*allowsActions

*assetID

*inventoryObjectID

*objectDescription

*quantity

*retired

*serialNumber

*action

I'm using the following to GET data from the webservice.
NSString *urlString = [NSString stringWithFormat:@"%@", inventoryAndActionsWebservice];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];

Then shoving into a dictionary like so:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
 {
     if (data.length > 0 && connectionError == nil)
     {
         NSLog(@"WE HAS THE DATAS");
         NSDictionary *inventory = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        // Then storing the values in CoreData here
     }
 }

What would be the syntax for updating the webservice? It expects an object in the body of the service call (POST).

A: NSMutableURLRequest let's you setHTTPBody: and setHTTPMethod:.@"POST"is the way to do a post.  Most services need to know the body length and encoding set in headers.  (seeaddValue:forHTTPHeaderField:`) for that.
The only reason this topic is tricky is because the developer is forced to grapple with two problems at once:  what constitutes a valid request for my server, and (2) how do I form that request with iOS?  Part (2) is actually pretty easy once you get a valid request.
The best way to proceed is to get an example working using curl (or something equivalent).  Then move on to producing that request in iOS.  If you have trouble, ask a question here of the form:  "I know my server needs X, here's my code to produce X, but I'm getting this error Y".

A: So the syntax that I was looking for was ultimately this:
NSString *jSONString = [NSString stringWithFormat:@"{\"MediaInventoryObjectsId\":%d,\"AssetId\":%d,\"Quantity\":%d,\"SerialNumber\":\"%@\",\"Description\":\"%@\",\"AllowActions\":%d,\"Retired\":%d}",inventoryObjectId, assetID, quantity, serialNumber, description, allowActions, retired];

// Convert jSON string to data
NSData *putData = [jSONString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

// Instantiate a url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

// Set the request url format
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%d", inventoryAndActionsWebservice, inventoryObjectId]]];
[request setHTTPMethod:@"PUT"];
[request setHTTPBody:putData];
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];

// Send data to the webservice
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];


text:
Q: Enable button after File Upload Using JQuery in ASP.net to upload files.  After the upload is complete I want to enable visibility on a button for the user to continue to the next step.  I've attempted using the show function without success.
Here's my code and html

                <asp:FileUpload runat="server" ID="UploadImages" AllowMultiple="true" />
                <input type="button" id="btnUpload" value="Upload Files" class="btn btn-lg btn-primary" onclick="UploadFile()" />
                <%--<asp:Label ID="listofuploadedfiles" runat="server" />--%>

                <progress id="progressBar" value="0" max="100" style="width: 300px; height: 50px;"></progress>

                <asp:Button runat="server" CssClass="btn btn-lg btn-primary" ID="btnContinue" Text="Process Images" OnClick="btnContinue_Click" />

A: It seems that you're simply missing # for the element selector reference?
Change:
$("btnContinue").show();

To:
$("#btnContinue").show();


text:
Q: What is the difference between synchronized(this) and synchronized(ClassName.class)? I read somewhere that synchronized(this) should be avoided for various reasons. Yet some respectable code that I encountered uses the following in the constructor:
public SomeClass(Context context) {
  if (double_checked_lock == null) {
    synchronized (SomeClass.class) {
      if (double_checked_lock == null) {
        // some code here
      }
    }
  }
}

Is there really a difference between synchronized(this) and synchronized(SomeClass.class)?

A: this is different for each instance.
ClassName.class is not.
Therefore, synchronized(this) will allow multiple instance to run simultaneously.

A: synchronized(this) is synchronized on the current object, so only one thread can access each instance, but different threads can access different instances. E.g. you can have one instance per thread.
This is typically useful to prevent multiple threads from updating an object at the same time, which could create inconsistent state.
synchronized(SomeClass.class) is synchronized on the class of the current object ( or another class if one wished) so only one thread at a time can access any instances of that class.
This might be used to protect data that is shared across all instances of a class (an instance cache, or a counter of the total number of instances, perhaps) from getting into an inconsistent state .

A: The synchronized keyword, when applied to a class locks on the class, and when it's applied to this locks on the current object instance. From the Java Language Specification, section 8.4.3.6, 'synchronized Methods':

A synchronized method acquires a monitor (§17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

A: Each java Object can have a lock. This lock can be held by at most one thread at a time, any other thread has to wait to get the lock of the same object.

*

*synchronized(this) acquires the lock of the instance this  for the current thread. The method can run parallel on different instances (different values for this and therefore different locks)

*synchronized(SomeClass.class) acquires the lock of the global class object of SomeClass. Only one instance of the method can run as all object instances lock on the same global object (same lock).

A: These are 2 different object to lock on:
'this' refer to current instance context, so creating multiple instances will have no effect if, for example, each thread using a different instance and lock on it. 'this' can be referred only on non-static context.
the 'class' is a static member of the Java Class and there is exactly one instance of it. You can lock on it in both static and non-static context.

A: synchronized(this) synchronizes on the instance of the object.
synchronized(SomeClass.class)uses the instance of the Class object that represents SomeClass, which is global for all instances in the same classloader.
Thus, these are different constructs with different semantics.
Using synchronized alone, or as a method modifier, also synchronizes on the instance's semaphore, which is normally used to prevent contention between multiple threads accessing that instance as a shared resource (i.e. a List).
The thread you refer states that it's a better practice to use a private instance, as synchronizing directly on your object instance may be dangerous. For that you'd use:
class MySharedResourceClass {

    private SomeClass lock = new SomeClass();

    public doSomething() {
        synchronized (lock) {
            // Do something here
        }
    }
}


text:
Q: getJSON request isnt parsing data I have a page that onload is adding fields to a form, but this call never seems to step into the .each statement inside of getJSON. I can see the url being fetched with a GET on the network tab of chrome, but it doesnt add any inputs to my form.
$.each( brand, function( key, value ) {
    if(domain == value) $("#brand").show();
    $.getJSON( 'http://forms.anniesatticmysteries-news.com/ats/url.aspx?cr=422&wu=1', function( data ) {
        $.each( data, function( key, val ) {
            $("#brandForm").append('<input type="hidden" name="s_email_sp'+ [value][0] +'_status_id" value="'+ [value][2] +'" /> ');
        });
    });
});

And here is a part of my json object.
{
"anniescatalog-news.com":["1","email_sp1_status_id","{(email_sp1_status_id)}"],
"anniesmysteries-news.com":["2","email_sp2_status_id","{(email_sp2_status_id)}"],
"anniesnewsletters-news.com":["3","email_sp3_status_id","{(email_sp3_status_id)}"],
"annies-publishing-news.com":["4","email_sp4_status_id","{(email_sp4_status_id)}"]
}

The domains are the same that I am requesting from, so it shouldnt be a cross site issue. Here is the url: http://forms.anniesatticmysteries-news.com/ats/show.aspx?cr=422&fm=43&dm=AnniesAtticMysteries-news.com

A: I'm pretty sure your Json is formatted incorrectly for what you want.
If you take:
var obj1 = {
"anniescatalog-news.com":["1","email_sp1_status_id","{(email_sp1_status_id)}"],
"anniesmysteries-news.com":["2","email_sp2_status_id","{(email_sp2_status_id)}"],
"anniesnewsletters-news.com":["3","email_sp3_status_id","{(email_sp3_status_id)}"],
"annies-publishing-news.com":["4","email_sp4_status_id","{(email_sp4_status_id)}"]
};

If you look at this in an inspector you can see the url is a property name not a value:

so you can't access anniescatalog-news.com as a value. The property is called anniescatalog-news.com: obj1.anniescatalog-news.com == "1","email_sp1_status_id","{(email_sp1_status_id)}" Fiddle here
If you can change the Json to:
[
    {name:"anniescatalog-news.com", value:["1","email_sp1_status_id","{(email_sp1_status_id)}"]},
    {name:"anniesmysteries-news.com", value:["2","email_sp2_status_id","{(email_sp2_status_id)}"]},
    {name:"anniesnewsletters-news.com", value:["3","email_sp3_status_id","{(email_sp3_status_id)}"]},
    {name:"annies-publishing-news.com", value:["4","email_sp4_status_id","{(email_sp4_status_id)}"]}
]

Or similar. Now you have an array (Json notation: [])of objects (Json notation: {}) containing name and value pairs. So you can access these thus:
var obj1 = [
    {name:"anniescatalog-news.com", value:["1","email_sp1_status_id","{(email_sp1_status_id)}"]},
    {name:"anniesmysteries-news.com", value:["2","email_sp2_status_id","{(email_sp2_status_id)}"]},
    {name:"anniesnewsletters-news.com", value:["3","email_sp3_status_id","{(email_sp3_status_id)}"]},
    {name:"annies-publishing-news.com", value:["4","email_sp4_status_id","{(email_sp4_status_id)}"]}
];

$.each(obj1, function(index, obj2) {
    alert(obj2.name);
});

fiddle
You can also access the value array thus:
obj2.value[1]

Fiddle
BTW the standard Json serializer's tend to make a hash of this kind of stuff. I'd recommend Json.Net for something that works better.

Your response is badly formatted for some reason:
[
    {name:"anniescatalog-news.com", value:["1","email_sp1_status_id",""]},
    {name:"anniesmysteries-news.com", value:["2","email_sp2_status_id",""]},
    {name:"anniesnewsletters-news.com", value:["3","email_sp3_status_id",""]},
    {name:"annies-publishing-news.com", value:["4","email_sp4_status_id",""]},
    {name:"anniesquiltedmysteries-news.com", value:["5","email_sp5_status_id",""]},
    {name:"annieswsl-news.com", value:["6","email_sp6_status_id",""]},
    {name:"cardmakerkitclub-news.com", value:["email_sp7_status_id",""]},
    {name:"cardmakermagazine-news.com", value:["email_sp8_status_id",""]},
    {name:"countrysampler-news.com", value:["email_sp9_status_id",""]},
    {name:"creativegirlsclub-news.com", value:["email_sp10_status_id",""]},
    {name:"creativeknittingmagazine-news.com", value:["email_sp11_status_id",""]},
    {name:"creativequiltersfabricclub-news.com", value:["email_sp12_status_id",""]},
    {name:"creativewomanmysteries-news.com", value:["email_sp13_status_id",""]},
    {name:"crochetmagazine-news.com", value:["email_sp14_status_id",""]},
    {name:"crochet-world-news.com", value:["email_sp15_status_id",""]},
    {name:"e-patternscentral-news.com", value:["email_sp16_status_id",""]},
    {name:"freebeadguide-news.com", value:["email_sp17_status_id",""]},
    {name:"free-cardmaking-news.com", value:["email_sp18_status_id",""]},
    {name:"free-crochet-news.com", value:["email_sp19_status_id",""]},
    {name:"free-knitpatterns-news.com", value:["email_sp20_status_id",""]},
    {name:"freepatterns-news.com", value:["email_sp21_status_id",""]},
    {name:"free-quilting-news.com", value:["email_sp22_status_id",""]},
    {name:"freequiltingguide-news.com", value:["email_sp23_status_id",""]},
    {name:"free-sewing-news.com", value:["email_sp24_status_id",""]},
    {name:"freesewingguide-news.com", value:["email_sp25_status_id",""]},
    {name:"goodolddaysmagazine-news.com", value:["email_sp26_status_id",""]},
    {name:"goodolddaysstore-news.com", value:["email_sp27_status_id",""]},
    {name:"hookandneedleclub-news.com", value:["email_sp28_status_id",""]},
    {name:"just-crossstitch-news.com", value:["email_sp29_status_id",""]},
    {name:"knitandcrochetnow-news.com", value:["email_sp30_status_id",""]},
    {name:"learntoknitsocks-news.com", value:["email_sp31_status_id",""]},
    {name:"liveitagain-news.com", value:["email_sp32_status_id",""]},
    {name:"quiltersworld-news.com", value:["email_sp33_status_id",""]},
    {name:"sanqmagazine-news.com", value:["email_sp34_status_id",""]},
    {name:"simplybeadskitclub-news.com", value:["email_sp35_status_id",""]},
    {name:"youngwoodworkers-news.com", value:["email_sp36_status_id",""]},
    {name:"anniescatalog-orders.com", value:["email_sp37_status_id",""]},
    {name:"annieswsl-orders.com", value:["email_sp38_status_id",""]},
    {name:"e-patternscentral-orders.com", value:["email_sp39_status_id",""]},
    {name:"goodolddaysstore-orders.com", value:["email_sp40_status_id",""]},
    {name:"orders.annies-publishing-news.com", value:["email_sp41_status_id",""]},
    {name:"orders.anniesquiltedmysteries-news.com", value:["email_sp42_status_id",""]},
    {name:"orders.cardmakerkitclub-news.com", value:["email_sp43_status_id",""]},
    {name:"orders.cardmakermagazine-news.com", value:["email_sp44_status_id",""]},
    {name:"orders.countrysampler-news.com", value:["email_sp45_status_id",""]},
    {name:"orders.creativegirlsclub-news.com", value:["email_sp46_status_id",""]},
    {name:"orders.creativeknittingmagazine-news.com", value:["email_sp47_status_id",""]},
    {name:"orders.creativequiltersfabricclub-news.com", value:["email_sp48_status_id",""]},
    {name:"orders.creativewomanmysteries-news.com", value:["email_sp49_status_id",""]},
    {name:"orders.crochetmagazine-news.com", value:["email_sp50_status_id",""]},
    {name:"orders.crochet-world-news.com", value:["email_sp51_status_id",""]},
    {name:"orders.goodolddaysmagazine-news.com", value:["email_sp52_status_id",""]},
    {name:"orders.hookandneedleclub-news.com", value:["email_sp53_status_id",""]},
    {name:"orders.just-crossstitch-news.com", value:["email_sp54_status_id",""]},
    {name:"orders.liveitagain-news.com", value:["email_sp55_status_id",""]},
    {name:"orders.quiltersworld-news.com", value:["email_sp56_status_id",""]},
    {name:"orders.sanqmagazine-news.com", value:["email_sp57_status_id",""]},
    {name:"orders.simplybeadskitclub-news.com", value:["email_sp58_status_id",""]},
    {name:"orders.youngwoodworkers-news.com", value:["email_sp59_status_id",""]},
    {name:"email.anniesnewsletters-news.com", value:["email_sp60_status_id",""]},
    {name:"email.anniescatalog-news.com", value:["email_sp61_status_id",""]},
    {name:"email.countrysampler-news.com", value:["email_sp62_status_id",""]},
    {name:"goodolddaysnewsletter.com", value:["email_sp63_status_id",""]},
    {name:"anniesquiltersworldnewsletter.com", value:["email_sp64_status_id",""]},
    {name:"anniestalkingcrochetnewsletter.com", value:["email_sp65_status_id",""]},
    {name:"anniescreativewomannewsletter.com", value:["email_sp66_status_id",""]},
    {name:"anniescreativeknittingnewsletter.com", value:["email_sp67_status_id",""]},
    {name:"anniessewingsavvynewsletter.com", value:["email_sp68_status_id",""]},
    {name:"e-patternscentral-daily-news.com", value:["email_sp69_status_id",""]},
    {name:"anniesquiltsewdaily-news.com", value:["email_sp70_status_id",""]},
    {name:"anniescardmakernewsletter.com", value:["email_sp71_status_id",""]},
    {name:"anniessimplybeadsnewsletter.com", value:["email_sp72_status_id",""]},
    {name:"anniescrochetcraft-news.com", value:["email_sp73_status_id",""]},
    {name:"e-patternscentral-quilt-news.com", value:["email_sp74_status_id",""]},
    {name:"anniesgoodolddaysstoredaily-news.com", value:["email_sp75_status_id",""]},
    {name:"anniesquiltdaily-news.com", value:["email_sp76_status_id",""]},
    {name:"anniescrochetknitdownload-news.com", value:["email_sp77_status_id",""]},
    {name:"anniesquiltsewdownloads-news.com", value:["email_sp78_status_id",""]},
    {name:"anniesknityarndaily-news.com", value:["email_sp80_status_id",""]},
    {name:"anniescrochetloversdaily.com", value:["email_sp81_status_id",""]},
    {name:"annieslovetoknit.com", value:["email_sp82_status_id",""]},
    {name:"annieslovetoquilt.com", value:["email_s83_status_id",""]},
    {name:"anniescrochetdaily-news.com", value:["email_sp84_status_id",""]},
    {name:"e-patternscentral-crochet-news.com", value:["email_sp85_status_id",""]},
    {name:"e-patternscentral-knitting-news.com", value:["email_sp86_status_id",""]},
    {name:"anniescreativecards.com", value:["email_sp87_status_id",""]},
    {name:"anniesplasticcanvaslovers.com", value:["email_sp88_status_id",""]},
    {name:"anniesbeadsandjewelry.com", value:["email_sp89_status_id",""]},
    {name:"anniesonlineclassdaily-news.com", value:["email_sp90_status_id",""]},
    {name:"anniesknitandcrochetnownewsletter.com", value:["email_sp91_status_id",""]},
    {name:"anniescrossstitchneedlework.com", value:["email_sp92_status_id",""]},
    {name:"anniesjustcrossstitchnewsletter.com", value:["email_sp93_status_id",""]},
    {name:"anniessimplysewing.com", value:["email_sp94_status_id",""]},
    {name:"anniesfabrictrendreport.com", value:["email_sp95_status_id",""]},
    {name:"anniesyarntrendreport.com", value:["email_sp96_status_id",""]},
    {name:"anniesatticmysteries-news.com", value:["email_sp97_status_id",""]},
    {name:"anniescreativepainter-news.com", value:["email_sp98_status_id",""]},
    {name:"anniescreativewomanclub-news.com", value:["email_sp99_status_id",""]},
    {name:"anniessecretofthequilt-news.com", value:["email_sp100_status_id",""]},
    {name:"anniesmysteriesunraveled-news.com", value:["email_sp101_status_id",""]},
    {name:"countrysamplermagazine-news.com", value:["email_sp102_status_id",""]},
    {name:"clotilde-news.com", value:["email_sp103_status_id",""]},
    {name:"CountrySamplerStyleToSpare-news.com", value:["email_sp104_status_id",""]},
    {name:"CountrySamplerIssuePreview-news.com", value:["email_sp105_status_id",""]}
]

Whats the

Doing there??? Use fiddler to inspect your HTTP.


text:
Q: How to get Play Progress of Vimeo video from android webview? I m building an app which requires vimeo video play support. I got success in playing video but dont know how to get current video play progress.
I am using HTML5WebView as suggested in https://github.com/droid28/VimeoVideo.
If anybody has idea..please suggest..
Thanks
Here is the Code:
webview = (WebView)findViewById(R.id.webView1);
WebSettings webViewSettings = webview.getSettings();
webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webview.addJavascriptInterface(new JavaScriptInterface(this),"jsInterface");
webview.setWebChromeClient(new WebChromeClient());
webViewSettings.setJavaScriptEnabled(true);
webViewSettings.setPluginState(PluginState.ON);

 String page=" " +
                " " +
                    "" +
                "" +
                    "" +
                        "" +
                        "" +
                    "" +
                "";

webview.loadDataWithBaseURL("file:///android_asset/page.html", page,"text/html", "UTF-8",null);

A: I'm looking for the same thing but I think, unfortunately, the answer is still that their player doesn't support play progress events on mobile
See this table to see which events are supported on which platform https://developer.vimeo.com/player/js-api#event-compatibility


text:
Q: How can be copied the data showed in an frx report on screen? I have a exe based on VFP9, and I'm looking to copy the data that appears on the screen when a large report (200+ pages) is generated, since the option to save it has been disabled. (when you hit ctrl+F3).
I would like to export the data to a txt, csv or xls file.
I don't have the project files, only the exe and some dlls.
There is a folder called reports that I'm guessing should contain the report files, but it is empty.
Can this be done from within the VFP9 IDE?


text:
Q: Try to sort records after joining table using PageRequest Hibernate JPA need help I have data table that display joining table records then there is option to sort by clicking a column. In this case I want to sort joined column by using PageRequest.
I want to sort / order by roleIdentifier that joined to employee table.
right now the way I call the repository like this
this.employeeRepository.findAll(pageRequest);
where the pageRequest parameters for sort I set with "role" just like inside the employee entity. But then sorting doesn't work properly.
Did I miss something ?
I have Employee Entity like this
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;

  @Column(name = "identifier")
  private String identifier;

  @OneToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "identifier",  referencedColumnName = "identifier", insertable = false, updatable = false)
  private UserRoleEntity role;

and I have user Role Entity like this
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "identifier")
  private String identifier;
  @Column(name = "roleIdentifier")
  private String role;

thanks in advace

A: use primary key for relation, or is idenitifier unique?
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "roleId", insertable = false, updatable = false)
private UserRoleEntity role;

and then try
employeeRepo.findAll(PageRequest.of(0,10, Sort.by(Sort.Direction.DESC, "role.identifier")));


text:
Q: How to duplicate a movement construct of one element to another? JavaScript Below is an example of a box moving left,right,up or down based
on pressing the arrow keys. However when I added a "laser" and used
the exact same principal/code to move the laser from left to right using "laserLeft++;" with the space bar, it does not move. I have very
carefully duplicated the code from the "square" to apply to the laser and
I cannot find why there is no movement. (I did not copy and paste the entire view source since it isn't relevant to problem).
the specific function is question is fireLaser().
#square {
position: absolute;
top: 0px;
left: 0px;
height: 5px;
width: 5px;
background-color: white;
}
#laser {
postion: absolute;
top: 0px;
left 0px;
height: 2px;
width: 5px;
background-color: red;
}

<script>
document.addEventListener("keydown", keyBoardInput);

var boxTop = 0;
var boxLeft = 0;
var laserTop = 0;
var laserLeft = 0;

function moveBoxUp(){
var square = document.getElementById("square");
boxTop--;
square.style.top = boxTop;

};
function moveBoxDown(){
var square = document.getElementById("square");
boxTop++;
square.style.top = boxTop;

};
function moveBoxLeft(){
var square = document.getElementById("square");
boxLeft--;
square.style.left = boxLeft;

};
function moveBoxRight(){
var square = document.getElementById("square");
boxLeft++;
square.style.left = boxLeft;

};
function fireLaser(){
var laser = document.getElementById("laser");
laserLeft++;
laser.style.left = laserLeft;
};

var i = event.keyCode;
if(i == 38){
moveBoxUp();
};

if(i == 40){
moveBoxDown();
};

if(i == 37){
moveBoxLeft();
};

if(i == 39){
moveBoxRight();
};

if (i == 32){
fireLaser();
};

};
</script>

A: I found my error!!! it was incorrectly typed "postion: absolute;" now it works perfectly!!!


text:
Q: Do the flags get called when I make this program? I recently got feedback that my Makefile doesn't call the required flags. This is a snippet of my Makefile.
CXX = g++
CXXFLAGS = -Wall

all: testFacility testCode testRunway testSiteNumber airport distance

testFacility: testFacility.cpp Facility.o gcdistance.o
    $(CXX) -o $@ $^

Does the flag "-Wall" get called when I type Make?

A: No, it needs to be referenced directly:
$(CXX) $(CXXFLAGS) -o $@ $^

You probably want to define something to compile all those .cpp files too:
%.o: %.cpp
    $(CXX) $(CXXFLAGS) -c -o $@ $<

testFacility: testFacility.o Facility.o gcdistance.o
    $(CXX) $(CXXFLAGS) -o $@ $^


text:
Q: How to remove links on the footer in Magento 1.9 The links I am trying to remove are in yellow. I have tried the links.phtml file and when I remove it or alter it the links under the account tab will not pop up when the account link is clicked. I am using magento 1.9 and the included template that come with the install. Does anyone know how to remove the bottom ones and it not effect the top links.

A: Those links aren't hardcoded or coming from CMS either, they are added dynamically via layout XML files. Example from app/design/frontend/rwd/default/layout/catalog.xml:
<reference name="footer_links">
    <action method="addLink" translate="label title" module="catalog" ifconfig="catalog/seo/site_map"><label>Site Map</label><url helper="catalog/map/getCategoryUrl" /><title>Site Map</title></action>
</reference>

The easiest way to remove them is via your own layout XML file from your custom theme like so:
<reference name="footer_links">
    <action method="removeLinkByUrl"><url helper="catalog/map/getCategoryUrl" /></action>
    <action method="removeLinkByUrl"><url helper="catalogsearch/getSearchTermUrl" /></action>
    <action method="removeLinkByUrl"><url helper="catalogsearch/getAdvancedSearchUrl" /></action>
</reference>


text:
Q: Parse a Website that contains AJAX with Python - Which libraries? I want to parse different websites which contain Javascript / JQuery / AJAX. What options do I have in Python?
I have seen several different libraries, but I want to know, which is the best to go for?

A: You can always use selenium / splinter with the xvfb ;)
your_bash_script.sh:
#!/usr/bin/env bash
set -e
xvfb-run --server-args="-screen 0 1024x768x24" python your_parse_script.py


text:
Q: Stack of Images as Single Input to CNN I am newbie, I need your help. How can I combine 3 different images for making single input for CNN neural network? In simple words I am using list of 3 images as single input with one output.
let's suppose :
x1=[img1,img2,img3] ====> y1
x2=[img1,img2,img3] ====> y2
x3=[img1,img2,img3] ====> y3

Thanks!

A: The idea in this case is is known as a multi-input model. Such model would have a stack of layer until some point where every stack is concatenated to follow a new stack of prediction. You can imagine it as this:

The source of this image and the implementation of such model can be found here: https://blog.csdn.net/alphachx/article/details/96482328


text:
Q: Conceptual difficulty with friction and inertia Consider this -
A box lies on the floor of a bus which starts accelerating. Two cases arise
$1.$ If the static friction is great enough, the box accelerates with the bus with acceleration equal to that of the bus in the direction of force
$2.$ If the static friction is not great enough, the box tries to maintain its inertia and then moves with the bus after kinetic friction kicks in.
My question is if my reasoning in the second case is not flawed, the value of kinetic friction is greater than that of static friction (this follows since there are no other forces acting on the block except friction), which is wrong.
Where is my reasoning flawed?
P.S. - In the second case, my reasoning is the static friction is in $0$, so no forces acts on the object initially, but since the floor moves away, kinetic friction increases, which causes the object to move with the bus.

A: Let's consider both cases in the frame of the road. Let the bus have acceleration $a$.

*

*The box sticks to the bottom of the bus. Hence, the box accelerates with with the bus, and its acceleration is also $a$. This acceleration is due to the static friction force.

*The box slips and doesn't quite accelerate as quickly as the bus. Its acceleration is less than $a$. This acceleration is due to the kinetic friction force.

Since the box experiences a smaller acceleration in scenario (2), it experiences a smaller force. Hence, the kinetic friction force is less than the static friction force.

A: You are wrong in thinking that kinetic friction is greater than static friction. When you start pushing against an object, at first it it does not move, As you increase the force, eventually it starts to move. Once it's moving, you can decrease the force, while still keeping the box moving.
This explains the use of Anti-lock Braking Systems (ABS) in cars. When a wheel is not skidding, its point of contact with the ground is static. When you brake with ABS, sensors detect when a wheel stops turning, indicating skidding. The system then automatically releases the brakes. This allows the wheel to stop skidding and re-establish static friction. Doing this enables the car to sustain maximum braking power.
You can test this if you have a car without ABS. On a wet or icy road (without obstacles, preferably), apply more and more force on the brake pedal. When the wheels lock up it will feel as it the car suddenly shoots forward. Release the brake and try again more gently for more braking force. Before ABS was introduced, this was routine practice for experienced drivers.

A:

*

*If the static friction is great enough, the box accelerates with the bus with acceleration equal to that of the bus

This is correct, and the sentence should end here. The box and the bus have equal acceleration, and acceleration includes direction. Adding the words "in the direction of force" here does not make sense.

*If the static friction is not great enough, the box tries to maintain its inertia and then moves with the bus after kinetic friction kicks in.

This seems to suggest that the box first remains stationary, but after some time, kinetic friction passes some threshold and the box starts moving. Everything about this description is incorrect.
If the static friction is not great enough, the box slips. When the box slips, there is no static friction at all, only kinetic friction. This kinetic friction is proportional to the normal force (in this case, constant). In any case, the kinetic friction does not depend on how much the box has slipped. [1] The box does not accelerate as much as the bus, but it does accelerate, and this acceleration begins immediately.
[1] Unless this slippage causes the box to move to a section of floor with a different coefficient of friction.

A: The flaw in your reasoning is that you have confused two different situations in case 2.
You have described one situation in which the bus has constant acceleration, and the force of friction is not enough to match the acceleration of the bus. In this case, DanDan0101's answer is completely correct: the box will slide backward forever.
But the other situation is one where the box starts sliding, then eventually stops. This result is entirely possible - you've probably seen it happen in real life, which is why you're asking about it. So what's different about this situation that makes the box eventually stop?
The answer is that the acceleration of the bus isn't constant.
The bus accelerates for a certain amount of time, and during this time the box slides because the friction force can't accelerate the box enough to keep up. Then the bus stops accelerating and moves at a constant velocity. Now the box's acceleration due to friction is greater than the bus's (because the bus's acceleration is 0), and the box will stop sliding once it has accelerated to match the bus's velocity.


text:
Q: how do I pass a command status to Postrun in cobra cli Cobra CLI has support for PostRun to invoke after execution of a command.
https://github.com/spf13/cobra#prerun-and-postrun-hooks
How do I pass on the command status to PostRun call?
I have requirement of posting the command status after its execution to a server

A: Cleaner approach would be to leverage the Annotations provided in cobra command
package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    var rootCmd = &cobra.Command{
        Use:   "root [sub]",
        Short: "My root command",
        Run: func(cmd *cobra.Command, args []string) {
            // Do your processing here
            // Set the command annotations
            cmd.Annotations = make(map[string]string)
            cmd.Annotations["status"] = "status_goes_here"
            cmd.Annotations["error"] = "error_goes_here"
        },
        PostRun: func(cmd *cobra.Command, args []string) {
            // Retrieve the annotations
            fmt.Println(cmd.Annotations["status"])
            fmt.Println(cmd.Annotations["error"])
        },
    }

    rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
    rootCmd.Execute()
}

Really liked the approach @Bracken has taken here, Although there are some tweaks that will make it work
package main

import (
    "fmt"
    "errors"

    "github.com/spf13/cobra"
)

type wrapper struct {
    err error
}

// RunE fails to proceed further in case of error resulting in not executing PostRun actions
func (w *wrapper) Run(f func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) {
    return func(cmd *cobra.Command, args []string) {
        err := f(cmd, args)
        w.err = err
    }
}

func (w *wrapper) PostRun(f func(cmd *cobra.Command, args []string, cmdErr error)) func(cmd *cobra.Command, args []string) {
    return func(cmd *cobra.Command, args []string) {
        f(cmd, args, w.err)
    }
}

func main() {
    cmdWrap := wrapper{}
    var rootCmd = &cobra.Command{
        Use:   "root [sub]",
        Short: "My root command",
        Run: cmdWrap.Run(func(cmd *cobra.Command, args []string) error {
            return errors.New("i'm not in the book, you know")
        }),
        PostRun: cmdWrap.PostRun(func(cmd *cobra.Command, args []string, cmdErr error) {
            fmt.Printf("error was %v\n", cmdErr)
        }),
    }

    rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
    rootCmd.Execute()
}

----- Old Answer -----
If I understand it right, There is some status that needs to be passed from cmd.Execute to PostRun.
You can use ExecuteContext(ctx context.Context) method instead of Execute() and set whatever key-value needs to be set in context.
ctx := context.WithValue(context.Background(), "status", "statusValue")
rootCmd.ExecuteContext(ctx)

Same values can be Retrieved inside PostRun using cmd.Context()
PostRun: func(cmd *cobra.Command, args []string) {
   ctx := cmd.Context()
   status := ctx.Value("status")
}

A: I would wrap your Run (or RunE) function and your PostRun function using high order functions to catch errors or panics and then pass them into your PostRun:
package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

type wrapper struct {
    err error
}

func (w *wrapper) RunE(f func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {
    return func(cmd *cobra.Command, args []string) (err error) {
        defer func() {
            if r := recover(); r != nil {
                err = fmt.Errorf("panic: %v", r)
                w.err = err
            }
        }()
        err = f(cmd, args)
        w.err = err
        return
    }
}

func (w *wrapper) PostRun(f func(cmd *cobra.Command, args []string, cmdErr error)) func(cmd *cobra.Command, args []string) {
    return func(cmd *cobra.Command, args []string) {
        f(cmd, args, w.err)
    }
}

func main() {
    cmdWrap := wrapper{}
    var cmdFail = &cobra.Command{
        Use:   "fail",
        Short: "Doesn't work",
        RunE: cmdWrap.RunE(func(cmd *cobra.Command, args []string) error {
            panic("i'm not in the book, you know")
        }),
        PostRun: cmdWrap.PostRun(func(cmd *cobra.Command, args []string, cmdErr error) {
            fmt.Printf("error was %v\n", cmdErr)
        }),
    }

    var rootCmd = &cobra.Command{}
    rootCmd.AddCommand(cmdFail)
    rootCmd.Execute()
}


text:
Q: (Windows) Using ftello() returns incorrect file size for "some" binary files I use fseeko to move the file pointer to the file end first, then use ftello to get the binary file size. I refer to this page Do not use fseek... and follow exactly the same code in "Compliant Solution (POSIX ftello())" section.
My problem is this works fine for some binary file, but doesn't for some other binary files. I am now looking for a general way to access a binary file size.
fseeko(imageFile, 0, SEEK_END);
imageSize = ftello(imageFile);
fseeko(imageFile, 0, SEEK_SET);

I prefer to use stdio in C rather than any OS-based functions. Thanks!


text:
Q: PHP Website VIdeo Conferencing Integration In a PHP project, I need to implement feature of Video Conferencing.
I did google and found few options as below:

*

*http://openmeetings.apache.org/index.html

*http://codecanyon.net/item/video-chat/5492482
Also, i have read about HTML5 option, however i came to know that still only few browsers support that feature hence we also need to have flash as alternative.
Can anyone suggest me alternative? We are ready for open source as well as to purchase licence.
Please advice.
Thanks

A: Try VLine.
Its based on WebRTC protocol and I have used it in few projects, worked great.
Vline
Using this you can create Video chat rooms and one to one or one to many conference calls.

A: WebRTC is not currently supported by default PC browsers (Internet Explorer for Windows and Safari for Mac OS).
http://www.videochat-scripts.com/webrtc-videochat-and-conferencing-support/
To be able to provide service for all site users you should consider RTMP solutions.
For quick setup and testing you could try WordPress video conferencing plugins:
https://wordpress.org/plugins/search.php?type=term&q=video+conference


text:
Q: String preparation when calling stored procedure in Entity Framework Actually, I have code that uses Entity Framework 4.1 in Visual Studio 2010. Everything is working fine except for one thing : it doesn't seem to "prepare" the parameters like a good old [parameters.Add] habitually did.
Here's my code :
using (MyEnterprisesEntities dataContext = new
                             MyEnterprisesEntities(entityBuilder.ToString()))
{
         dataContext.CompanyInitializer(connection.Catalog,
                                        args.CompanyId,
                                        args.CompanyName);
}

So, if my company's name is O'Brian and sons (actually it passed before through a WCF web service so it's more in this form: O\'Brian and sons), it's seem to break my stored procedure (including the possibility of allowing SQL injection).
Is there a way to avoid this situation with EDMX or the old way is more reliable ?

A: You shouldn't not need to do anything prior to the call to your Stored Proc.
To help you, start the SQL Profiler to see what are the parameters sent to your database.
I ran some tests and if I'm using a parameter like O'Brian, the framework automatically double the quote in the query to SQL.


text:
Q: JPA/Hibernate, @OneToMany and constraints (Oracle) I have the following scenario:
@Entity
class A {

  @Id
  @GeneratedValue
  private long dbId;

  @OneToMany ( cascade = CascadeType.ALL )
  @JoinColumn( name = "A_ID", referencedColumnName = "DBID" )
  Set<C> setOfCs;

}

@Entity
class B {

  @Id
  @GeneratedValue
  private long dbId;

  @OneToMany ( cascade = CascadeType.ALL )
  @JoinColumn( name = "B_ID", referencedColumnName = "DBID" )
  Set<C> setOfCs;

}

@Entity
class C {

    @Id
@GeneratedValue
private long dbId;

}

Table C is created with two columns A_ID and B_ID as foreign keys to A.DBID and B.DBID respectively. This makes little sense in my case as each element of C is either linked from A or (xor) B but not both at the same time (both relationships are one-to-many not many-to-many).
Is there a way to have the same tables (which are fine) without the foreign key constraint on A_ID and B_ID? When I set A->C Oracle complains that C.B_ID is not set.
Thanks
Matteo

A: Why don't you use @JoinTable? it will remove any foreign key on table C.
@OneToMany(cascade = CascadeType.ALL,fetch=FetchType.LAZY,orphanRemoval=true)
@JoinTable(name = "A_B_TABLE", joinColumns = { @JoinColumn(name = "A_ID") },      inverseJoinColumns = { @JoinColumn(name = "DB_ID") })
public Set<C> getSetOfCs() {
    return setOfCs;
}

and by the way do not annotate  items, do it on its getters instead.

A: The only way i can think of to do this is to force both relationships through a common class, to which C can have a foreign key.
The simplest way to do this would be to introduce some class X which would be a superclass of A and B, and would have the dbId and setOfCs properties. C's table would then have a column X_ID.
Alternatively, make C abstract, and introduce subclasses Ca and Cb, such that instances of A always referred to instances of Ca, and instances of B to Cb. Each of Ca and Cb would only need a single foreign key. This might be very awkward to use, though; amongst other things, it would mean you could never transfer an instance of C from an A to a B.
If you weren't in a position to introduce any base classes, you could apply Wheeler's law and plaster on a layer of indirection, combining both the above approaches. Create an abstract class X, and give it the dbId and setOfCs properties from A and B; C then has a phantom ManyToOne relationship to X, and it table has the corresponding foreign key. Create two concrete subclasses of X, Xa and Xb, each having a OneToOne relationship with an instance of A or B respectively, those instances of A and B having corresponding OneToOne relationships pointing in the other direction.


text:
Q: What functions does WordPress use for filtering / sanitizing comments? We have some custom built comments (ones tied to custom post types, that we can't integrate with WP's comment system). But we want to filter the comments when they are submitted the way WP does and also save them to the DB the way WP does so everything is filtered (not really for spam), basically sanitized for security purposes but also if we get the pretty  tags and emoticons that WP will do. We need this to be safe for front end and backend. As I was able to put in  tags and have tested with SQL injections and also want to make sure that it doesnt get all the wierd \n \r\n garbage.

A: You can use wp_filter_kses() and then wp_unslash to filter the content.


text:
Q: is there a way to get SQL Server 2008 available servers without using SMO  DataTable dataTable = SmoApplication.EnumAvailableSqlServers(false);
 comboBox1.ValueMember = "Name";
 comboBox1.DataSource = dataTable;

I'm using the above code to populate a comboBox with available SQL Servers but this requires me to reference Microsoft.SqlServer.Management.Smo in my project.
Is there away i can display available SQL Server 2008 Servers in a comboBox with out using Microsoft.SqlServer.Management.Smo?

A: SqlDataSourceEnumerator.Instance.GetDataSources().
There used to be an issue that it did not always find all Sql Server instances on a server. I'm not sure if that is still the case.


text:
Q: JFrame Wont Show Up I know this has been asked on other threads, but I can't see what the problem with my code is. My JPanels aren't showing up in my JFrame. Please assist.
This is for a introductory level computer science school assignment, so some otherwise stupid things are outside my control.
Thanks.
package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class DequeueView {

    //main JFrame
    private JFrame mainFrame ;

    //Containers
    private JPanel display;
    private JPanel buttons;

    //Buttons
    private JButton addFront;
    private JButton dequeue;
    private JButton enqueue;
    private JButton removeRear;

    //Textbox and label
    private JTextField displayQueue;
    private JLabel greeting;

    /**
     * Constructor for the main application with the title bar set to
     * a title.
     */
    public DequeueView(){

        /*
         * The hierarchy is as follows:
         *
         * Container JPanel-    to display the message "Hello" and to display queue.
         *      Label , textbox
         * Container JPanel-    to put the buttons.
         *      JButtons
         */

        JPanelDisplayHelper();      //formats the displays.
        JPanelButtonHelper();       //formats the buttons.
        JFrameHelper();             //formats the JFrame.

    }

    /**
     * Sets up the JFrame that will house the 4 buttons.
     */
    private void JPanelButtonHelper(){

        addFront = new JButton("Add to Front");
        dequeue = new JButton("Take from Front");
        enqueue = new JButton("Add to Back");
        removeRear = new JButton("Take from Back");

        buttons = new JPanel();
        buttons.add(addFront);
        buttons.add(dequeue);
        buttons.add(enqueue);
        buttons.add(removeRear);
    }

    /**
     * Sets up the JFrame that will house everything.
     */
    private void JFrameHelper(){

        String title = new String ("Queue Application");

        mainFrame = new JFrame();
        mainFrame.setLocation(200,150);
        mainFrame.setSize(500, 500);
        mainFrame.setResizable(false);
        mainFrame.setTitle(title);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        mainFrame.add(display);
        mainFrame.add(buttons);
        mainFrame.setLayout(new BorderLayout());
        mainFrame.setVisible(true);

    }

    /**
     * Sets up the JPanel that will display the greeting and the queue in
     * String form.
     */
    private void JPanelDisplayHelper(){

        String text = new String("Hello, this app displays a queue. Enjoy!");

        //formats the label
        greeting = new JLabel(text, JLabel.LEFT);
        greeting.setVisible(true);

        //formats the JTextField.
        displayQueue = new JTextField(10);
        displayQueue.setText("Your Queue will display here!");
        displayQueue.setBackground(Color.WHITE);
        displayQueue.setEditable(false);
        displayQueue.setVisible(true);
        displayQueue.validate();

        display = new JPanel();
        display.add(greeting);
        display.add(displayQueue);
        display.setLayout(new BorderLayout());

    }

}

A: Have you instanciated the class in your main method like this? It does not know about it in the main method for your program unless you actually define it
public static void main(String[] args) {
    new DequeueView();
}

PS: you can add the title parameter inside the JFrame frame = new JFrame("title")


text:
Q: New job triggers not working as intended on a looped trigger I'm currently trying to setup a script to uninstall Chrome from PCs to upload onto Intune but following the MS documentation on the parameters of new job triggers just pops up with errors on invalid times. I'll paste below the documentation I'm using to get the parameters, not sure where to go in terms of resolving the error
https://learn.microsoft.com/en-us/powershell/module/psscheduledjob/new-jobtrigger?view=powershell-5.1
Register-ScheduledJob -Trigger $Trigger -RunAs32 -ScriptBlock {

$SEARCH = 'chrome$'
$INSTALLED = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  Select-Object DisplayName, UninstallString
$INSTALLED += Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, UninstallString
$RESULT = $INSTALLED | ?{ $_.DisplayName -ne $null } | Where-Object {$_.DisplayName -match $SEARCH }
if ($RESULT.uninstallstring -like "msiexec*") {
$ARGS=(($RESULT.UninstallString -split ' ')[1] -replace '/I','/X ') + ' /q'
Start-Process msiexec.exe -ArgumentList $ARGS -Wait
} else {
$UNINSTALL_COMMAND=(($RESULT.UninstallString -split '\"')[1])
$UNINSTALL_ARGS=(($RESULT.UninstallString -split '\"')[2]) + ' --force-uninstall'
Start-Process $UNINSTALL_COMMAND -ArgumentList $UNINSTALL_ARGS -Wait
}

} -Name RemoveChrome```


text:
Q: OpenVPN Access Server connects and can browse all other ports than port HTTP and HTTPS Hello dear Serverfault experts,
I have a very frustrating issue with my recently installed OpenVPN Access Server (https://openvpn.net/index.php/access-server/download-openvpn-as-sw/113.html?osfamily=CentOS CentOS 6.5)
Everything works, except I can't browse port 80 or port 443.
I can do NSLOOKUP, traceroutes, pings, visit websites that use other ports in the address bar (For instance www.example.com:2087), Skype connects just fine, and so forth. The only thing that doesn't work, is when I want to browse a website on regular port, like www.google.com.
The OpenVPN server is installed on a node hosted by OVH in Canada. It has multiple IPs (Public IPs), 1 Canadian IP and 2 US. It's currently setup to listen and serve on one of the US IPs. I have tried the Canadian IP as well, same result.
Let me know what more information you'd require and I'll reply as quick as possible.
Thank you in advance!
EDIT:

Here is the result of the Telnet using Putty:
  puu.sh/bvMON/2ce15e6735.png 2) This should determine if we are using
  IPv4 or IPv6, right? puu.sh/bvMSf/1241ddf1c4.png
  puu.sh/bvMUU/13fa10c86f.png Both internet connection of client and
  server use IPv4 to connect to each other in the OpenVPN client
  settings as well. - Added from comment

EDIT 2:
Server is CentOS 6.5 and client is Windows.
EDIT 3:
Here is a "netstat -n" command used while VPN is turned on: http://pastebin.com/iet3ErVX
Please note the "<--- comments"
Kind regards,
Thomas Schmidt

A: SOLVED:
I had these in my iptables:
# COMMENTED OUT TO SUPPORT OPENVPN
#-A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8880
#-A PREROUTING -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 8881


text:
Q: TableLayout Tweak. Is it possible? I have a table layout with five columns and many rows with dynamic content.
We notice that each column takes the width of the maximum of all cells of that column.
I do not want horizontal scrolling but I want to detect when the total width has been exceeded so I can remove one of the columns.
Is this possible?

A: You could call measure() on the TableLayout yourself and check the result with getMeasuredWidth/Height.

A: If you are adding each row in a loop, then I guess you could do something like:
int longestRowWidth = 0;

for(i=0; i<6; i++)
{

    // Add your row here

    // Get the width of your new row here
    int rowWidth = blablah

    // Check if it exceeds longestRowWidth
    if(rowWidth > longestRowWidth)
    {
        // Do your stuff here.
    }
}


text:
Q: Iterate through Map in HTML I am trying to iterate through a Map object in HTML using for loop.
{%for s in objects%}
   {{s}}
{%endfor%}

The object is a Map (i.e. {a: b, c: d, e: f})
When I run this code, {{s}} will give me the value of the the object (i.e. b, d, f).
How do I get the Key of this object?

A: Is this written in a templating engine? I think it looks like Nunjucks code.T
This is from the Nunjucks homepage

  {% for name, item in items %}

{{ name }}: {{ item }}

  {% endfor %}


text:
Q: Java Throws ExecutionException in a loop after several successful thread executions I'm having trouble with the callable thread.
Here is code snipet:
ExecutorService service = Executors.newFixedThreadPool(1);
for(int i =0; i<30;i++){
    Future<MyClass> task = service.submit( new MyThread(parameter1, parameter2));
    try{
        result = task.get();
    }
    catch(InterruptedException ex){
        System.out.println("Interruped!");
    }
    catch(ExecutionException ex){
        System.out.println("Execution ExceptioN!");
    }
}
service.shutdownNow();

The code above would correctly executes 18 times and then throw the ExecutionException after the 18th time.
What am I doing wrong?
Thanks!

A: ExecutionException documentation states:
Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.
So your task is throwing an exception.  Call getCause on the ExecutionException to view that exception.


text:
Q: Searching or a specific substring in a file This question is possibly a duplicate but any answers i find don't seem to work. I have a .txt file full of this layout:
artist - song, www.link.com
artist2 - song2, www.link2.com
This is my general purpose:
uinput = input("input here: ")

save = open("save.txt", "w+")
ncount = save.count("\n")

for i in range(0, ncount):
    t = save.readline()
    if uinput in t:
        print("Your string " uinput, " was found in" end = "")
        print(t)

My intention is: If the userinput word was found in a line then print the entire line or the link.

A: *

*You want to read the file, but you are opening the file in write mode. You should use r, not w+

*The simplest way to iterate over a file is to have a for loop iterating directly over the file object

*Not an error but a nitpick. You do not close your file. You can remedy this with with.. as context manager

uinput = input("input here: ")

with open("save.txt", "r") as f:
    for line in f:
        if uinput in line:
            print('Match found')

A: You can use list-comprehension to read the file and get only the lines that contain the word, for example:
with open('save.txt', 'r') as f:
    uinput = input("input here: ")
    found = [line.rstrip() for line in f if uinput.lower() in line.lower()]
    if found:
        print('Found in these lines: ')
        print('\n'.join(found))
    else:
        print('Not found.')

If you want to print the link only, you can use:
found = [line.rstrip().split(',')[1] for line in f if uinput.lower() in line.lower()]

A: You can use list comprehension to fetch the lines containing  user input words.
use below code:
try:
    f = open("file/toyourpath/filename.txt", "r")
    data_input = raw_input("Enter your listed song from file :");
    print data_input
    fetch_line = [line for line in f if data_input in line]
    print fetch_line
    f.close()
except ValueError, e:
    print e


text:
Q: ami_block_device_mappings not working properly with packer I am using packer to create AMI adding 2 block devices, 1 root and another ebs attached to it. The block device mapping is not attaching the ebs block to the ami or temporary instance created.
My code block looks like (only details with block device mapping added):
"builders": [
    {
      "type": "amazon-ebs",
       "ami_block_device_mappings":[{
        "device_name":"/dev/xvda",
        "volume_size":8,
        "volume_type":"gp2",
        "encrypted":false,
        "delete_on_termination":true
       },
       {
        "device_name":"/dev/sdb",
        "volume_size":50,
        "volume_type":"gp2",
        "encrypted":true,
        "delete_on_termination":true
       }]
     }],
      "provisioners": [
    {
        "type" : "shell",
        "inline" : [
            "sleep 30",
            "sudo yum update -y",
            "sudo yum-config-manager --enable epel",
            "sudo yum install ansible -y",
            "sleep 30",
            "sudo fdisk -l"
        ]
    }
  ]

fdisk -l shows that only 1 block added
 amazon-ebs: Disk /dev/xvda: 8589 MB, 8589934592 bytes, 16777216 sectors
    amazon-ebs: #         Start          End    Size  Type            Name
    amazon-ebs: 1         4096     16777182      8G  Linux filesyste Linux
    amazon-ebs: 128         2048         4095      1M  BIOS boot parti BIOS Boot Partition

I am not sure why this would be happening? Any help on this?
Thanks and Regards,
Jay

A: I think you are looking for launch_block_device_mappings.


text:
Q: Jquery click, show and hide function please help me with my snippet.. I have this code and I don't know what is wrong.. This is my code

<form id="krishna">
    <input type="text" readonly value="krishna" >

    <button id="next">Next</button>
</form>
<form id="radha">
    <input type="text" readonly value="radha" >

    <button id="prev">Previous</button>
</form>

When I click next It seems does not go to the next form.. thank you all.

A: This may be due to some missing attibutes of your form
HTML
<form id="krishna">
    <input type="text" readonly value="krishna" />

    <button type='button' id="next">Next</button>
</form>
<form id="radha">
    <input type="text" readonly value="radha" />

    <button type='button' id="prev">Previous</button>
</form>

Script
$(document).ready(function () {
    $("#radha").hide();

    $("#next").click(function () {
        $("#radha").show();
        $("#krishna").hide();
    });

    $("#prev").click(function () {
        $("#radha").hide();
        $("#krishna").show();
    });
});

check here

A: You need to prevent the default action, which is the form submit. When you prevent the default action from happening, you will see the desired result
Check this fiddle
$(document).ready(function () {
    $("#radha").hide();

    $("#next").click(function (e) {
        e.preventDefault();
        $("#radha").show();
        $("#krishna").hide();
    });

    $("#prev").click(function (e) {
        e.preventDefault();
        $("#radha").hide();
        $("#krishna").show();
    });
});

P.S  I am not sure why you are still using jquery 1.3.x.
Also, check the fiddle for the updated HTML

A: This is how I did it.
http://jsfiddle.net/GnzWZ/2/
$('form button').click(function(e){
    $("#radha, #krishna").toggle();
    return false;
});

Notes:

*

*return false is the jquery solutions for preventdefault.

*You can simplify your selectors and optimize your code a little more.

*Avoid making style changes that should be originally made in CSS.

A: Because it is trying to submit the form. So you need to make that button type to button. It is "submit" by default in a form.
JSFidle Demo
<form id="krishna">
<input type="text" readonly value="krishna" >

<button type="button" id="next">Next</button>
</form>
<form id="radha">
<input type="text" readonly value="radha" >

<button type="button" id="prev">Previous</button>
</form>

A: Your code is fine but What is happening here that your submit button required post request. So you can prevent this behavior by e.preventDefault() function of jquery. I have updated the jquery code as below.
    $(document).ready(function(e) {
$("#radha").hide();

$("#next").click(function(e){
    e.preventDefault();
$("#radha").show();
$("#krishna").hide();
});

$("#prev").click(function(e){
            e.preventDefault();
$("#radha").hide();
$("#krishna").show();
});

});
visit the following link to get demo on jsfiddle :
http://jsfiddle.net/4N95Q/

A:

    <input type="text" readonly value="krishna" >

    <button id="next">Next</button>

    <input type="text" readonly value="radha" >

    <button id="prev">Previous</button>

Working fine if you change

form

in the

div


text:
Q: Stop bootstrap-select dropdown menu from moving other controls I have a form that looks like the following when closed and when opened:

The save button is moving.  I've replicated the problem in http://jsfiddle.net/m06eob4h/1/ with following markup.
I'm using snapappointments.com/bootstrap-select (without any custom styling) and bootstrap 4.  Here is what I think the relevant rendered markup looks like:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Plan 1 Status

              Election Status

                <select name="iAuthStatus1" id="iAuthStatus1" class="form-control selectpicker show-tick iAuthStatus1">
                  <option value=""></option>
                  <option value="Pend">Pending Review</option>
                  <option value="Rev">In Review</option>
                  <option value="Wa">Waiting</option>
                  <option value="Com">Package Complete</option>
                  <option value="DECL">Decline</option>
                  <option value="INC">Incomplete</option>
                  <option value="Inelig">Ineligible</option>
                </select>

Plan 1 Status

              Election Status

                <select name="iAuthStatus1" id="iAuthStatus1" class="form-control selectpicker show-tick iAuthStatus1">
                  <option value=""></option>
                  <option value="Pend">Pending Review</option>
                  <option value="Rev">In Review</option>
                  <option value="Wa">Waiting</option>
                  <option value="Com">Package Complete</option>
                  <option value="DECL">Decline</option>
                  <option value="INC">Incomplete</option>
                  <option value="Inelig">Ineligible</option>
                </select>

Save

Anyway, you'll see that my fiddle has two issues when I expand the dropdown in the first card.
1) The Save button moves down.
2) The second card moves around.
UPDATE - I've modified the html to have two cards (more like our real app) and the associated fiddle.

A: I see a typo in your HTML (6th line):

                      ^
                      X

shouldn't it be

maybe thats causing this issue
Edit So this code works on my machines (did a quick test on win/MacOS with FF74 and Chrome > 79) as it should

Plan 1 Status

                      Election Status

                        <select name="ControlHost:ParticipantTab-Paper-Elections-Document-Status:iAuthStatus1:iAuthStatus1" id="ControlHost_ParticipantTab-Paper-Elections-Document-Status_iAuthStatus1_iAuthStatus1" class="form-control selectpicker show-tick iAuthStatus1" data-size="15" data-live-search="true" tabindex="-98">
                          <option value=""></option>
                          <option value="Pend">Pending Review</option>
                          <option value="Rev">In Review</option>
                          <option value="Wa">Waiting</option>
                          <option value="Com">Package Complete</option>
                          <option value="DECL">Decline</option>
                          <option value="INC">Incomplete</option>
                          <option value="Inelig">Ineligible</option>
                        </select>

      Save

So I placed the button inside the card - works (commented div). If you put the save button out of the card but inside the card-column than it moves around like drunk when changing screen sizes This solution puts it out of the card column in an extra row (which you could also skip) - that works too like expected:

Plan 1 Status

                      Election Status

                        <select name="ControlHost:ParticipantTab-Paper-Elections-Document-Status:iAuthStatus1:iAuthStatus1" id="ControlHost_ParticipantTab-Paper-Elections-Document-Status_iAuthStatus1_iAuthStatus1" class="form-control selectpicker show-tick iAuthStatus1" data-size="15" data-live-search="true" tabindex="-98">
                          <option value=""></option>
                          <option value="Pend">Pending Review</option>
                          <option value="Rev">In Review</option>
                          <option value="Wa">Waiting</option>
                          <option value="Com">Package Complete</option>
                          <option value="DECL">Decline</option>
                          <option value="INC">Incomplete</option>
                          <option value="Inelig">Ineligible</option>
                        </select>

      Save


text:
Q: Is Codeigniter Datamapper other_field must append _id automatically? I have a problem with Codeigniter Datamapper when Joining table. I have 2 table:
Purchase
purchase_id, ref ...

Stock
stock_id, purchase_ref...

I created a has_many relation :
For purchase:
 public $has_many = array(
            'stock' => array(
                'join_table' => 'stocks',
                'other_field' => 'purchase_ref',
                'cascade_delete' => TRUE
            )
    );

For stock:
public $has_one = array(
            'purchase'=>array(
                'join_other_as' => 'purchase_ref',
                'join_table' => 'purchases',
                'cascade_delete' => FALSE
            )
    );

But datamapper seems append _id to the column that I wanna join and it be comes purchase_ref_id
and the sql statement becomes something like:
...LEFT OUTER JOIN "stocks" stocks ON "purchases"."id" = "stocks"."purchase_ref_id"...

Is that anyway to avoid appending _id when joining table in datamapper? thx a lot.

A: This is a hard coded behaviour (for example here, but in many places in the code) and you can't change it with the current version. I'm afraid you would either have to patch the library's code or change your db schema.


text:
Q: List of symbols and units under an equation I have many equations in my report and want to add a list (like the one shown below) below all of my equations (not a separate nomenclature list at the end). Kind of like a mini-nomenclature. Also would be nice if the units ended at the same point.

Is there anyway to do this? Any help very much appreciated.

A: Maybe a tabular could help?
\documentclass{article}

\usepackage{tabularx}

\begin{document}

text
%
\[
  A+B=1
\]
\begin{tabularx}{\textwidth}{lXr}
A & this & m/s\\
B & that & s\\
\end{tabularx}

text
\end{document}


text:
Q: java - register parent JPanel to MouseEvent Consider I have the following code:
public LSUIEditingPanel(LSView view) {
    super();
    parent     = view;
    controller = view.getController();

    LayoutManager overlay = new OverlayLayout(this);

    setLayout(overlay);
    scribbleArea = new LSScribblePanel();
    scribbleArea.setOpaque(false);
    add(scribbleArea);
    viewArea = new LSCanvasViewport(view);
    add(viewArea);
    setAutoscrolls(true);
    drawListener = new SVGEditorDrawMouseAdaptor();

}

where scribbleArea and viewArea are both a custom JPanel. They are both subpanels added to the main panel.
Now I want do make it such that I can register a MouseEvent to the parent panel itself, which is I could do a panning of the panel as the parent panel will be embed in a JScrollPane after instantiating.
This is the code segment performing the dragging:
public class LSPanMouseAdapter extends MouseAdapter {

/**
 * Panning pivot point
 */
private final Point panPoint = new Point();

/**
 * {@inheritDoc}

 * Set pan starting point to be the point where the mouse currently located, and change the
 * current cursor to HAND_CURSOR.
 */
@Override
public void mousePressed(MouseEvent event) {
    JViewport  viewport  = (JViewport) event.getSource();
    JComponent component = (JComponent) viewport.getView();

    panPoint.setLocation(event.getPoint());
    component.setCursor(new Cursor(Cursor.HAND_CURSOR));
}

/**
 * {@inheritDoc}

 * Reset cursor to DEFAULT_CURSOR.
 */
@Override
public void mouseReleased(MouseEvent event) {
    JViewport  viewport  = (JViewport) event.getSource();
    JComponent component = (JComponent) viewport.getView();

    component.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}

/**
 * {@inheritDoc}

 * Get the current viewport of the canvas and move the viewable area respective to the
 * event cursor location.
 */
@Override
public void mouseDragged(MouseEvent event) {
    JViewport  viewport     = (JViewport) event.getSource();
    JComponent component    = (JComponent) viewport.getView();
    Point      currentPoint = event.getPoint();
    Point      viewPoint    = viewport.getViewPosition();

    viewPoint.translate(panPoint.x - currentPoint.x, panPoint.y - currentPoint.y);
    component.scrollRectToVisible(new Rectangle(viewPoint, viewport.getSize()));
    panPoint.setLocation(currentPoint);
}
}

I have tried registering the event but the parent panel does not fire the event, any suggestion on how should I do this?

A: See this example below which shows how you can have some kind of view port drag. The mouse listener is attached to the viewport view and modifies the viewport position as the mouse is dragged. In order to compute proper "offset" of the mouse, mouse locations are converted into viewport coordinates as the mouse is dragged.
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestDragViewPortView {
    public static class MouseDragger extends MouseAdapter {
        private Point startPoint;
        private Component draggedObject;
        private JViewport viewport;

        @Override
        public void mousePressed(MouseEvent e) {
            draggedObject = (Component) e.getSource();
            viewport = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, draggedObject);
            if (viewport != null) {
                startPoint = SwingUtilities.convertPoint(draggedObject, e.getPoint(), viewport);
                draggedObject.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            }
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (viewport == null) {
                return;
            }
            Point location = SwingUtilities.convertPoint(draggedObject, e.getPoint(), viewport);
            Point newPosition = viewport.getViewPosition();
            newPosition.translate(startPoint.x - location.x, startPoint.y - location.y);
            newPosition.x = Math.min(newPosition.x, draggedObject.getWidth() - viewport.getExtentSize().width);
            newPosition.y = Math.min(newPosition.y, draggedObject.getHeight() - viewport.getExtentSize().height);
            newPosition.x = Math.max(newPosition.x, 0);
            newPosition.y = Math.max(newPosition.y, 0);
            viewport.setViewPosition(newPosition);
            startPoint = location;
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            draggedObject.setCursor(Cursor.getDefaultCursor());
            startPoint = null;
            draggedObject = null;
            viewport = null;
        }

        public void makeDraggable(Component component) {
            component.addMouseListener(this);
            component.addMouseMotionListener(this);
        }

    }

    private JFrame frame;

    protected void initUI() throws MalformedURLException {
        frame = new JFrame(TestDragViewPortView.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel background = new JLabel(new ImageIcon(new URL("http://blogs.dirteam.com/photos/sanderberkouwer/images/2157/original.aspx")));
        JScrollPane scrollPane = new JScrollPane(background);
        new MouseDragger().makeDraggable(background);
        frame.add(scrollPane);
        frame.pack();
        frame.setSize(frame.getWidth() / 2, frame.getHeight() / 2);
        frame.setVisible(true);
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new TestDragViewPortView().initUI();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}


text:
Q: how to upgrade android sdk version by command line i am new to Android development and i want to upgrade my android sdk version from 32.1.0-rc1 to 33.0.0-rc2.
And i have another question what is the difference between compileSdkVersion and targetSdkVersion on the file build.gradle on flutter ?

A: For update sdk by command LINE, see this gist:
https://gist.github.com/srayhunter/4bce340b62109b5bae43
sdkmanager "build-tools;30.0.2" "platforms;
About the difference ...
The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API.
And the targetSdkVersion indicate that you have tested your app on the version you specify.


text:
Q: Choosing an NLog target based on global log level I'm trying to log to a file using NLog based on a globally-set log level.  I'm unsure if this is possible from everything I can dig up.
Essentially, I want to have a global setting in my appconfig.json that has the log level.  Default would be Debug, but Trace would be another option.  If I select Debug, I want to log everything from Debug up to Fatal in a file called log-debug.txt.  This seems pretty reasonable; it's the base tutorial case from what I can tell, and I've made that work.
Here's the other thing, though: if I set the global log level to Trace, I want everything from Trace on up to log to log-trace.txt.  My initial thought was to add a new config rule, so I added the second one in the rules collection, but from everything I've read that would end up with the debug messages in one file and the trace messages in another.
The purpose of this is extreme-case debugging (i.e., user doesn't have any idea how they got to that state, so flip the setting from "Debug" to "Trace", play with it again, and when you hit the bug send me the log-trace.txt), so splitting the debug and trace messages into different files would defeat the purpose.
How would I go about doing this?
This is a WPF app, so I'm setting the global level by using this in app.xaml.cs:
serviceCollection.AddLogging(builder =>
{
    builder.ClearProviders();

    // Haven't written the code to pull it from the config file yet, but this is how
    // I would set it.
    builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
    builder.AddNLog();
});

appconfig.json
{
  "settings": {
    "logLevel": "Debug"
  },
  "NLog": {
    "internalLogLevel": "Info",
    "autoReload": true,
    "targets": {
      "logfile-debug": {
        "type": "File",
        "fileName": "log-debug.txt",
        "layout": "${longdate}|${level}|${message}|${exception:format=tostring}"
      },
      "logfile-trace": {
        "type": "File",
        "fileName": "log-trace.txt",
        "layout": "${longdate}|${level}|${message}|${exception:format=tostring}",
      },
      "logconsole": {
        "type": "Debugger",
        "layout": "${longdate}|${level}|${message}|${exception:format=tostring}"
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Debug",
        "writeTo": "logfile-debug,logconsole"
      },
      {
        "logger": "*",
        "minLevel": "Trace",
        "writeTo": "logfile-trace,logconsole"
      }
    ]
  }
}

A: You can do this:
void EnableGlobalTrace(bool enable)
{
   NLog.GlobalDiagnosticsContext.Set("GlobalTraceLevel", enable ? "Trace" : "Off");
   NLog.LogManager.ReconfigureExistingLoggers();
}

And have the rules like this:
    "rules": [
      {
        "logger": "*",
        "minLevel": "Debug",
        "writeTo": "logfile-debug,logconsole"
      },
      {
        "logger": "*",
        "minLevel": "${gdc:GlobalTraceLevel:whenEmpty=Off}",
        "writeTo": "logfile-trace"
      }
    ]

See also: https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules
See also: https://github.com/NLog/NLog/wiki/Environment-specific-NLog-Logging-Configuration


text:
Q: Dropping Packets By IP With C++ I'm writing a program in C++ that sniffs packets and compares them to a table by IP address.  I would ike to know how to "Drop A Packet" if it does not meet the criteria that I setup.  Everything is done, the sniffer, the criteria.  I just need to know how to drop the packet...
Windows 7, Visual Studio 2010.

A: In general, packet sniffers don't modify the underlying stream, they just observe it.
It sound like what you really want is some sort of transparent proxy.
However, you should post some sample code or more details on what you are doing, since we have no idea how you actually implemented anything, and thus can't offer any suggestions.


text:
Q: Not been able to use Shift + 6 on Wine I've been having a problem running a game through wine (starcraft 2), when i need to add units to an existing control group i press shift + 6 in game,this doesn't seems to have any output at all, i've tried to check with the ingame chat, but the normal output should be "^" but there's nothing.
I'm using the English, int with dead keys as my layout.

A: To get a caret symbol with dead keys, press space after the caret.
"Dead keys" means that some keys don't work normally. Instead, they're used to modify other characters. For example, ^ followed by O produces ô.
You may wish to use another layout like English (US, alternative international) (which I believe uses AltGr+6 followed by O for ô) if you need international characters or English (US) if you don't.