text:
Q: capacitor placement I would like to know is there any standard on placing capacitor on a pcb board. For example, in front of a power supply 3.3V, I put 100p, 10n, 10u, and 1n. How should I put it in the correct order from the nearest to the furthest from the specified pin. Is there any standard in this kind of placement. If possible can you attach a source to further increase my knowledge. I myself put it in order of 100p,1n,10n,and the furthest is 10u, however I do not really know whether this is correct or not. Thank you for your help.
Best regards,
RH

A:
How should I put it in the correct order from the nearest to the furthest from the specified pin.

Generally you should put the lowest valued part, which you expect to provide the highest-frequency currents, closest to the chip. This minimizes the parasitic inductance between the chip and the capacitor, giving it the best chance to work at high frequencies.

I put 100p, 10n, 10u, and 1n.

I suspect that the 10 nF and 100 pF parts are counterproductive here. By pushing the higher valued parts farther away from the chip, they are degrading their performance, but they don't "store" enough charge to provide meaningful current for many loads. In particular I'll suggest very strongly if the chip being bypassed is a digital device, you'd be better off getting rid of the lower valued capacitors and moving the higher valued capacitors closer.
Of course every application is different. In an analog application you might have a very good idea of what frequency band the IC will draw currents in and a low-valued cap might be a better choice.
You should also be aware that capacitors in parallel with values separated by more than about one decade (i.e. the larger part is more than 10x the value of the smaller part) have a good chance of producing an anti-resonant (or parallel resonance) behavior where the impedance is very high at some frequency between the series resonant frequencies of the two parts. This is discussed in detail in section 3.5 of Murata's Application Manual for Power Supply Noise Suppression and Decoupling for Digital ICs
See also: Will a 0402 0.01 µF ceramic capacitor next to a 0402 0.1 µF ceramic capacitor have any power decoupling benefits?

A: I've seen a lot of my fellow students and friend that are into electronics struggle with this, so I decided to type out a quite lengthy response - I hope people looking for similar information might find help in this.
We need to start with an understanding of what the decoupling capacitor is actually used for in the first place - many people will say that it is to filter out noise from other components. This is not the main/only reason, especially in digital circuits! If we have say a CMOS circuit, we will find that most of the current draw happens in very brief spikes on the clock. If we have no decoupling, this current will have to flow through the trace coming from the powersupply. This trace has a resistance R and inductance L. I have a schematic down lower where you can see these. When you have a sudden spike of current through this combination, we will have a large voltage drop over this trace, causing issues ranging from noise on mixed signal circuits, jitter on clocks, to complete failure of the device requiring a reset.
By placing a capacitor close to the pin, we have a local source of current during these spikes. On average, the capacitor will be charged from the powersupply. During the short current spikes, the capacitor will discharge, providing the current needed while doing so.
Now, on to the question:
It is a very common mistake to think that it's only the capacitance value that matters. The key is the combination of Equivalent Series Inductance (ESL) and capacitance. The equivalent schematic used in this post is the following:

In this schematic, C is the rated capacitance. ESL is the equivalent inductance. This depends on the capacitor design, size, and type.
We often see something like this on our schematic:

When we place this on the pcb, it looks like this:

But when we look at the main non-idealities, the picture becomes more complex. We first need to replace our ideal capacitor with the circuit including the ESL. On top of that, we need to include the trace resistance and inductances. Our simple schematic is now:

Using a smaller capacitor with the same ESL closer to the part makes (almost - see (1)) no difference - in fact, it's performance might be worse! The reason we often want to use smaller capacitance values closer to the chip has to do with the fact that - in general - the ESL/ESR of these parts is lower (usually, we use smaller packages, as for a given family, these always have lower ESL).
The closer you can get it to the pin, the better, since the trace towards the pin also forms inductance and has a resistance. Note that it is not just the positive trace that matters - it is the inductance of the entire loop that matters - including the ground connection.
This Intersil appnote is a very good starting resource for more in depth information and figures. All figures that follow in this post are from this appnote.
http://www.intersil.com/content/dam/Intersil/documents/an13/an1325.pdf
If we factor in the impedance of a ideal capacitor, we know the impedance as a function of frequency has a \$\frac{1}{f}\$ behaviour - as we increase the frequency, the impedance decreases, and thus we get better filtering.
However, every actual capacitor also has an ESL. If we include this ESL, and we look at the impedance of the capacitor as a function of frequency, we get the following picture:

Source: Tamara Schmitz, Mike Wong, Intersil Application Note 1325: Choosing and Using Bypass Capacitors
So, what happens if we now get more capacitors? Let's say we choose a 1uF, 0.1uF and 0.01uF capacitor, in an 0805 formfactor. If we now put them together, we get the following plot:

Source: Tamara Schmitz, Mike Wong, Intersil Application Note 1325: Choosing and Using Bypass Capacitors
What we see is that even though we added smaller capacitors, we don't really get any significant benefit - the inductance causes our impedance to go up, removing all benefit of the smaller capacitors.
What we should have done is use 3 different packages, say, 0805, 0603 and 0402. This would have given us the following figure:

Source: Tamara Schmitz, Mike Wong, Intersil Application Note 1325: Choosing and Using Bypass Capacitors
(1)Ofcourse, since it's closer to the part there will be less trace inductance and resistance, but you might as well just put the bigger capacitance part closer, eliminating this difference

A: Silicon circuits only work at speed, because of the ONCHIP stored energy.
An MCU may have 1nF or 2nF or 100nF onchip, mostly in well_substrate capacitors; wells exist under every Pchannel FET in standard processes; the distributed nature, usually in tiny rectangles, of these wells, along with the even smaller "contacts" into the well and nearby "contacts" into that substrate underlying the well, lead to substantial resistance for charge to flow in and out of the well_sub capacitor.
But you have a well under every Pch FET, thus a well is needed in every inverter, bigger well in every gate, even bigger well in every FlipFLop, on and on. With capacitance and resistance and as "joren vaes" illustrated, the always present inductance.
With 100,000 of these tiny (2u by 5u, for example) capacitors all over the silicon, there is lots of capacitance because the Cs add up. The Rs reduce, because in parallel. And the inductances reduce, because in parallel.
It gets even better. All those gates and FFs, with lots of tiny FET gate oxide capacitors, also store change in gate-capacitors; any gateC that is not changing state is usefully storing charge, to be used by the sibling transistors just 1micron away, or 10microns away.
And there is some metal-metal capacitance, if VDD is atop GND metal.
All three --- well_substrate caps, gate_oxide_caps, metal_metal caps ---- are in parallel. Perhaps 0.1uF (100,000 picoFarad).
Then the MCU clocks, and 100,000 gates simultaneously demand charge, and as the Pch and Nch transistors switch oppositely there is the crossover time when both transistors are ON for say oh hmmm 20picoseconds. Passing 20uA for 20pS. Not all 1,000,000 gates, but just 100,000 gates this time. What does that do to the onchip stored charge.
Assuming Q = I * T = 20uA for 20pS, Q = 400 e-18 coulombs, scaled up by 100,000 gates. Equals 400-13 or 40 picoCoulombs. To be supplied ONCHIP. In 20pS. What happens?


text:
Q: How to Hide the TabPager Layout with Animation im tryin to hid my Tabs layous with an animation, here i provided a code, but it only works on the titles of the Tabs, so im Forced to Hide the Tab manually, is there Any way that I Can Hide the Tabs Layout With Animation?
        tabs.setOnPageChangeListener(new OnPageChangeListener() {

        public void onPageScrollStateChanged(int state) {}

        @Override
        public void onPageScrolled(int position, float positionOffset,
                int positionOffsetPixels) {
            if(position == 3){
                System.out.println("position:"+position);
                if(badge2!=null){
                    badge2.setVisibility(View.GONE);
                    badge2.invalidate();
                    badge2=null;
                }
                TranslateAnimation anim = new
  TranslateAnimation(0, 0, 0,-100);
                anim.setInterpolator(new BounceInterpolator());
                anim.setDuration(1000);
                tabAnimation=anim;
            tabs.setAnimation(anim);

A: ok found the solution, instead of tabs, used the Animation on the ViewPager

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I solve index alias error if I can't run elasticSearch? The es instance I'm working with crashed, and attempting to restart the kernel leads to the run command immediately being killed (runES.sh: line 1: 92654 Killed ./bin/Elasticsearch).
The log shows this error:
[2022-03-02T10:40:54,802][INFO ][o.e.x.i.IndexLifecycleRunner] [smartmedia] policy [logstash-policy] for index [logstash-testin
dex] on an error step due to a transitive error, moving back to the failed step [check-rollover-ready] for execution. retry att
empt [24812]
[2022-03-02T10:50:54,779][ERROR][o.e.x.i.IndexLifecycleRunner] [smartmedia] policy [logstash-policy] for index [logstash-testin
dex] failed on step [{"phase":"hot","action":"rollover","name":"check-rollover-ready"}]. Moving to ERROR step
java.lang.IllegalArgumentException: index.lifecycle.rollover_alias [logstash] does not point to index [logstash-testindex]
        at org.elasticsearch.xpack.core.ilm.WaitForRolloverReadyStep.evaluateCondition(WaitForRolloverReadyStep.java:104) [x-pa
ck-core-7.8.1.jar:7.8.1]
        at org.elasticsearch.xpack.ilm.IndexLifecycleRunner.runPeriodicStep(IndexLifecycleRunner.java:173) [x-pack-ilm-7.8.1.ja
r:7.8.1]
        at org.elasticsearch.xpack.ilm.IndexLifecycleService.triggerPolicies(IndexLifecycleService.java:329) [x-pack-ilm-7.8.1.
jar:7.8.1]
        at org.elasticsearch.xpack.ilm.IndexLifecycleService.triggered(IndexLifecycleService.java:267) [x-pack-ilm-7.8.1.jar:7.
8.1]
        at org.elasticsearch.xpack.core.scheduler.SchedulerEngine.notifyListeners(SchedulerEngine.java:183) [x-pack-core-7.8.1.
jar:7.8.1]
        at org.elasticsearch.xpack.core.scheduler.SchedulerEngine$ActiveSchedule.run(SchedulerEngine.java:211) [x-pack-core-7.8
.1.jar:7.8.1]
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) [?:?]
        at java.util.concurrent.FutureTask.run(FutureTask.java:264) [?:?]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) [?:?]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) [?:?]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) [?:?]
        at java.lang.Thread.run(Thread.java:832) [?:?]

If I understand correctly, the problem is this part: [logstash] does not point to index [logstash-testindex]. However I do not know how to change an alias for an index if I can't even start the kernel. This
curl -X PUT "localhost:9200/logstash?pretty" -H 'Content-Type: application/json' -d'
{
  "aliases": {
    "logstash-testindex":{
      "is_write_index": true
    }
  }
}
'

results in an error because elasticSearch is not actually running. Is there a config file I need to change instead?

A: This error occurs due to below reason as mentioned in this document.

Either the index is using the wrong alias or the alias does not exist.

If you are using ES version below 7.8 then you can set below configuration in elasticsearch.yml file.
xpack.ilm.enabled: false


text:
Q: Computing a FFT on CSV Data i would like to get the FFT out of my CSV Data to analyse it afterwards. Im very new in Programming.
This is a look in my CSV Data:
Zeit;Kanal A;Kanal B;Kanal C;Kanal D
(s);(mV);(mV);(mV);(V)
0;2,734709;-13,00818;10,01709;-10,22464
0,0001;2,618728;-12,8922;9,547064;-10,22464
0,0002;0,3845684;-16,54865;2,862898;-4,42559
0,0003;3,082652;-11,47601;12,36113;-4,42559
0,0004;2,496643;-13,00818;9,431083;-4,42559
0,0005;2,496643;-12,77622;9,663045;-7,32511
0,0006;2,966671;-13,48431;18,3372;-13,12416
0,0007;0,9705775;-14,9005;6,14699;-16,02368
0,0008;2,496643;-12,06812;11,65303;-18,92321
0,0009;1,794653;-12,8922;10,13307;-16,02368
0,001;2,026615;-12,8922;10,36504;-16,02368
0,0011;4,492736;-6,995483;17,75119;-10,22464
0,0012;1,208644;-13,71627;8,13698;-7,32511
0,0013;1,794653;-12,77622;11,42107;-4,42559
The total length of my CSV Data is ~100.000 rows.
from os import sep
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from numpy.fft import rfft, rfftfreq,irfft

dt=1/10000

g=pd.read_csv('20210803-0002.csv', sep = ';', skiprows=[1,2],usecols = [4],dtype=float, decimal=',')

n=len(g)

acc=g.values.flatten()

fft=abs(rfft(acc)*dt)
freq=rfftfreq(n,d=dt)

FFT=abs(fft)

plt.plot(freq,FFT)
plt.show()

Does this code makes sense to compute and plot a FFT with it ?
I got this problem:

I expect a peak at 15, but it is at 14.75
I am happy for every useful feedback !


text:
Q: Using the 'f' command in vim to search more than just the current line I know that philosophically the f/F command is used to search through the current line. However, other than [LINE]G f, what would be the best way to jump to somewhere else in the file in the style of the f command?

A: Add this line to you ~/.vimrc
set incsearch

to activate incremental search and use /foo<CR> to search forward or ?bar<CR> to search backward.
Note that, like fFtT, /? can also be very useful as motions for dcsv.
If you don't mind using a plugin, there are a bunch of them designed around the idea of multi-dimensional fFtT like this one. Take a look around vim.org.

A: You may want to use the vim plugin EasyMotion,

*

*github repo

*vim online
<Leader>f<char> will search forward from current line to the end of current window.
<Leader>F<char> will search backward from current line to the start of current window.
for all usage :help easymotion.txt

A: Christian Brabandt's ft_improved plugin extends the built-in f / t commands to search in following lines, too.


text:
Q: what happened to missing.pattern.plot or mp.plot? I have the package mi installed.
But when I try to run mp.plot (as Thomas Leeper does in this tutorial:) I get the following error message:

mp.plot(mydf)
  Error in mp.plot(mydf) : could not find function "mp.plot"

On one website this is called missing.pattern.plot, but that also does not work:

missing.pattern.plot(mydf)
  Error in missing.pattern.plot(mydf) :
    could not find function "missing.pattern.plot"

Any idea what the issue might be?
I do not really care much if I cannot use this function, but I'm curious as to what is going on in case I later need to use a graph that I really need.


text:
Q: Why can I no longer command Siri "go to sleep?" I have been saying "hey Siri go to sleep" as I leave my home office every day since I got my iMac Retina a few weeks back.
Today I got these responses:

I haven't changed any settings, is it possible a recent update to Big Sur has changed something? It's the only use of Siri I really have!

A: I have been monitoring this for some time now and it seems quite clear that Siri's performance degrades over time when my Mac is left running for days or weeks:

*

*The time it takes the Siri popup to appear after saying "Hey Siri" slowly gets longer and longer. After a reboot it is instant, over time it can end up being several seconds

*Some commands or wordings like "go to sleep" stop being recognised. I can still say "put this Mac to sleep" for example.

Rebooting fixes everything until it gradually gets annoying enough to reboot. Quite odd, presumably some subtle bug somewhere.


text:
Q: SharePoint linked datasource I have created a linked datasource in sharepoint designer by joining two sharepoint lists. Can anyone tell me how can I access this linked datasource programmatically?
Regards,
Sharmila

A: In SharePoint designer, it seems to me that linked datasources show up in the list of available libraries when you are trying to build a data view web part or similar constructs.
So maybe try to access your linked datasource like you would any other list or document library?


text:
Q: perl: upper case evaluation for subroutine I need to pass system variable in upper case to perl subroutine.
For example, if the variable with name VARNAME (value 'super'), i need to pass "SUPER_MAN".
In general, if we use 'uc' option like in the example below, we can convert to upper case
 perl -e 'print uc"$ENV{VARNAME}\n"'

But when we try to pass it in subroutine, we need to include uc function in the syntax and evaluate during runtime. To emulate that I was trying the below but not working, Where am I going wrong?
perl -e 'print ".uc($ENV{VARNAME})_MAN\n"'
.uc(super)_MAN

Alternate methods/approach is also welcome.

A: Take the uc out of the quotes "", since perl thinks you want the literal letters uc:
FOO=abc perl -e 'print "." . uc($ENV{FOO}) . "_MAN\n"'
.ABC_MAN

perldoc perlop - Quote and Quote like Operators


text:
Q: Shapefile of South Tyneside borough (north-east England) boundary I'm looking for a free-to-download shapefile (polygons) of South Tyneside borough. South Tyneside is a metropolitan borough in NE England. Can anyone help?

A: You could use free and open OpenStreetMap data.
With the Overpass-API it's possible to download the data.
Simply follow this link to run the query, click "export" and choose your prefered format (e.g. GeoJSON).
Alternatively, run a query by typing name="South Tyneside" and execute the query.


text:
Q: CSS Selector for hidding a text Consider below HTML

         Sample Link

       Hide Me with CSS

Is it possible to remove or hide the Hide Me With CSS with CSS?
I tried:
#nav-main li a:after{
    content: "";
}

But no luck.
http://jsfiddle.net/6powxzru/
I can not change the above HTML as this is a dynamically generated code (with a JSP tag).

A:
I can not change the above html as this is a dynamically generated code

Change the font-size

#nav-main li {
  font-size: 0;
}
#nav-main li a {
  font-size: 12px;
}

      Sample Link

    Hide Me with CSS

A: One way to achieve this is to set visibility: hidden for the li and then set it to visible for the a inside the li.

#nav-main li {
  visibility: hidden;
}
#nav-main li a {
  visibility: visible;
}

      Sample Link
    Hide Me with CSS

A: Remove the text node with JS:
var node = document.querySelector('#nav-main > LI > A').nextSibling;
node.parentNode.removeChild(node);

A: How about you try the following approach (not sure if possible in your case, though):

*

*Color li within nav with the background color of the whole container, so the text is not visible any more.

*After that, you would style individual elements based on colors you want. If the container background is white, you would start with:
nav-main li{color:#FFF;}
nav-main li a{color:#000;}
etc.

A: From W3Schools:

The ::after selector inserts something after the content of each selected element(s).

This means any content you add in the after "element" will appear after but still inside the original element, which in your case is the a tag.
Also, you cannot remove text using the content property which was not added using the content property. So, to hide such text which is outside the a but inside the li on a specific event, such as hover, you can instead do something like this.

#nav-main li:after {
    content: "Hide Me With CSS";
}
#nav-main li:hover:after {
    content: "";
}

         Sample Link


text:
Q: Display Fragment Onclick I have the error in line

FragmentManager fm = getFragmentManager();

Any solution for pass activities when I click? So what I need?
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {

private List<ItemObject> itemList;
private Context context;

public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
    this.itemList = itemList;
    this.context = context;
}

@Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
    RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
    return rcv;
}

@Override
public void onBindViewHolder(final RecyclerViewHolders holder, final int position) {
    holder.cardText.setText(itemList.get(position).getName());
    holder.cardPhoto.setImageResource(itemList.get(position).getPhoto());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {

            switch (position){
                case 0:

                    FragmentManager fm = getFragmentManager();

                    FragmentTransaction ft = fm.beginTransaction();
                    ft.replace(R.id.frameLayout, new FragmentNewGame(), "newGame");
                    ft.addToBackStack(null);
                    ft.commit();

A: Replace this :
 FragmentManager fm = getFragmentManager();

to this :
FragmentManager fm = ((Activity)context).getFragmentManager();

Then your code should look like :
FragmentManager fm = ((Activity)context).getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frameLayout, new FragmentNewGame(), "newGame");
ft.addToBackStack(null);
ft.commit();

Or
FragmentTransaction ft = ((Activity)context).getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frameLayout, new FragmentNewGame(), "newGame");
                ft.addToBackStack(null);


text:
Q: Spring Transaction Isolation Level Most of us might be using Spring and Hibernate for data access.
I am trying to understand few of the internals of Spring Transaction Manager.
According to Spring API, it supports different Isolation Level - doc
But I couldn't find clear cut information on which occasions these are really helpful to gain performance improvements.
I am aware that readOnly parameter from Spring Transaction can help us to use different TxManagers to read-only data and can leverage good performance. But it locks the table to get the data to avoid dirty-reads/non-committed reads - doc.
Assume, in few occasions, we might want to blindly insert the records into a table and retrieve the information without locking the table, a case where we never update the table data, we just insert and read [append-only]. Can we use better Isolation to gain any performance?

*

*As you see from one of the reference links, do we really require to implement/write our own CustomJPADiaelect?

*What's the better Isolation for my requirement?

A: Read-only allows certain optimizations like disabling dirty checking and you should totally use it when you don't plan on changing an entity.
Each isolation level defines how much locking a database has to impose for ensuring the data anomaly prevention.
Most database use MVCC (Oracle, PostgreSQL, MySQL) so readers don't lock writers and writers don't lock readers. Only writers lock writers as you can see in the following example.
REPEATABLE_READ doesn't have to hold a lock to prevent a concurrent transaction from modifying your current transaction loaded rows. The MVCC engine allows other transactions to read the committed state of a row, even if your current transaction has changed it but hasn't yet committed (MVCC uses the undo logs to recover the previous version of a pending changed row).
In your use case you should use READ_COMMITTED as it scales better than other more strict isolation levels and you should use optimistic locking for preventing lost updates in long conversations.

Update
Setting @Transactional(isolation = Isolation.SERIALIZABLE) to a Spring bean has a different behaviour, depending on the current transaction type:

*

*For RESOURCE_LOCAL transactions, the JpaTransactionManager can apply the specific isolation level for the current running transaction.

*For JTA resources, the transaction-scoped isolation level doesn't propagate to the underlying database connection, as this is the default JTA transaction manager behavior. You could override this, following the example of the WebLogicJtaTransactionManager.

A: Actually readOnly=truedoesn't cause any lock contention to the database table, because simply no locking is required - the database is able to revert back to previous versions of the records ignoring all new changes.
With readOnly as true, you will have the flush mode as FlushMode.NEVER in the current Hibernate Session preventing the session from committing the transaction. In addition, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database not to commit changes.
So readOnly=true is exactly what you are looking for (e.g. SERIALIZED isolation level).
Here is a good explanation.


text:
Q: In JavaScript testing the equality of two values where the content includes & The following code snippet demonstrates my problem.  When I test a string that contains the "&" the result is always false.
How should this be handled?  JavaScript solution only please.

  var PROJECT = "This & Somthing Else";
  var PROJECT2 = "This and Somthing Else";

  function testValues()
  {
   if (PROJECT == document.getElementById("curPrjct").innerHTML)
   {
    alert("The Same");
   }else{
    alert("Not The Same");
   }
  }

  function testValues2()
  {
   if (PROJECT2 == document.getElementById("curPrjct2").innerHTML)
   {
    alert("The Same");
   }else{
    alert("Not The Same");
   }
  }
<!doctype html>

 This & Somthing Else

 <input type="button" value="Go This will fail" onclick="testValues()">

 This and Somthing Else

 <input type="button" value="Go This will work" onclick="testValues2()">

A: The problem with trying to look at the HTML is that when it is converted to a DOM and then back to HTML, it will be normalised.
& will be converted to &.
Compare the textContent instead of the HTML.

  var PROJECT = "This & Somthing Else";
  var PROJECT2 = "This and Somthing Else";

  function testValues()
  {
   if (PROJECT == document.getElementById("curPrjct").textContent)
   {
    alert("The Same");
   }else{
    alert("Not The Same");
   }
  }

  function testValues2()
  {
   if (PROJECT2 == document.getElementById("curPrjct2").textContent)
   {
    alert("The Same");
   }else{
    alert("Not The Same");
   }
  }
<!doctype html>

 This & Somthing Else

 <input type="button" value="Now this will work" onclick="testValues()">

 This and Somthing Else

 <input type="button" value="Go This will work" onclick="testValues2()">


text:
Q: POP-Before-SMTP Recently I had to move one of my web applications to a new hosting provider. The mail and web service is still held on the old hosting site however, when I try to send an email from the new server,I get an error;
"The server rejected one or more recipient addresses. The server response was:
450 <email_address>: Recipient address rejected: Greylisted for 5 minutes

I asked my old hosting provider what I need to do to fix this and they replied with

The mail server operates on POP before
  SMTP. If a valid POP login is not
  received before sending mail through
  the server, then the mail is
  greylisted and held for 5 minutes
  before a retry.
To prevent this, simply do a Receive
  before sending mail

Does anyone have any idea how I do a POP before SMTP in C#?

A: i'm not sure how C# would handle the specifics (sockets?), but basically you just want to make a connection to your new POP server. here's a sample POP transaction:
$ telnet new-pop-server.com 110
Connected to new-pop-server.com.
Escape character is '^]'.
+OK
USER <username>
+OK
PASS <password>
+OK               // you're authenticated at this point
LIST
+OK
.                 // no new messages!
QUIT
+OK

once you're authorized you should be able to send your mail programatically. (USER, PASS, LIST, QUIT) are all commands you would send (pop3 RFC).

A: They greylist you because you connect from your new provider, right? Doesn't the new provider have a SMTP which allows connections from the servers IP-range?
Another approach is to do the MX-lookup yourself, and connect directly to the authoritive SMTP-server for which address you're sending email to. However, that also requires you to handle greylisting, meaning, retries on 4xx responses in order to have a reliable delivery.
Maybe you should ask your provider if they provide auth SMTP as an alternative aswell, it's kind of another possible point of failure with the need of POP-login before using the SMTP-service.

A: I'm pretty sure POP3 is not built into the .NET Framework, so you'll need to implement it yourself as Owen suggested or look for an existing POP3 library such as this one.
Even better would be convincing your new hosting provider to relax that greylisting rule.

A: I managed to write the code for this. I am willing to share the solution, (if anyone is interested?) but not sure how best to put the code on Stackoverflow? It's about 50 lines of code.

A: As suggested I added the code to my blog. It's not the best blog ever published but, someone may find it useful...
POP-Before-SMTP

A: You already have the code you're looking for, but if I may add in my thoughts: Like someone else already suggested, I would check with the old provider whether they provide AUTH with SMTP. To me, what they are saying is that, "You can use SMTP only if you are coming from the same IP range/subnet, or if you have authenticated yourself". A lot of ISPs do this with their SMTP servers. If you are connected through a particular ISP, you can use the SMTP without providing any AUTH credentials explicitly. If you switch to another ISP and want to use the old ISP's SMTP, you'll have to explicitly authenticate with the SMTP server.


text:
Q: Android program crashes I'm having some difficulties with my android application.
Heres my code:
package activities;

import java.util.Vector;

import coursework.prototype.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class game_calculator extends Activity {

double currentTotal = 0.0; //Total of current calculation
String currentText = "0"; //Text displayed in the TextView
TextView Calculator_Display;
Vector<String> currentCalculations = new Vector<String>(); //Set up a vector to hold calculations

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game_calculator);

    Calculator_Display = (TextView) findViewById(R.id.display); //Locate the textview
    Calculator_Display.setText( currentText ); //Set the text to default value
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

// MY CODE STARTS HERE

//Go Back button on click event
//Sets the current activity to the main menu
public void GoToMenu(View v)
{
    startActivity( new Intent(this, game_selection.class) );
}

//Adds the number to the current display
public void CalculatorButton(View v)
{
    //Get the buttons text
    String buttons_text = ((Button) v).getText().toString();

    //If no number has been inputed (screen will show 0)
    if(currentText == "0")
    {
        currentText = buttons_text;
    }
    else //Add the number to the current display (after previous entered numbers)
    {
        currentText = currentText + buttons_text;
    }
    Calculator_Display.setText(currentText); //Set the display to the inputed number
}

//Performs the calculation with the current total and the display number
public void CalculatorFunction(View button)
{
    switch( button.getId() )
    {
    case R.id.calculator_equals: //display the current total

        currentCalculations.add( currentText ); //Add current number into the vector

        if(currentCalculations.size() > 0) //Only process calculations if there's elements to process
            CalculateTotal();

        currentText = "0"; //Reset display
        break;
    case R.id.calculator_reset:
        currentText = "0"; //Reset stored display
        currentTotal = 0; //Reset stored total
        currentCalculations.clear();
        break;
    case R.id.calculator_backspace:
        //Delete the last entered number
        if (currentText.length() > 0 && currentText.charAt(currentText.length()-1)=='0') {
            currentText = currentText.substring(0, currentText.length()-1);
          }
        break;
    default:
        //Convert the display to an integer to be worked with
        currentCalculations.add( currentText ); //Add current number into the vector
        currentCalculations.add( ((Button) button).getText().toString() ); //Add the type of calculation to perform

        currentText = "0"; //Reset display number
        break;
    }

    Calculator_Display.setText( currentText ); //Set the new display
}

public void CalculateTotal()
{
    //Set up variables
    String currentElement; //Temporary string storage
    String currentSign = " "; //Temporary sign storage
    double currentNumber = 0; //Temporary number storage
    Log.i("INFORMATION", "<=================== MY LOGS START HERE ===================>" );
    Log.i("INFORMATION", "Size: " + Integer.toString(currentCalculations.size()) );

    //Start processing
    for(int c = 0; c <= currentCalculations.size(); c++) //Loops through elements to process
    {
        currentElement = currentCalculations.get( c ); //Get element from array
        Log.i("INFORMATION", "Element " + Integer.toString(c) + " : " + currentElement );

        //Check if the element is a sign
        if(currentElement == "+" || currentElement == "-" || currentElement == "*" || currentElement == "/")
        {
            Log.i("INFORMATION", "Sign found!");
            currentSign = currentElement; //Save into temporary storage to be used next loop
        }
        else // Element is a number
        {
            currentNumber = Double.parseDouble( currentElement ); //Convert number to integer

            if(currentSign == "+")
                currentTotal += currentNumber;
            else if(currentSign == "-")
                currentTotal -= currentNumber;
            else if(currentSign == "*")
                currentTotal = currentTotal * currentNumber;
            else if(currentSign == "/")
                currentTotal = currentTotal / currentNumber;
            else
                Log.i("INFORMATION", "THE PROGRAMS FUCKED UP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        }

    }
    Calculator_Display.setText( Double.toString( currentTotal ) ); //Display the currentTotal

    Log.i("INFORMATION", "<=================== MY LOGS END HERE ===================>" );
}
}

The app crashes when I hit the equals button so I know the error is with CalculateTotal but am not sure why its crashing. If I do 7 + 8, the Logcat shows:
11-13 19:10:43.073: I/INFORMATION(1408): <=================== MY LOGS START HERE ===================>
11-13 19:10:43.073: I/INFORMATION(1408): Size: 5
11-13 19:10:43.114: I/INFORMATION(1408): Element 0 : 7
11-13 19:10:43.114: I/INFORMATION(1408): Element 1 : +
11-13 19:10:43.244: W/dalvikvm(1408): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
11-13 19:10:43.476: E/AndroidRuntime(1408): FATAL EXCEPTION: main
11-13 19:10:43.476: E/AndroidRuntime(1408): java.lang.IllegalStateException: Could not execute method of the activity
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.view.View$1.onClick(View.java:3633)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.view.View.performClick(View.java:4240)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.view.View$PerformClick.run(View.java:17721)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.os.Handler.handleCallback(Handler.java:730)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.os.Looper.loop(Looper.java:137)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.reflect.Method.invokeNative(Native Method)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.reflect.Method.invoke(Method.java:525)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at dalvik.system.NativeStart.main(Native Method)
11-13 19:10:43.476: E/AndroidRuntime(1408): Caused by: java.lang.reflect.InvocationTargetException
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.reflect.Method.invokeNative(Native Method)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.reflect.Method.invoke(Method.java:525)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at android.view.View$1.onClick(View.java:3628)
11-13 19:10:43.476: E/AndroidRuntime(1408):     ... 11 more
11-13 19:10:43.476: E/AndroidRuntime(1408): Caused by: java.lang.NumberFormatException: Invalid double: "+"
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.StringToReal.initialParse(StringToReal.java:151)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.StringToReal.parseDouble(StringToReal.java:263)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at java.lang.Double.parseDouble(Double.java:295)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at activities.game_calculator.CalculateTotal(game_calculator.java:127)
11-13 19:10:43.476: E/AndroidRuntime(1408):     at activities.game_calculator.CalculatorFunction(game_calculator.java:76)
11-13 19:10:43.476: E/AndroidRuntime(1408):     ... 14 more
11-13 19:14:16.423: I/Process(1408): Sending signal. PID: 1408 SIG: 9
11-13 19:14:18.223: I/dalvikvm-heap(1446): Grow heap (frag case) to 4.082MB for 1536016-byte allocation
11-13 19:20:14.522: I/dalvikvm-heap(1545): Grow heap (frag case) to 4.082MB for 1536016-byte allocation
11-13 19:20:20.124: I/dalvikvm-heap(1545): Grow heap (frag case) to 5.822MB for 1536016-byte allocation
11-13 19:20:29.415: I/dalvikvm-heap(1545): Grow heap (frag case) to 7.856MB for 1536016-byte allocation
11-13 19:20:32.132: I/Choreographer(1545): Skipped 31 frames!  The application may be doing too much work on its main thread.
11-13 19:20:43.032: I/INFORMATION(1545): <=================== MY LOGS START HERE ===================>
11-13 19:20:43.032: I/INFORMATION(1545): Size: 3
11-13 19:20:43.122: I/INFORMATION(1545): Element 0 : 7
11-13 19:20:43.162: I/INFORMATION(1545): THE PROGRAMS FUCKED UP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
11-13 19:20:43.172: I/INFORMATION(1545): Element 1 : +
11-13 19:20:43.224: W/dalvikvm(1545): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
11-13 19:20:43.292: E/AndroidRuntime(1545): FATAL EXCEPTION: main
11-13 19:20:43.292: E/AndroidRuntime(1545): java.lang.IllegalStateException: Could not execute method of the activity
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.view.View$1.onClick(View.java:3633)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.view.View.performClick(View.java:4240)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.view.View$PerformClick.run(View.java:17721)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.os.Handler.handleCallback(Handler.java:730)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.os.Looper.loop(Looper.java:137)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.reflect.Method.invokeNative(Native Method)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.reflect.Method.invoke(Method.java:525)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at dalvik.system.NativeStart.main(Native Method)
11-13 19:20:43.292: E/AndroidRuntime(1545): Caused by: java.lang.reflect.InvocationTargetException
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.reflect.Method.invokeNative(Native Method)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.reflect.Method.invoke(Method.java:525)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at android.view.View$1.onClick(View.java:3628)
11-13 19:20:43.292: E/AndroidRuntime(1545):     ... 11 more
11-13 19:20:43.292: E/AndroidRuntime(1545): Caused by: java.lang.NumberFormatException: Invalid double: "+"
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.StringToReal.initialParse(StringToReal.java:151)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.StringToReal.parseDouble(StringToReal.java:263)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at java.lang.Double.parseDouble(Double.java:295)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at activities.game_calculator.CalculateTotal(game_calculator.java:126)
11-13 19:20:43.292: E/AndroidRuntime(1545):     at activities.game_calculator.CalculatorFunction(game_calculator.java:76)
11-13 19:20:43.292: E/AndroidRuntime(1545):     ... 14 more
11-13 19:25:43.513: I/Process(1545): Sending signal. PID: 1545 SIG: 9
11-13 19:25:44.963: I/dalvikvm-heap(1577): Grow heap (frag case) to 4.082MB for 1536016-byte allocation

A: never ever ever use == to check equality for strings in Java. you must always use
string1.equals(string2)

the line
if (currentString == "+")

will always return false, so you must use
if (currentString.equals("+"))

A: The problem is that you do  Integer.toString(c) before you check to see if c is numeric.
Also, be aware that you shouldn't compare strings with == you must use .equals(), or you will get unexpected results.

A: I think the problem is that your IF returns "false" in this fragment:
    //Check if the element is a sign
    if(currentElement == "+" || currentElement == "-" || currentElement == "*" || currentElement == "/")
    {
        Log.i("INFORMATION", "Sign found!");
        currentSign = currentElement; //Save into temporary storage to be used next loop
    }
    else // Element is a number
    {
        currentNumber = Double.parseDouble( currentElement ); //Convert number to integer
    }

So you get fatal error when you try to execute Double.parseDouble(currentElement) with currentElement="+".
I would use string comparison instead of "==", like this:
if("+".equals(currentElement) || "-".equals(currentElement) ... etc


text:
Q: How to use a pattern on an input[type="number"]? I want the default value to be 0 and recolor the input if it's more than 0, using :valid. Am I doing something wrong? Is Google Chrome wrong? Or the HTML5 specification? I want to solve this without JS.

:valid {
  background: green
}

This should not be green, but it is:

<input max="100" min="0" pattern="^[1-9]\d*$" type="number" value="0" />

Works perfectly, if the type is changed to text:

<input pattern="^[1-9]\d*$" type="text" value="0" />

A: Citing MDN on the pattern property (highlighting added):

pattern
A regular expression that the control's value is checked against.
  The pattern must match the entire value, not just some subset. Use the
  title attribute to describe the pattern to help the user. This
  attribute applies when the value of the type attribute is text,
  search, tel, url or email; otherwise it is ignored. The regular
  expression language is the same as JavaScript's. The pattern is not
  surrounded by forward slashes.

Interestingly I can't find any mentioning of that in both W3C and WhatWG standards.

A: I see that if you give the minimum value of 1, the color is not green for 0. The color changes to green when you enter 1. I think that is what you are expecting, right?
Basically, you can use min and max values for validation purpose. I don't think you need pattern for this.
<input max="100" min="1" type="number" value="0" />

There is one limitation here. If you leave the field empty, it is still green!


text:
Q: Why two parallel arrays are faster than single array for storing tuples Android developer guide mentions the following point

If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects.

Could somebody help me understand why using two parallel arrays is faster?

A: I am assuming you're reading this page: https://developer.android.com/training/articles/perf-tips
The idea behind what they're saying is that every object instance incurs a small amount of memory overhead. Therefore, one array of many Tuple objects each holding one Foo and one Bar will have more overhead than two arrays (one of Foo objects and one of Bar objects).
This increase in memory consumption might cause the garbage collector to run more frequently, and each garbage collection action will pause your app (though it will only pause it for tiny fractions of a second).
However, keep in mind that this article is very old. You can get a sense of exactly how old it is from this line (emphasis mine):

The concurrent garbage collector introduced in Android 2.3 helps

These performance considerations mattered more when android hardware was weak and slow. Now that we're working on hardware that's orders of magnitude more powerful, the practical impact of things like this is significantly reduced.
In general, I would very much recommend against taking this article's advice. One array of Tuple objects is much easier to reason about, and will make your app much easier to maintain in the long run. Unless you have done specific and explicit performance measuring and determined beyond a shadow of a doubt that your application is garbage collecting too frequently, just ignore these "tips".
In fact, even this article tells you that you should probably ignore it unless you know you have a problem:

Choosing the right algorithms and data structures should always be your priority

and

Always measure
Before you start optimizing, make sure you have a problem that you need to solve. Make sure you can accurately measure your existing performance, or you won't be able to measure the benefit of the alternatives you try.


text:
Q: How to know which API Partner Server URL to use I have registered an development test account in SF and one connected app.
From connected app I have to call SF SOAP API. I do not know which web service base address to use. I see that for different environments there are different URL addresses, such as Api.Partner_Server_URL_160 Api.Partner_Server_URL_210 and others.
How to know which one URL environment to use ?
Thanks

A: The version number (e.g. 160, 210) references the version of the API being used (e.g. 16.0, 21.0). This is influenced by when the app was originally developed or last updated to the latest version of the API. When creating a new app, you will generally use the latest possible version available at that time (e.g. 29.0), because you cannot intentionally download a WSDL for an older version. Versioning is how salesforce.com can keep introducing new features while maintaining backwards compatibility. In summary, if you have any doubt, check the version of the imported WSDL file; that is the version you will use.


text:
Q: css3 background radial circle gradient I have this code below which creating a background radial circle gradient.
it's working well on all browsers except IE (not working even on IE9)
what should I add to the css in order for it to work also on IE9 and IE8?
http://jsfiddle.net/bhBtw/
The code:
<!DOCTYPE html>

    <title></title>

A: *

*IE up to and including 9 don't support CSS gradients. So it shouldn't work in IE 9 and older.

*There is no need for the -ms-linear-gradient line. Gradients are supported unprefixed in IE10 and they are not supported at all in IE9 and older.

*You should always put the unprefixed version last. Even browsers that support the unprefixed syntax will still use the prefixed one if you don't put the unprefixed version last.

*The new gradient syntax uses farthest-corner instead of cover. And that's the default value, so you can leave it out.

*center is the default value for position (so you can leave that out as well).

What should you do for IE9 and older? Not much. Fallback on:

*

*a linear IE filter gradient or

*a background image with that gradient or

*just a solid color (the option I'd go with in this case, given that the two colors you're using here are not that different from one another and most people couldn't even tell there's a gradient there without looking closely)

So that code should become:
background: #352e24; /* ultimate fallback, always put this, just in case */

/* if you choose the IE filter linear gradient fallback */
filter: progid:DXImageTransform.Microsoft.gradient(
             startColorstr=#352e24, endColorstr=#1a160d);

/* if you choose to use the image fallback */
background: url(gradient.png);

/* Chrome, Safari */
background: -webkit-radial-gradient(circle, #352e24, #1a160d);

/* Firefox 15 and older, Firefox for Android */
background: -moz-radial-gradient(circle, #352e24, #1a160d);

/* Opera 11.6 (older only supported linear), Opera 12.0, Opera Mobile 12.0 */
background: -o-radial-gradient(circle, #352e24, #1a160d);

/* standard syntax, IE10, Firefox 16+, Opera 12.1+ */
background: radial-gradient(circle, #352e24, #1a160d);


text:
Q: How to return previous element from group where some column is True My data frame is as follows:
ex = {'group': {0: '0', 1: '0', 2: '0', 3: '0', 4: '0', 5: '0', 6: '0', 7: '0', 8: '0', 9: '0', 10: '0', 11: '0', 12: '0', 13: '0', 14: '0', 15: '0', 16: '0', 17: '0', 18: '0', 19: '0', 20: '0', 21: '1', 22: '1', 23: '1', 24: '1', 25: '1', 26: '1', 27: '1', 28: '1', 29: '1', 30: '1', 31: '1', 32: '1', 33: '1', 34: '1', 35: '1', 36: '1', 37: '1', 38: '1', 39: '1'}, 'order': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 0, 22: 1, 23: 2, 24: 3, 25: 4, 26: 5, 27: 6, 28: 7, 29: 8, 30: 9, 31: 10, 32: 11, 33: 12, 34: 13, 35: 14, 36: 15, 37: 16, 38: 17, 39: 18}, 'id': {0: '102', 1: '302', 2: '302', 3: '302', 4: '102', 5: '302', 6: '302', 7: '302', 8: '302', 9: '302', 10: '102', 11: '308', 12: '308', 13: '308', 14: '308', 15: '302', 16: '102', 17: '302', 18: '102', 19: '302', 20: '102', 21: '102', 22: '102', 23: '308', 24: '312', 25: '312', 26: '312', 27: '308', 28: '102', 29: '302', 30: '312', 31: '302', 32: '302', 33: '102', 34: '102', 35: '302', 36: '312', 37: '308', 38: '102', 39: '302'}, 'type': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'D', 5: 'E', 6: 'D', 7: 'E', 8: 'A', 9: 'E', 10: 'E', 11: 'D', 12: 'A', 13: 'A', 14: 'A', 15: 'D', 16: 'D', 17: 'D', 18: 'A', 19: 'D', 20: 'A', 21: 'D', 22: 'F', 23: 'A', 24: 'D', 25: 'A', 26: 'E', 27: 'A', 28: 'E', 29: 'D', 30: 'E', 31: 'E', 32: 'G', 33: 'A', 34: 'D', 35: 'D', 36: 'H', 37: 'I', 38: 'A', 39: 'E'}, 'of_interest': {0: False, 1: False, 2: True, 3: False, 4: False, 5: True, 6: False, 7: True, 8: True, 9: True, 10: True, 11: True, 12: True, 13: False, 14: True, 15: True, 16: True, 17: True, 18: False, 19: False, 20: True, 21: False, 22: False, 23: False, 24: True, 25: False, 26: True, 27: True, 28: False, 29: True, 30: True, 31: False, 32: True, 33: True, 34: True, 35: True, 36: True, 37: False, 38: True, 39: False}}

ex.head()
  group  order   id type  of_interest
0     0      0  102    A        False
1     0      1  302    B        False
2     0      2  302    C         True
3     0      3  302    A        False
4     0      4  102    D        False

I want to create a column that for each combination of group and id return previous type where of_interest == True.
My first attempt involved querying for of_interest == True, therefore returned value only for these rows:
ex['prev_type_of_interest'] = ex \
    .query('of_interest == True') \
    .groupby(['group', 'id'])['type'] \
    .shift(1)

How can I return previous type of interest for every row?

A: I believe you need shift all rows per groups, then set missing values by Series.where and last replace missing values by previos non missing values by GroupBy.ffill:
ex1 = ex.groupby(['group', 'id']).shift()
ex['prev_type_of_interest'] = ex1['type'].where(ex1['of_interest'] == True)

ex['prev_type_of_interest'] = ex.groupby(['group', 'id'])['prev_type_of_interest'].ffill()

print (ex.head(10))
  group  order   id type  of_interest prev_type_of_interest
0     0      0  102    A        False                   NaN
1     0      1  302    B        False                   NaN
2     0      2  302    C         True                   NaN
3     0      3  302    A        False                     C
4     0      4  102    D        False                   NaN
5     0      5  302    E         True                     C
6     0      6  302    D        False                     E
7     0      7  302    E         True                     E
8     0      8  302    A         True                     E
9     0      9  302    E         True                     A


text:
Q: azure re-run startup task in cloud service without restarting role I have an azure cloud service startup tasks that creates a PhantomJS process which hosts a web server in the background.  Sometimes the PhantomJS processes needs to be restarted.
How would I re-run this startup task without having to a do a full role recycle?
I have an endpoint that I hit every 5 minutes to check the status of the PhantomJS process and if it comes back as a failure, I want to restart this process.
I'd prefer to stay away from using Process.Start within asp.net as then I have to worry about credentials and user impersonation to start the process back up.
My startup tasks runs the following...
START /B  "my_log.txt >>" /D "%~dp0" phantomjs2.exe --local-to-remote-url-access=true --ignore-ssl-errors=true js\renderHtmlWebServer.js >>  "%TEMP%\PhantomJS_%datetimef%.txt" 2>&1

A: You can't rerun your startup task without restarting the role, but you could move that code into your Run method in WebRole.cs.  The run method runs in WaIISHost.exe (or WaWorkerHost.exe for a worker role) which is the same user context (a virtual account created by the guest agent) as a startup task, which is different than the w3wp/asp.net (which runs as standard network user).
However, a better question might be - why is your PhantomJS process not still running?  If it is expected to shut down due to inactivity or something like that then simply restarting it may be ok.  But if it is shutting down for unknown reasons then you might consider treating the role as in an unknown healthy state and recycle the entire role.

A: I'll offer three suggestions.

*

*Make sure PhantomJS doesn't die. From personal experience I know that can be really tough.

*Package up and deploy an .exe that ensures that the PhantomJS process is always running. It can monitor running processes and if it notices the PhantomJS process is dead, it will restart it.

*Create a special endpoint that allows you to restart the process remotely/on demand. This is the last option because of security issues. It's a possibility, but not recommended.


text:
Q: Equation of a plane through a point and perpendicular to 2 other planes Find the plane through the point P = (2, 1, -1) which is perpendicular to the planes 2x + y - z = 3 and x + 2y + z = 2.
So far, what I'm doing is taking the two direction vectors from the 2 given planes (2, 1, -1) and (1, 2, 1) and taking the cross product between them to get (3, 3, 3). I then used this directional derivative to get an equation of a plane through the point (2, 1, -1) like so: 3(x - 2) + 3(y - 1) + 3(z + 1) = 0. However, my answer is x + y + z = 3 and the correct answer is x - y + z = 0. What am I doing wrong?

A: You made a mistake in the cross product.   It should be (3,-3,3).


text:
Q: How to read phone state over bluetooth I try to develop an application that connect to mobile phone and read its phone state (incoming call, outgoing call etc.) like a smart watch. I used a smartwatch and connect to my phone, then open android studio to look at logcat. I understand the watch using bluetooth Obex service,Hfp,a2dp Rfcomm services but I didn't find any example or instructions for using them.
how can i do?
thanks.

A: To know the states kindly use the BluetoothHeadsetClient class. This class contains the necessary function to know the phone state (incoming call, outgoing call etc.)


text:
Q: How can I access an NSMutableArray in a different class? I declare the following in ViewController.h
@property (nonatomic, strong) NSMutableArray *locations;

and the following in ViewController.m
@implementation GHViewController
@synthesize locations;
...
for (FSFourSquareVenueObject *object in array) {
        locations = [[NSMutableArray alloc] init];
        [locations addObject:object.locationName];
        NSLog(@"%@", locations);
    }

This successfully logs all the string locations that have been placed in the locations NSMutableArray.  How can I access this NSMutableArray in a different class?
I am trying to access it in my TableViewController class in order to display all the elements in the array.  I have tried importing the ViewController.h file into my TableViewController.h file, yet I still cannot access the array from the ViewController class.

A: Remove the line
locations = [[NSMutableArray alloc] init];

from your for loop and place it somewhere like viewDidLoad or init. You're wiping out your array every time before adding a new object.
To access a single object across classes, you want to look into creating a singleton. There are many tutorials online.

A: Do as @Stonz2 suggests, but also modify your headers as follows:
In GHViewController.h:
@property (nonatomic, strong) NSArray *locations;

In GHViewController.m
@implementation GHViewController
@synthesize locations;
...
NSMutableArray *array = [[NSMutableArray alloc] init];
for (FSFourSquareVenueObject *object in array) {
    [array addObject:object.locationName];
    NSLog(@"%@", array);
}
self.locations = [array copy];

You can then access the array from another class using GHViewController -locations. You can edit the locations using the following snippet (or by creating a similar method in GHViewController):
NSMutableArray *array = [gh_viewController.locations mutableCopy];
[array addObject: newLocation];
gh_viewController.locations = [array copy];

Exposing a mutable array allows other class to modify the array without notifying GHViewController and vice versa. This can lead to unpredictable and hard to debug problems, such as if GHViewController removes some elements while TableViewController is iterating through all the objects. Using a non-mutable array prevents these sorts of bugs and ensures everyone has a consistent view of what's inside.


text:
Q: Infer type of object of classes Building a form config builder, want to infer types dynamically, here's the minimal reproduction code
interface Meta {
    optional: boolean
}

class Base<Type = any> {
    readonly _type!: Type
    baseMeta: Meta

    constructor() {
        this.baseMeta = {
            optional: false,
        }
    }

    optional() {
        this.baseMeta.optional = true
        return this;
    }
}

class FieldText extends Base<string> {

}

class FieldNumber extends Base<number> {

}

class Field {
    static text() {
        return new FieldText();
    }

    static number() {
        return new FieldNumber();
    }
}

const fields = {
    fieldText: Field.text(),
    fieldNumber: Field.number(),
    fieldTextOptional: Field.text().optional(),
    fieldNumberOptional: Field.number().optional(),
}

Given code above I want to achieve one of the following types, doesn't matter which one
type ExpectedType = {
    fieldText: string;
    fieldNumber: number;
    fieldTextOptional: number | undefined;
    fieldNumberOptional: number | undefined;
}

Also fine
type ExpectedTypeWithOptionalKeys = {
    fieldText: string;
    fieldNumber: number;
    fieldTextOptional?: number;
    fieldNumberOptional?: number;
}

I've gotten to infering types, but can't figure out why the optional property is not taken in consideration
type ExtractFieldType<O, T> = O extends true ? T | undefined : T;

type SchemaType<T extends Record<string, Base>> = {
    [Property in keyof T]: ExtractFieldType<T[Property]['baseMeta']['optional'], T[Property]['_type']>;
};

type Schema = SchemaType<typeof fields>;

type Schema results in:
type Schema = {
    fieldText: string;
    fieldNumber: number;
    fieldTextOptional: string;
    fieldNumberOptional: number;
}

this O extends true ? T | undefined : T always returns T, doesn't take actual value of optional into consideration
EDIT:
after a bit of fumbling around with @kelly's answer for providing a value to the optional function here's the end result:
    optional<T extends boolean>(value?: T): Base<Type, T> {
        const optional = typeof value === 'boolean' ? value : true;
        this.baseMeta.optional = optional as Optional;
        return this as unknown as Base<Type, T>;
    }

first you can't have a default value as then Typescript get's angry with:
Type 'boolean' is not assignable to type 'T'.
  'boolean' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'boolean'.(2322)

So we simply make value optional and then the rest works pretty much as Kelly explained
except for return this as unknown as Base<Type, T>;
if you remove the as unknown part you get the following error:
Conversion of type 'this' to type 'Base<Type, T>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type 'Base<Type, Optional>' is not comparable to type 'Base<Type, T>'.
    Type 'Optional' is not comparable to type 'T'.
      'Optional' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'boolean'.(2352)

Here's the final working in Typescript Playground

A: The type of optional in Meta is always boolean. You need to store the value in a generic to use later:
interface Meta<Optional extends boolean> {
    optional: Optional;
}

class Base<Type = any, Optional extends boolean = false> {
    readonly _type!: Type
    baseMeta: Meta<Optional>

    constructor() {
        this.baseMeta = {
            optional: false as Optional,
        }
    }

    optional(): Base<Type, true> {
        this.baseMeta.optional = true as Optional; // needs unsafe assert, or alternatively //@ts-ignore
        return this as Base<Type, true>;
    }
}

Then when you change it with optional, trick TypeScript into believing you are returning Base<Type, true> instead.
You only need to change this. Your original solution now works.

Addressing the followup in the comments:
optional<T extends boolean = true>(value: T = true): Base<Type, T> {
    this.baseMeta.optional = value as Optional;
    return this as Base<Type, T>;
}


text:
Q: Как сделать что бы не коммитился уже созданный файл Есть файл который изменяется постоянно при работе самого приложения и его коммитить не нужно. Как сделать чтоб он не коммитился? .gitignore не вариант, так как файл уже создан.

A: Предположим, что у Вас имеется следующая папка с файлами (репозиторий) и некоторое количество  коммитов:

Вы обнаруживаете, что в репозитории лежит файл который совершенно не нужен в проекте.

Исправляем ошибку
Ситуация №1. Ненужный файл уже в коммите
Вам потребуется сначала удалить файл из коммитов. Выполняем команду:
git filter-branch --tree-filter 'rm -f NOOOO.cpp' HEAD

Ссылка на оригинал ответа.
Ситуация №2. Ненужный файл в состоянии stage
Вы выполнили комманду git add * (например) и весь репозиторий оказался в состоянии stage. Команда git status покажет какие файлы в каком состоянии находятся.

В этой ситуации необходимо выполнить git rm --cached NOOOO.cpp или git reset NOOOO.cpp. После выполнения команды получим следующий результат:

Ситуация №3. Ненужный файл в был создан но не попал в поле зрения git
В этой ситуации Вам нужно перейти к следующему пункту :).

Избегаем будущих ошибок
Теперь мы избавились от ненужного файла в коммитах существующих или в области stage. Нужно теперь сделать так, чтобы гит не "видел файл".
Создаем .gitignore (на win можно создать через .gitignore.). добавляем в него следующую строку и сохраняем:
NOOOO.cpp

Теперь нужно, чтобы git проиндексировал gitignore. для этого занесем его в новый коммит:
git add .gitignore
git commit -m "gitignore"

После этого git будет сообщать, что новых файлов нету:

Успешных коммитов!

A: Если вы хотите прекратить отслеживать изменения в каком-либо файл в репозитории git, но файл .gitignore по каким-либо причинам не подходит — например, файл является довольно специфическим для конкретного проекта и на других компьютерах не возникает (скажем, временные тестовые файлы, полезные только единственному участнику), можно воспользоваться файлом .git/info/exclude. Он должен находиться в скрытом внутреннем каталоге git'а, его синтаксис и семантика точно такая же, как и у gitignore. Единственное различие — он является локальным для репозитория, его содержимое видно только его владельцу.
Ещё есть глобальная версия этого файла. Она используется для всех репозиториев пользователя и по умолчанию находится в ~/.config/git/ignore (путь можно изменить настройкой core.excludesFile). Тут целесообразно указывать временные файлы вашей любимой IDE, как пример.
Подробнее про обработку всех подобных файлов: классического .gitignore, а так же вышеупомянутых .git/info/exclude и ~/.config/git/ignore — смотрите руководство gitignore(5). Там же описаны все вариации именования этих файлов.


text:
Q: Android app is not showing installed on emulator and my device I have tried converted my android app from eclipse to android studio project and app is working on testing on emulator and my real device but I couldn't find it when trying to exit the app .. After publishing to the store I got the same issue + app is never open .. after installing I just got uninstall only on google play store .. please help :)
this is app url to the store : https://play.google.com/store/apps/details?id=com.linkedtalents.app&hl=en
Here is my manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.linkedtalents.app"
android:versionCode="10"
android:versionName="1.1" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="17" />
<application
    android:allowBackup="true"
    android:icon="@drawable/launch123"
    android:label="@string/app_name"
    android:largeHeap="true" >
  <activity
  android:name="com.linkedtalents.app.Splash"
  android:theme="@style/AppBaseTheme"
  android:screenOrientation="portrait"
  android:configChanges="locale"
  >

A: it seems that you are missing the intent filter. at least you didnt post it. can you have a look that you have the MAIN LAUNCHER like here? you need exactly one activity that matches this, if you want to be started from a homescreen.
<activity
        android:name="..."
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
</activity>


text:
Q: Stored procedure not inserting data into table I'm trying to implement a stored procedure like this where it's going to compare UserID from another table. If that user id already exists in dbo.user info table, it will insert data into [dbo].[BulkUploadTagDetail] table.
Every time I execute this stored procedure running into an issue that the data doesn't get inserted into my database table.
CREATE PROCEDURE [dbo].[InsertBulkUploadTagDetail]
    (@BulkTagID INT,
     @PortalUserID UNIQUEIDENTIFIER,
     @EmailAddress VARCHAR(256),
     @BulkUploadFileName VARCHAR(256),
     @CreatedOn DATETIME2(7),
     @IsCompleted BIT = 0)
AS
BEGIN
    SET NOCOUNT ON

    IF EXISTS (SELECT UserID
               FROM dbo.UserInfo
               WHERE UserID = @PortalUserID)
    BEGIN
        UPDATE [unp]
        SET [unp].[BulkTagID] = @BulkTagID,
            [unp].[UserID] = @PortalUserID,
            [unp].[EmailAddress] = @EmailAddress,
            [unp].[BulkUploadFileName] = @BulkUploadFileName,
            [unp].[CreatedOn] = GETUTCDATE(),
            [unp].[IsCompleted] = @IsCompleted
        FROM
            [dbo].[InsertBulkUploadTagDetail] unp
        INNER JOIN
            [dbo].[UserInfo] uinfo ON [unp].[UserID] = [uinfo].[UserID]
        WHERE
            [unp].[UserID] = @PortalUserID
    END
    ELSE
    BEGIN
        INSERT INTO [dbo].[BulkUploadTagDetail]
                    ([BulkTagID], [PortalUserID], [EmailAddress],
                     [BulkUploadFileName], [CreatedOn], [IsCompleted])
        VALUES (@BulkTagID, @PortalUserID, @EmailAddress,
                @BulkUploadFileName, @CreatedOn, @IsCompleted)
    END
END


text:
Q: Calculating and adding the totals row in Oracle for multiple columns I am new to sql and oracle. Below is the result of a complicated and time consuming query.
I would like to calculate the sums for col2, col3 and col4. I would like to add a totals row at the end of the table.
Current Output.
id  rate rate2 col2      col3  col4
1   2,3  11    10        36     10
1   2,4  2     229,32    36     229,32
1   3    44    229,32    36     229,32
1   4,5  3,4   165,2     36     90,2
81  1,1  11    30,3      36     30,3
81  2,3  22    10        36     10

Desired Result. (N stands for null)
id  rate rate2 col2      col3  col4
1   2,3  11    10        36     10
1   2,4  2     229,32    36     229,32
1   3    44    229,32    36     229,32
1   4,5  3,4   165,2     36     90,2
81  1,1  11    30,3      36     30,3
81  2,3  22    10        36     10
N   N    N     674,14    216    599,14

I have been doing some searching, i am able to manage this using UNION. However there is performance issue, i am running the same query calculating the totals and appending. Bottom line is i don`t want to run the same time consuming query twice. Is there any other way to manage this ?
Thanks in advance.

A: Probably the simplest method is to use union all:
with q as (
      <your query here>
     )
select q.*
from q
union all
select null, null, null, sum(col2), sum(col3), sum(col4)
from q;

Because Oracle sometimes materializes CTEs, there is not necessarily much impact on performance.
If your complicated query is an aggregation that ends in:
group by id, rate, rate2

Then grouping sets is another option:
group by grouping sets ( (id, rate, rate2), () )

A: You can use CTE and MATERIALIZE hint to fetch the desired output as following:
with cte as (SELECT /*MATERIALIZE*/ <your query after select>)
select c.*
  from cte c
union all
select null, null, null, sum(col2), sum(col3), sum(col4)
  from cte;

The undocumented MATERIALIZE hint uses global temporary table so there will be no or little performance impact.
Cheers!!


text:
Q: Using bash convert a JSON file to JSON Object I have a JSON File as follows :
{
 "IP Address" : " 192.168.43.221 ",
 "OS ":" Ubuntu ",
 "OS Version ": " 16.04.4 ",
 "OS Installed Data ": " Dec 8 23:59 ",
 "Model name ": " AMDA10-5750MAPU with Radeon(tm)HD ",
 "MemTotal ": " 5275728kB ",
 "Hard disk capacity ": " [1.00TB] ",
 "Users ": " ananth "
}

I want to convert the above JSON File into JSON Object only using shell scripting? Can someone help me to do this..
Thanks in advance.

A: Your file is valid as JSON text, as can for example be verified by pasting the contents into https://jsonlint.com
One way to "load" the JSON file into a javascript interpreter would be as follows.  For the sake of specificity, assume the interpreter is v8 or js (JavaScript-C). First, copy the file while prepending something like "x=", e.g.
(echo "x="; cat input.json) > input.js

Now, after starting v8 or js, run: load("input.js")
The variable x will then contain the JSON object.
If you want to trim the key names so that they do not have exterior spaces, you could, for example, run the following jq command:
jq 'with_entries(.key|=(sub("^ +";"")|sub(" +$";"")))' input.json

Object Equality
Based on some comments, it appears you want to check whether the JSON objects in two files are "equal" in the sense of object-equality.
This can be done in a variety of ways.  One simple and tidy way would be to use jq as follows:
jq -s '.[0] == .[1]' file1.json file2.json

An alternative would be to write the files in a "canonical" (i.e., normalized) way so that a text-oriented tool such as diff can be used, e.g.
jq -S . file1.json | sponge file1.json
jq -S . file2.json | sponge file2.json

The -S option causes the keys to be sorted in a fixed order; sponge is inessential here but convenient.


text:
Q: internal, implementation, error,handler method did not return a value, a promise, or throw an error Am trying to get data using postman but am getting handler method did not return a value yet i can console.log results. What might be the problem with my code?
{
    method: 'GET',
    path: '/departments',
    handler: (request, h) => {
        // let results=[];
        connection.query('SELECT * FROM departments', function (Error, results) {
            if (Error) {
                console.log(Error);
                return Error;
            }
            console.log(JSON.stringify(results));
        });
        return h.response(results);
    }
}


text:
Q: How to predict the likelihood a x based on percentage of x I'm trying to understand how likely it is that a variable x (snail) would be found on y (type of food) based on the relative abundance of the food source.
Basically do I find more snails on lettuce because there is more lettuce than carrots or not?
Given the simplified data set below, what is the best way to model this in R?

Site
Snails
Food
Food_Percentage_Abundance

A
4
lettuce
10%

A
48
carrot
80%

A
12
broccoli
4%

B
34
lettuce
10%

C
5
lettuce
13%

I've been reading and learning about modeling functions in R for the past few weeks but don't come from a Stats background so struggling to visualise this.
is it as a simple of Snails ~ Food * Food_Percentage_Abundance and I'm getting confused by the need to include the label or is a more complicated forumla required?
Also, how would I then adapt the model to test the significance of Site as well?
Thanks
I've tried fitting ANOVA, GLM and GAM models, but I'm not actually sure what to expect or how to interpret the results in this case


text:
Q: The method getAccessory(Intent) is undefined for the type UsbManager I am working on a project about android and I am trying to set a connection between device and ADK my problem is .getAccessory(); method. It should be taken from UsbManager class, but eclipse throws following error:
The method getAccessory(Intent) is undefined for the type UsbManager
And my code sample is here:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if(ACTION_USB_PERMISSION.equals(action)){
            synchronized (this) {
                UsbAccessory accessory = UsbManager.getAccesory(intent);
                if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
                    openAccessory(accessory);//q
                }
            }
        }

        else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)){
            UsbAccessory accessory = UsbManager.getAccessory(intent);
            if(accessory != null && accessory.equals(mAccesory)){
                closeAccessory();//q
            }
        }
    }

};

Do you have any idea what to do?
Maybe I am wrong, in this case what can I use for its task?
Edit: JVM cannot see the getInstance() method too which I used in OnCreate(Bundle savedInstanceState).

A: I have just done my project build target 4.0.3 to Google APIs(API lvl 17) and it was solved

A: You have to use UsbManager and UsbAccessory from these imports:
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;

not from
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;

in order to have UsbManager.getAccessory(intent);


text:
Q: Need to setup Subversion in my local box I am using Windows7 and I do lot of Java coding in Eclipse. But I dont have a version control system. I have heard of Subversion being a very popular VCS, so I would like to set it in my local box. Can you please give me some pointers on where to start/look at?
I would like to checkin/checkout files using Eclipse. Please guide me.
Thanks

A: If you're on windows it's difficult not to go with VisualSVN. As for Eclipse you can get an eclipse plugin here

A: Subclipse http://subclipse.tigris.org/ is a plugin for eclipse that allows you to checkout / in files inside of the eclipse IDE.
It doesn't get SVN set up on your machine, you'll need to install svn and set up a repository first, but the integration with eclipse is nice to have.

A: If you're the only person who needs to access the repository, you can create a svn repository on your filesystem and you won't need to install and run a server.
http://vincenthomedev.wordpress.com/2007/10/15/setup-svn-local-repository-step-by-step/
Subclipse is a great SVN plugin for Eclipse, you might also find TortoiseSVN very handy as well. Both are very easy to use.

A: First, you'll need a Subversion repository, which can either be a remote server on the internet (google "free subversion repository"), or a server running locally on your machine, or a machine on your lan. For the last one, you can use VisualSVN Server.
Once with a SVN repository setup, you have to install a SVN client to work with it. I recommend TortoiseSVN for general stuff, but I'm pretty sure Eclipse has SVN support builtin, so once you've setup a repository server, you just have to configure the client on Eclipse to connect to it.


text:
Q: Should I be duplicating Equality methods in the test project? I have read plenty of questions on here about overriding .equals and .hashcode for testing purposes only.
My Domain classes have implemented .equals and .hashcode.  Should I be
1) Duplicating these classes in my test project
or
2) Using the Domain Class .equals in my test project
The only justification I can see for point one is if the .equals and .hascode are different in the test project, however in my case they are not.  Therefore I believe that point two is the answer.
The reason I ask is that I am trying to follow the principle of least astonishment ready for when someone else looks at my code in future.

A: You already answered the question by yourself. If you need two different kind of equality comparisons somewhere in your code  - tests or not - you obviously need to implement two different ones. And if you need only one, implement only one. The DRY principle applies to your whole code base, not just the code outside your tests.
Just make sure you override object.Equals for the comparison which feels most "natural" to the domain object, in the context of the particular program, and give the other equality check a self-describing function name which makes it clearly distinguishable from the former.


text:
Q: No effect with EnvironmentalReverb I am making application with sound effects attached to MediaPlayer, So I got BassBoost working
 BassBoost bassBoost = new BassBoost(0, mp2.getAudioSessionId());
             bassBoost.setEnabled(true);
             BassBoost.Settings bassBoostSettingTemp =  bassBoost.getProperties();
             BassBoost.Settings bassBoostSetting = new BassBoost.Settings(bassBoostSettingTemp.toString());
             bassBoostSetting.strength=1000;
             bassBoost.setProperties(bassBoostSetting);
             if(start2<1000){
                 start2 = (short) (start2 + 100);
                 //setUpBassBostandUI();
                 bassBoost.setStrength((short)start2);
                 System.out.println("short is: "+start2);}
             bassBoost.setStrength((short) start2);
             mp2.attachAuxEffect(bassBoost.getId());

But i cant get Reverb working, I tried PresentReverb and i had no results with it, now i am trying with EnvironmentalReverb and there is no any effect
EnvironmentalReverb eReverb = new EnvironmentalReverb(0, mp2.getAudioSessionId());
            eReverb.setDecayHFRatio((short) 100000);
            eReverb.setDecayTime(100000);
            eReverb.setDensity((short) 100000);
            eReverb.setDiffusion((short) 100000);
            eReverb.setReverbLevel((short) 100000);
            eReverb.setReverbDelay(100);
            eReverb.setEnabled(true);
            mp2.attachAuxEffect(eReverb.getId());
            mp2.setAuxEffectSendLevel(1.0f);

A: Check that whatever you're testing on supports it (it is device-dependent). You can use:
final Descriptor[] effects = AudioEffect.queryEffects();

// Determine available/supported effects
for (final Descriptor effect : effects) {
    Log.d(TAG, effect.name.toString() + ", type: " + effect.type.toString());
}

I can't remember off-hand if the name prints out something useful. You can find the UUIDs here: AudioEffect.java
If it is supported and you are still not hearing anything, you may have to apply it to the global audio session to get it working. That's described here.


text:
Q: Windows Server Tesla/GPU Hosting I have a Windows calculation-intensive solution that uses NVidia's GPGPU (CUDA).
I am looking to host my application on the cloud and expose it via a Web service.
The only host I found was AWS, but it does it on Linux CentOS.
I want to find an online host that supports:
1 - NVidia GPUs, specifically Tesla (Tesla M2090 or Tesla M2075).
2 - Using Windows Server 2008 R2 or 2012.
3 - Virtual or Dedicated.
Are you aware of any host that fits my 3 points above?


text:
Q: How to store multiple checkbox values in reactive form in angular2? I am working on angular2 application and getting problem in storing values of multiple check boxes in form field.
Type script
form : FormGroup;
cities = ["Mohali", "Chandigarh", "Ludhiana", "Amritsar"];
zip_codes = ["282001", "456123", "123456", "140412"];

constructor(private formBuilder : FormBuilder)
{
    this.form = this.formBuilder.group({
       cities   : this.formBuilder.array(["Mohali", "Amritsar"]),
       zip_codes : this.formBuilder.array(["456123"])
    });
}

HTML

    <input type="checkbox" formControlName="cities" value="city">
    {{city}}

    <inbput type="checkbox" formControlName="zip_codes" value="zipCode">
     {{zipCode}}

I want to store checked cities and zip_codes in form field and when I have default values in form field then the values are in array will be checked automatically.

A: I liked very much the answer of @yurzui
But had an issue with getting the values back .. So..
My solution - solved it for Angular 5 with Material View
The connection is through the

formArrayName="notification"
(change)="updateChkbxArray(n.id, $event.checked, 'notification')"

This way it can work for multiple checkboxes arrays in one form.
Just set the name of the controls array to connect each time.

constructor(
  private fb: FormBuilder,
  private http: Http,
  private codeTableService: CodeTablesService) {

  this.codeTableService.getnotifications().subscribe(response => {
      this.notifications = response;
    })
    ...
}

createForm() {
  this.form = this.fb.group({
    notification: this.fb.array([])...
  });
}

ngOnInit() {
  this.createForm();
}

updateChkbxArray(id, isChecked, key) {
  const chkArray = < FormArray > this.form.get(key);
  if (isChecked) {
    chkArray.push(new FormControl(id));
  } else {
    let idx = chkArray.controls.findIndex(x => x.value == id);
    chkArray.removeAt(idx);
  }
}

 0">
    Notifications to send:

      <mat-checkbox class="checkbox-margin" (change)="updateChkbxArray(n.id, $event.checked, 'notification')" value="n.id">{{n.description}}</mat-checkbox>

At the end you are getting to save the form with array of original records id's to save/update.

Will be happy to have any remarks for improvement.

Here is the Gist

A: One way would be like this:
1) Setup FormArray fields with false default values
this.form = this.formBuilder.group({
  cities   : this.formBuilder.array(this.cities.map(x => !1)),
  zip_codes : this.formBuilder.array(this.zip_codes.map(x => !1))
});

2) The template will look like this:

  <input type="checkbox" [formControlName]="i">
  {{city}}

  <input type="checkbox" [formControlName]="i">
  {{zipCode}}

3) Submit form
convertToValue(key: string) {
  return this.form.value[key].map((x, i) => x && this[key][i]).filter(x => !!x);
}

onSubmit() {
  const valueToStore = Object.assign({}, this.form.value, {
    cities: this.convertToValue('cities'),
    zip_codes: this.convertToValue('zip_codes')
  });
  console.log(valueToStore);
}

4) Default values
const defaultCities = ["Mohali", "Amritsar"];
const defaultZipCodes = ["456123"];
this.form = this.formBuilder.group({
  cities: this.formBuilder.array(this.cities.map(x => defaultCities.indexOf(x) > -1)),
  zip_codes: this.formBuilder.array(this.zip_codes.map(x => defaultZipCodes.indexOf(x) > -1))
});

Plunker Example


text:
Q: Why disallow subclasses to override superclass properties with a derived type? Swift programming language allows subclasses to override superclass properties with the same type T, but not with a different type S, not even when S derives from T. Here is a quote from https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html:

You must always state both the name and the type of the property you
  are overriding, to enable the compiler to check that your override
  matches a superclass property with the same name and type.

When overriding methods, Swift does allow an overriding subclass method to return a type that derives from the superclass method return type.
My question is: what is the motive for disallowing subclasses to override superclass properties with a type S that derives from T?

A: This is not actually limited to Swift. This would break polymorphism. See the subtyping rules on wikipedia: Subtyping
Basically, consider the following example:
class A {
   var x: NSObject?
}

class B: A {
   override var x: NSNumber?
}

and consider:
let b = B(x: 1)
let a: A = b // it's a subclass, polymorphism allows to assign it to A
a.x = NSObject() // let's assign NSObject() because A.x takes NSObject
print(b.x) // b.x should be a NSNumber now but we have assigned a NSObject?

You have to realize that a property is a combination of two functions, a setter and a getter. You could add a more specific type (covariant type) to the getter (return value of a function) but you cannot do that for a setter (parameters of an overriden function require contravariance).
That also tells you that this would work with a readonly property:
class A {
    var x: NSObject? {
        return NSObject()
    }
}

class B: A {
    override var x: NSNumber? {
        return NSNumber()
    }
}


text:
Q: Consuming WCF Service with Digest authentication from Java I want to create a client in Java that connects to a web service which requires Digest authentication. Since I am not familiar with java and java stack, I've made a research and came across jax-ws, axis2, xcf, and metro. I have learned JAX-WS is an API and there is a  reference implementation in the JDK but it lacks the digest authorization support.
My first attempt was to use axis2 since there is a built-in support for it in the Eclipse IDE. The following code seems to follow digest authentication workflow but somehow it still fails the authorization in the end.
Service1Stub stub = new Service1Stub();

HttpTransportProperties.Authenticator authenticator = new Authenticator();
List<String> authSchemes = new ArrayList<String>();
authSchemes.add(Authenticator.DIGEST);
authenticator.setAuthSchemes(authSchemes);
authenticator.setUsername("doman user");
authenticator.setPassword("domain password");
authenticator.setPreemptiveAuthentication(true);
Options options = stub._getServiceClient().getOptions();
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, org.apache.axis2.Constants.VALUE_FALSE);

GetData getData = new GetData();
getData.setValue(25);
GetDataResponse data = stub.getData(getData);
System.out.println(data.getGetDataResult());

My second attempt was to use metro framework but I get some errors related to JAXB versions.
java.lang.LinkageError: JAXB 2.1 API is being loaded from the bootstrap classloader, but this RI needs 2.2 API.
I have to use JDK 1.6.0_03 so I guess this is happening because of a JDK version mismatch, but I also don't want to use the suggested "endorsed directory mechanism" because it might cause lots of troubles during deployment.
I am totally lost and I am looking for the simplest, quickest and up-to-date way of consuming a web service that requires Digest authentication in Java? Preferably with as little as dependencies possible.

A: Java classloading is a mess, sorry. The root cause is that there are no strong names like there are in the .NET world, and therefore the runtime linker takes whatever match comes first on the classpath, regardless of whether that's the library version that the code was compiled against. The OSGi system solves this problem, but it never gained mainstream adoption.
The error message you cited:

java.lang.LinkageError: JAXB 2.1 API is being loaded from the bootstrap classloader, but this RI needs 2.2 API.

is uncharacteristically useful and specific, most of the time what happens instead is that you're left staring at a NoSuchMethodError or something of the sort. Over time, you learn to recognise these as library version mismatches. In this case, the library author(s) have written code to recognize a common error case and print a better error message (bless 'em).
Rant over, here's some info that I hope will set you on the right track:

*

*Java classloaders are hierarchical and resolution is bottom-up

*but there's a blessed class loader at the root of the hierarchy that's responsible for loading the core runtime library

*vendor shenanigans have led to a lot of stuff getting included in the core runtime library that really shouldn't have been in there, as it's a shortcut to becoming dominant in an otherwise Darwinistic selection process. JAXB is one of these things, as you've just found out. JAXB2 is actually pretty decent, but it evolves independent of the core runtime and, well, here we are.

*the JDK and JRE installation has a folder called lib\endorsed where you can add JAR files that need to be loaded by the root loader, bypassing even what's in rt.jar.

In summary, if you manually add the 2.2 version of the JAXB library to %JAVA_HOME%\lib\endorsed, then it should override the included 2.1 version and your web service client will deploy. This will have to happen on every system that will run the web service client, until the JDK is updated to a 7.x version that does included JAXB 2.2. If the same JVM is running other JAXB based applications, these may or may not break as a result.
Yes, this is painful. A tangent that you could investigate is to deliberately use an older version of Metro that's built for JAXB 2.1. So long as you're bound to deploying on 1.6.0_03, this may well be the better option, despite losing some of the recent improvements in Metro.
Updated: here's a blog post on this topic. It contains some links to further information.

A: Metro framework was way too complicated to configure and documents that I have found were incomplete. So I've done it with using Apache Axis2.
Steps to follow:

*

*Download and extract Apache Axis2 binaries.

*Reference to all jar files

*Go to /bin folder and use wsdl2java to generate client code.

wsdl2java -S src -uri "wsdl_file_location"

Copy everything under the src folder to your java application and connect to the service as follows:
//Fictious is the name of the web service
FictiousStub stub = new FictiousStub("servicelocation/fictiousService.php");

HttpTransportProperties.Authenticator authenticator = new Authenticator();
List<String> authSchemes = new ArrayList<String>();
authSchemes.add(Authenticator.DIGEST);
authenticator.setAuthSchemes(authSchemes);
authenticator.setUsername("admin");
authenticator.setPassword("12345");
authenticator.setPreemptiveAuthentication(true);
Options options = stub._getServiceClient().getOptions();
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, org.apache.axis2.Constants.VALUE_FALSE);


text:
Q: Refactoring variables and function names in MATLAB? In eclipse you can refactor all variables and function names by hitting CTRL+SHIFT+R which is great. I am editing someone else's matlab script and would like to change a lot of their varaibles and I was wondering if there is something similar in matlab?

A: Matlab editor in 2012a allows you to press shift + enter to change all of the common variables in a script or function when you start editing one of them.
Otherwise I would suggest find and replace.


text:
Q: How to develop in MVC (C#) with existing database I'm building an application that will use a large database that's currently hosted on Azure SQL. I also want to use ASP.net Identity. Additionally, my local machine cannot connect to the Azure SQL database due to security restrictions (I can't remove these, they are corporate IT policies).
When developing, do either of the following make sense? Or is there another option that I'm unaware of?

*

*Add the fields from the large database, and maybe a few rows of sample data, to my localdb that's being used by default by Visual Studio? If I do this, how do I migrate over to the existing Azure database when it's time to go live?

*Host the development application on Azure. This wouldn't be ideal, given that I'd need to upload the application with every change.

A: *

*You could do that for small scale testing and demonstration purposes yes. Essentially to interact with the database in ASP you create an instance of the database with the reference link to the local one. Providing they are identical, you could simply just change the link to the company database when it's time to go live. You should be careful however as working with relatively small datasets means everything will run relatively smoothly and quickly but if your coding is sloppy, it could slow the entire thing down with big data sets.

*As for developing, I would personally develop on a small scale yourself locally until you're happy with the result. However, before you do a full scale launch, I would do a pilot launch in a small section to highlight any bugs you may have pushed and halt this on azure. Then after you've ruled out the obvious bugs, you've got a much safer launch.

A: to work in an develop-release separated environment:

*

*you need a intranet copy of remote database first, then use code first approach to continue working,

*reverse your database to code-first:

*

*https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

*https://cmatskas.com/scaffolding-dbcontext-and-models-with-entityframework-core-2-0-and-the-cli/

*https://wildermuth.com/2017/12/20/Reverse-Engineering-Existing-Databases-in-Entity-Framework-Core-2

*Enable database migrate: https://msdn.microsoft.com/en-us/library/dn579398(v=vs.113).aspx

*Add identity framework to intranet database with code first: https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project

*carefully maintenance migration code in later tasks, remote database will be auto-updated after your code is released


text:
Q: jQuery UI Slider - Custom Slide Button that changes based on selection I have a slider that is working as needed, but I am missing one step. I need the custom slider button to change based on what step it is on. I have tried multiple things with no luck. Any thoughts?
Here is a link to the fiddle

Slide 1

Slide 2

Slide 3

Nav 1

Nav 2

Nav 3

A: You could use the css method to update the background according to the slides position. Updating the code in your fiddle, you would have something like this:
$("#slider").slider({
  value: 1,
  min: 1,
  max: 3,
  step: 1,
  change: function(event, ui) {
    $('.slide').fadeOut('500');
    switch(ui.value) {
      case 1:
        $('.slide.first').delay('400').fadeIn('500');
        $('.ui-slider-handle').css('background', "url('/img/logo.png') no-repeat");
        break;
      case 2:
        $('.slide.second').delay('400').fadeIn('500');
        $('.ui-slider-handle').css('background', "url('https://placehold.it/40x40') no-repeat");
        break;
      case 3:
        $('.slide.third').delay('400').fadeIn('500');
        $('.ui-slider-handle').css('background', "url('https://placehold.it/40x40/ff0000/000000') no-repeat");
        break;
    }
  }
});

I'm using placeholder images, which you can update at your discretion.
Demo