text:
Q: How does the voltage remain constant at secondary side of flyback SMPS when secondary current is decreasing linearly with time?
Continous Mode of Flyback SMPS

A: Voltage does not stay constant. There will be ripple voltage that depends on the output capacitor ESR and capacitance.

A: It's quite simply down to the formula for an inductor: -
$$V = L\dfrac{di}{dt}$$
When the fly-back transformer's primary is being "charged" with energy, a DC voltage is switched in parallel and this gives rise to a ramping current. In the 2nd half of the process, the energy is released and the current ramps back towards zero and, the rate of change of this current (\$\dfrac{di}{dt}\$) IS the output voltage produced divided by the turns ratio: -

The above is for a DCM fly-back circuit but the same is true of CCM. There are some worked examples on this page.


text:
Q: Make a canvas line with a point at the end I am trying to make the end of a canvas into a point (sort of like an arrow, except that the sides should not come out beyond the width of the line...see the following picture for an example of how the line end should look).
See the following picture for an example of how the line end should look.

I was experimenting with line caps, but the only available caps are 'round' or 'square' (http://www.w3schools.com/tags/canvas_linecap.asp).
The following fiddle is the line that I am trying to give points to the end of.
http://jsfiddle.net/699ktkv8/
The code is below as well:
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 200, 100, 200, 20);
ctx.lineWidth=10
ctx.stroke();

</script>

</body>

A: There is no such feature in canvas unfortunately. You will have to manually calculate the outcome angle of the line (which means you need to implement the Bezier math).
Then use the width of the line to draw the cap yourselves based on that angle.
Step 1 - find direction
Lets make it a little more challenging by using one end that isn't 90° up or to the side:

var ctx = document.querySelector("canvas").getContext("2d");

// draw as normal
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 170, 70, 200, 20);
ctx.lineWidth=10
ctx.stroke();

// get two points from the end
var pt1 = order3(20, 20, 20, 100, 170, 70, 200, 20, 0.98);
var pt2 = order3(20, 20, 20, 100, 170, 70, 200, 20, 1);

// show direction
ctx.lineWidth = 2;
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(pt1.x, pt1.y);
ctx.lineTo(pt1.x + (pt2.x - pt1.x) * 10, pt1.y + (pt2.y - pt1.y) * 10);
ctx.stroke();

//B(t) = (1-t)^3 * z0 + 3t (1-t)^2 * c0 + 3 t^2 (1-t) * c1 + t^3 * z1 for 0 <=t <= 1
function order3(z0x, z0y, c0x, c0y, c1x, c1y, z1x, z1y, t) {

  var tm1 = 1 - t,        // (1 - t)
    tm12 = tm1 * tm1,     // (1 - t) ^ 2
    tm13 = tm12 * tm1,    // (1 - t) ^ 3
    t2 = t * t,           // t ^ 2
    t3 = t2 * t,          // t ^ 3
    tmm3 = t * 3 * tm12,  // 3 x t * (1 - t) ^ 2
    tmm23 = t2 * 3 * tm1, // t ^ 2 * 3 * (1 - t)
    x, y;

  x = (tm13 * z0x + tmm3 * c0x + tmm23 * c1x + t3 * z1x + 0.5) | 0;
  y = (tm13 * z0y + tmm3 * c0y + tmm23 * c1y + t3 * z1y + 0.5) | 0;

  return {
    x: x,
    y: y
  }
}
<canvas width=220 height=100 />

Update Or as markE points, you could calculate it from the control points (my bad, I forgot about this completely - thanks markE) - This is probably the better approach for most cases compared to using the "t" approach.
I'll include it here for the sake of completeness:
// calculate the ending angle from the two last nodes (cp2 and end point)
var dx = pt2.x - cp2.x;   // assumes points and control points as objects
var dy = pt2.y - cp2.y;
var angle = Math.atan2(dy, dx);

Update end
Step 2 - find angle and distance
We need to calculate the actual angle so that we can use that for the base of the arrow:
// get angle
var diffX = pt1.x - pt2.x;   // see update comment above
var diffY = pt1.y - pt2.y;
var angle = Math.atan2(diffY, diffX);
var tangent = Math.atan2(diffX, -diffY);

(shown slightly offset on purpose)
Step 3 - draw cap
Now we have enough information to draw a cap on the line:

var ctx = document.querySelector("canvas").getContext("2d");

// draw as normal
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 170, 70, 200, 20);
ctx.lineWidth=40
ctx.stroke();

// get two points from the end
var pt1 = order3(20, 20, 20, 100, 170, 70, 200, 20, 0.98);
var pt2 = order3(20, 20, 20, 100, 170, 70, 200, 20, 1);
var diffX = pt1.x - pt2.x;
var diffY = pt1.y - pt2.y;
var angle = Math.atan2(diffY, diffX);
var tangent = Math.atan2(diffX, -diffY);
var lw = ctx.lineWidth * 0.5 - 0.5;

// draw cap
ctx.beginPath();
ctx.moveTo(pt2.x + lw * Math.cos(tangent), pt2.y + lw * Math.sin(tangent));
ctx.lineTo(pt2.x - lw * Math.cos(tangent), pt2.y - lw * Math.sin(tangent));
ctx.lineTo(pt1.x - lw * Math.cos(angle), pt1.y - lw * Math.sin(angle));

ctx.fill();

// due to inaccuracies, you may have to mask tiny gaps
ctx.lineWidth = 1;
ctx.stroke();

//B(t) = (1-t)^3 * z0 + 3t (1-t)^2 * c0 + 3 t^2 (1-t) * c1 + t^3 * z1 for 0 <=t <= 1
function order3(z0x, z0y, c0x, c0y, c1x, c1y, z1x, z1y, t) {

  var tm1 = 1 - t,        // (1 - t)
    tm12 = tm1 * tm1,     // (1 - t) ^ 2
    tm13 = tm12 * tm1,    // (1 - t) ^ 3
    t2 = t * t,           // t ^ 2
    t3 = t2 * t,          // t ^ 3
    tmm3 = t * 3 * tm12,  // 3 x t * (1 - t) ^ 2
    tmm23 = t2 * 3 * tm1, // t ^ 2 * 3 * (1 - t)
    x, y;

  x = (tm13 * z0x + tmm3 * c0x + tmm23 * c1x + t3 * z1x + 0.5) | 0;
  y = (tm13 * z0y + tmm3 * c0y + tmm23 * c1y + t3 * z1y + 0.5) | 0;

  return {
    x: x,
    y: y
  }
}
<canvas width=240 height=100 />

The actual angle at the end depends on what point near the end you choose (not the actual end point, ie. t=1). You may have to calculate the total line length and use that as basis of how much t shall be.
You may also run into situations where the angle is not entire correct and small gaps appear.
You can either mask these gaps by applying a stroke, or offset the cap a little based on the previous calculated angle/direction (use linear interpolation as in step 1, just with negative t), or the only other way to get it accurate is to manually calculate the walls of the line etc., e.g. treat it as a polygon and fill it as a single object.

A: @KenFrystenberg has answered your question well.
Here's an interesting math note that simplifies the calculations.
The ending angle (and starting angle) of a cubic Bezier curve can be calculated directly from the control points:
// define 4 cubic Bezier control points
var cp0={x:20,y:20};
var cp1={x:20,y:100};
var cp2={x:170,y:70};
var cp3={x:200,y:20};

// calculate the ending angle from cp2 & cp3
var dx=cp3.x-cp2.x;
var dy=cp3.y-cp2.y;
var angle=Math.atan2(dy,dx);

Here's example code and a demo about this math note:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var cp0={x:20,y:20};
var cp1={x:20,y:100};
var cp2={x:170,y:70};
var cp3={x:200,y:20};

ctx.lineWidth=10;

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 170, 70, 200, 20);
ctx.lineWidth=20
ctx.stroke();

ctx.beginPath();
ctx.arc(200,20,3,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle='red';
ctx.fill();

var dx=cp3.x-cp2.x;
var dy=cp3.y-cp2.y;
var angle=Math.atan2(dy,dx);

var x=cp3.x+15*Math.cos(angle);
var y=cp3.y+15*Math.sin(angle);

ctx.beginPath();
ctx.moveTo(cp3.x,cp3.y);
ctx.lineTo(x,y);
ctx.lineWidth=1;
ctx.strokeStyle='red';
ctx.stroke();
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set up Symfony2 on Cloud9? I've setup Symfony2 on Cloud9 following this Symfony on Cloud9 Guide.  When I preview the running application at (https://appname-username.c9users.io) it just serves up my file list:
Index of /
Name    Last modified    Size    Description
LICENSE
etc...

*

*Have I failed to setup a configuration somewhere?

*Should I be pointing my browser to a different url?

Thank you for help!

*

*I've followed this Symfony on Cloud9 Guide multiple times.

*I have this issue regardless of whether I install the acmedemo.

*I haven't been able to find the answer in The Symfony Book.

*This Stackoverflow did not help: Symfony framework on Cloud9.

A: Here is how you can install Symfony 3.2 successfully:
Follow the official installation documentation here: http://symfony.com/doc/current/setup.html
sudo mkdir -p /usr/local/bin
sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony
sudo chmod a+x /usr/local/bin/symfony

Create a new Symfony project:
symfony new my_project_name

Move content of project directory one level higher and delete that empty directory:
mv my_project_name/* .
rm -rf my_project_name

As Symfony is serving its content from the web directory, we need to modify the apache config using nano (a text editor):
sudo nano /etc/apache2/sites-enabled/001-cloud9.conf

Change the DocumentRoot to the following:
// Change this line
DocumentRoot /home/ubuntu/workspace
// To this
DocumentRoot /home/ubuntu/workspace/web

To save the file, Write Out, Enter, then Close (or press F2, Y, then Enter).
Open web/app.php and toggle your project to production mode:
// Change this line
$kernel = new AppKernel('prod', false);
// To this
$kernel = new AppKernel('prod', true);

Save.
Start your Cloud9 server as usual with the green "Run Project" button.
Happy coding!

A: The New Run Configuration window clearly says:
Starting Apache httpd, serving https://appname-username.c9users.io/web/app_dev.php.
Point browser at:
https://appname-username.c9users.io/web/app_dev.php


text:
Q: H264 RTP video stream corrupted with MediaCodec I am able to see the video playing in my TextureView but it is fairly corrupted. I have verified that I am receiving complete packets in the correct order. I have been able to parse the RTP header correctly. I believe my issue is related to the SPS and PPS and the MediaCodec.
My understanding is that you are supposed to strip the RTP header from the message and insert an RTP start code of 0x00000001 to the start of your message so that your input buffer to the decoder is of the form 0x00000001[sps] 0x00000001[pps] 0x00000001[video data].
My confusion is that the MediaCodec appears to require a MediaFormat with the SPS and PPS manually defined separately. I have found this example that I am currently using along with the message format I have defined above:
MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height);

// from avconv, when streaming sample.h264.mp4 from disk
byte[] header_sps = {0, 0, 0, 1, 0x67, 0x64, (byte) 0x00, 0x1e, (byte) 0xac, (byte) 0xd9, 0x40, (byte) 0xa0, 0x3d,
            (byte) 0xa1, 0x00, 0x00, (byte) 0x03, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x3C, 0x0F, 0x16, 0x2D, (byte) 0x96}; // sps
byte[] header_pps = {0, 0, 0, 1, 0x68, (byte) 0xeb, (byte) 0xec, (byte) 0xb2, 0x2C}; // pps

format.setByteBuffer(CSD_0, ByteBuffer.wrap(header_sps));
format.setByteBuffer(CSD_1, ByteBuffer.wrap(header_pps));

As you can see, I am not providing the MediaFormat with the SPS and PPS from my video stream, but instead using a hard coded set from an internet example. I've tried to find sources explaining how to extract the SPS and PPS from a packet, but haven't been able to find anything.
Questions:
Am I supposed to strip the SPS and PPS from my buffer before passing it to the MediaCodec if the MediaFormat is already being provided the SPS and PPS?
How do you correctly parse the SPS and PPS from a message?
Here's the first few bytes of one of my RTP packets with the header included:

80 a1 4c c3  32 2c 24 7a  f5 5c 9f bb  47 40 44 3a  40 0 ff ff  ff ff
  ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff
  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff
  ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff 0 0 1  c0 0 71 80  80
  5 21 0  5d d6 d9 ff  fb 12 c4 e7  0 5 5c 41  71 2c 30 c1  30 b1 88 6c
  f5 84 98 2c  82 f5 84 82  44 96 72 45  ca 96 30 35  91 83 86 42  e4 90
  28 b1  81 1a 6 57  a8 37 b0 60  56 81 72 71  5c 58 a7 4e  af 67 bd 10
  13 1 af e9  71 15 13 da  a0 15 d5 72  38 36 2e 35  11 31 10 a4  12 1e
  26 28  40 b5 3b 65  8c 30 54 8a  96 1b c5 a7  b5 84 cb a9  aa 3d d4 53
  47 0 45 34  55 0 ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff
  ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff
  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff
  ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff
  ff ff bf 9  95 2b 73 93  4e c3 f9 b1  d0 5f f5 de  c9 9e f7 f8  23 ab
  a5 aa

A: Yes you are correct that the mediacodec requires the SPS and PPS to be initialized first. You must extract the SPS/PPS from the SDP response which is the reply from the DESCRIBE command sent to the server(camera) during the RTSP handshake. Within the SDP response there is a sprop parameter set which contains the SPS/PPS. You can see them on WireShark as:
Media format specific parameters: sprop-parameter-sets=Z2QAKKwbGoB4AiflwFuAgICgAAB9AAAOph0MAHz4AAjJdd5caGAD58AARkuu8uFAAA==,aO44MAA=

They are separated by comma and must be decoded using Base64. See this for an explanation: How to decode sprop-parameter-sets in a H264 SDP?


text:
Q: ASP.NET Core 'Multipart body length limit 16384 exceeded' error I am using ASP.NET Core 1.1. and I am trying to upload files using JQuery AJAX but I keep getting the error: "Multipart body length limit 16384 exceeded"
Reseach told me to add this to my Startup.js file:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.Configure<FormOptions>(Option =>
    {
        Option.MultipartBodyLengthLimit = 200000000;
    });
}

But I still keep getting the error at
foreach (File file in Request.Form.Files)

I see that that the MultipartBodyLengthLimit is updated at startup but it doesn't seem to hold the updated value somehow when the app runs.
Does this even work in ASP.NET Core or do I need to use another way to upload files using jQuery in ASP.NET Core?


text:
Q: Visual Studio Graphics Debugger I cant get the Graphical Debugger in VS 2012 Ultimate to work, & I have no idea why.
The debugger starts ok, but when I hit the print screen button, the debugger just says its waiting for DX to draw frames. [even after I exit]
I am sure the draw refers to the Present() in the swap chain. I am calling it [thats why you see the box down there]
Is there some bug I need to be aware of?
Edit:
I think the render target might be related to OMSetRenderTargets().
I called it exactly as the SDK sample did, so I don't know what else to think.

A: I'm a developer on the Visual Studio graphics diagnostic tools at Microsoft. I'm fairly new on the team, and I don't believe that any previous team members were actively watching Stack Overflow, so sorry about the wait on this question.
As it's been a few months I'm guessing that you might not have the repro around anymore. So such this might be a bit hard to diagnose here and now. From what you shared it looks like the playback engine (which we use to capture and replay DirectX data while the application is running) crash while trying to collect data on your application. Sadly with the first release of our tool (In VS 2012) stability issues of this type are more common then we would like. Simply a function of how we did collection on something as complex as DirectX. However since then, particularly with Update 2, we've made some very big strides with compatibility and stability. As a first step I'd make sure that you have all the VS updates installed as Update 2 was a big upgrade for the graphics diagnostic tools in particular (Preview of 2013 as well if you have access to that).

A: Why don't you use PIX instead http://www.youtube.com/watch?v=-3PISvNTeB0
PIX Tutorial


text:
Q: How to parse XML from assets, keep it and add to ListVIew? I was to told to parse XML file. The task is to parse XML from assets folder and somehow put it into ListView. Moreover, xml contains links and when you click on particular ListView item, you should get file from corresponding link (you should get parsed CSV file, which contains in link. And this parsed CSV must be stored in local database, but that's whole another story)
Here's my XML:
<Table>
    <TableItem>
        <id>1</id>
        <title>bla-bla-bla</title>
        <url>http://thelink</url>
        <type>CSV</type>
    </TableItem>
    <TableItem>
        <id>2</id>
        <title>bla-bla-bla x2</title>
        <url>thelink</url>
        <type>CSV</type>
    </TableItem>
    <TableItem>
        <id>3</id>
        <title>bla-bla-bla</title>
        <url>the link</url>
        <type>CSV</type>
    </TableItem>

    .....
    </Table>

How do I parse such XML? I've tried XMLparser already and it didn't work for me. And now i've trying SAXParser and I need to describe Handler propperly.
public void parseThat() throws IOException, ParserConfigurationException, SAXException {
    InputSource inputSource = new InputSource(this.getActivity().getAssets().open("Table.xml"));
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.parse(inputSource);
}

And here's the Handler:
public class XmlContentHandler extends DefaultHandler
{
    List<TableItem> items = new ArrayList<TableItem>();
    private boolean inTableItem = false;
    private boolean inTitle = false;
    private boolean inUrl = false;
    private boolean inType = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if(localName.equals("TableItem"))
        {

        }
    }

    class TableItem{
        String title;
        String type;
        String url;

        private TableItem(String title, String type, String url)
        {
            this.title = title;
            this.url = url;
            this.type = type;
        }
    }
}

Any help and ideas would be much appreciated!


text:
Q: Routing Jetty http traffic to https I am trying to make Jetty 8.0 secure.
I have followed all the instruction mentioned here.
But I am not able to redirect http requests to https. Can some one help me in this?
I do get valid response when I do https:/// but do not get any response when I do http://:9393/.
9393 is the port where the application is configured to run.
Under the heading "Redirecting http requests to https" it says

To redirect http to https, the webapp should indicate it needs CONFIDENTIAL or INTEGRAL connections from users. This is done in web.xml:

Which web.xml they are referring to? The one which belongs to the application deployed?

A: Yes, the web.xml in your web application. Look at this if you haven't before: http://wiki.eclipse.org/Jetty/Howto/Configure_SSL#Redirecting_http_requests_to_https


text:
Q: An equivalent condition for a rectangular band. This is Exercise 1.9.4 of Howie's "Fundamentals of Semigroup Theory".

Definition: A semigroup $S$ is a rectangular band if $aba=a$ for all $a,b$ in $S$.
Lemma: Let $S$ be a rectangular band. Then every element of $S$ is an idempotent.

Proof: Let $a$ be an element of a rectangular band $S$. Then $a^3=a$ implies $a^4=a^2$. But $a^4=a(a^2)a=a$. Hence $a^2=a$.$\square$
The Question:

Show that a semigroup $S$ is $(A)$ a rectangular band if and only if $(B)$ for all $a,b$ in $S$, $ab=ba$ implies $a=b$.

My Attempt:
For $(A)\implies (B)$: Let $S$ be a rectangular band. Let $a, b\in S$ such that $ab=ba$. Then
$$\begin{align}
a&=aba \\
&= (ba) a \\
&=ba \\
&=b(ba) \\
&=bab \\
&=b.
\end{align}$$

But I don't know how to show $(B)\implies(A)$.

Please help :)

A: Elements $a$ and $a^2$ commute, so by $(B)$ we have $a^2 = a$ (every element is an idempotent).
We infer that elements $a$ and $aba$ commute:
$$ abaa = aba = aaba, $$
hence $(B)$ implies $aba = a$.


text:
Q: Do "Ors" Evaluate The Whole Expression? Say I have the following statement logic (I'll be using VBA for this example, but it also pertains to other languages)
x = 1
y = 2
z = 1000
If x = 1 Or y = 2 Or z = 4 Then
     Execute Code
End

Does the compiler or executing program find that the first value is true, and then continue to Execute Code or does it finish off the rest of the statement?

A: I can't speak for VBA, but I can say that it is language specific. In some languages, the programmer has the ability to use "short-circuit" AND and OR expressions. Short-circuiting is the process of no longer evaluating a boolean expression if the result has already been determined.
If using a short-circuited AND, the boolean operation stops early if a FALSE is found. If using a short-circuited OR, the boolean operation stops early if a TRUE is found.
For example, in Java:
a || b is a short-circuited OR
a | b is a non-short-circuited OR
a && b is a short-circuited AND
a & b is a non-short-circuited AND
Some may ask, "why would I ever use a non-short-circuited AND or OR?" The reason for this comes when you are calling a function that returns a boolean that you want to run in every case. For example a() | b() would run both function a and function b. a() || b() only runs function b if a returns false.

A: I think that also in vba you can use OrElse.
'Or' (bitwise comparison) always finishes the rest of the statement, 'OrElse' (logical comparison) stops when the requirement is met.
In C++, C# and Java you can use '|' and '||'.
For example if object is null Or object.value = "" will result in a null exception when the object is empty because of the attempt to access a field from an empty object.
With OrElse the evaluation if object is null OrElse object.value = "" will stop at the first comparison when an empty object is evaluated.


text:
Q: Not Showing Any Sign of Menu Button when there is not any default menu button in devices I am Working on One Application which has Settings Screen which Opens When User Click on OptionMenu Shortcut which shows on Devices as Default Button or any other Sign.
it Works fine when there is default menu button in device but not getting any Sign for Menu Option when there is not any default menu button in devices.
My Code is as Below:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_setting, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.btnSettingMenu:
        Intent intent = new Intent(MainActivity.this,
                RegisterActivity.class);
        intent.putExtra("From", "MainActivity");
        startActivity(intent);
        break;

    default:
        break;
    }

    return true;
}

I have refered to Link HERE but could not able to solve my problem.
Point I would like to add is: I am getting the Menu Option in Emulator when i am pressing PageUp or F2.
But when the Device Does not have Default Menu Button it is not Showing with any other indication as three dots or some other way.
My Question : How can User Go to my Setting Screen if he is not Finding Option Menu Sign in real devices Like Nexus 7?
Thanks in Advance.

A: For showing Menu icon in above 4.0 Devices:
if you have declared android:targetSdkVersion="xx"
Either remove it if you don't required.
OR
If you want to declare it,then set value 0f xx below 14
i.e.android:targetSdkVersion="13".

Hope it will work for you.

A: Try this:

*

*Please remove this two line in your java class.
// hide titlebar of application
// must be before setting the layout
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide statusbar of Android
// could also be done later
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

*Please remove this two line in your AndroidManifest.xml.
To hide the titlebar of your application you can use the predefined style
android:theme="@android:style/Theme.NoTitleBar".

or if you also want to hide the statusbar of your application use
android:theme="@android:style/Theme.NoTitleBar.Fullscreen".


text:
Q: How can I upload a file using jquery's $.ajax function with json and php I am trying to upload a file using jQuery's $.ajax function but didn't get any output.
Somebody please help me to solve this.
I don't know if this script is correct.
My script is:
$.ajax({
  url:'newsup.php',
  data: "",
  type: 'POST',
  contentType:'multipart/form-data',
  dataType: 'json',
  catche: 'false',

  success:function(data6)
  {
    $("#disp").removeClass().addClass((data6.error=== false)? 'success':'error').html(data6.msg).fadeIn('fast');
    //dele();
    if($("#disp").hasClass('success'))
    {
      alert("success");
      setTimeout("$('#disp').fadeOut('slow')",3000);
    }
  },

  error:function(XMLHttpRequest,textStatus,errorThrown)
  {
    $("#disp").removeClass().addClass('error').html("There was an <strong>"+errorThrown+"</strong> error due to  <strong>"+textStatus+" condition").fadeIn('fast');
  }

});

Also I need help getting data from file uploading field using jQuery.

A: Please use plugin for this.In my opinion this plugin is better solution for this.You don't need to remember all options etc.Just replace your 'ajax' to 'ajaxForm'.
Please read examples ,below
http://jquery.malsup.com/form/#ajaxForm

A: This is how I've done it. Use the FormData object.
Note: The odd syntax of the for statement is just setting "f" to the array[i] instance.
        $("#submit").click(function () {
            var formData = new FormData();
            for (var i = 0, f; f = fileArray[i]; i++) {
                formData.append("opmlFile", f);
            }
            $.ajax({
                url: "/Documents/SaveFiles/" + @Model,
                type: "POST",
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            })
            .error(function (xhr, status, error) {
                $.notify(error, true);
            })
            .success(function (data, status, xhr) {
                $.notify("Success");
            });
        });

Unfortunately I don't recall which article I got this from, but it was someone else on Stack Overflow.

A: AJAX doesnt support file uploading. There are plugins like ajaxfileupload which basically creates a hidden form and uploads your file dynamically.
take a look here and read Oli's answer

A: I'm using this and it's working fine:
  $('#btnUploadFile').on('click', function () {
                var data = new FormData();
                var files = $("#fileUpload").get(0).files;

                // Add the uploaded file content to the form data collection
                if (files.length > 0) {
                    data.append("upload", files[0]);
                }

                // Make Ajax request with the contentType = false, and procesDate = false
                var ajaxRequest = $.ajax({
                    type: "POST",
                    url: "/api/documents",
                    contentType: false,
                    processData: false,
                    data: data,

                    error: function (xhr, status, error) {
                        console.log(xhr);
                        console.log(status);
                        console.log(error);
                        console.log(data);
                    }
                });

                ajaxRequest.done(function (xhr, textStatus) {
                    $("#response").attr('class', "alert alert-success");
                    $("#response").html("File uploaded successfully");
                });

            });

A: You can use either of the two plugins Jquery File Upload Plugins 1 or Jquery File Upload Plugins 2 and there's no errors on this script.
Hope it helps
Thanks,
Rashid

A: Ajax supports File upload using FormData Object, Also supports in all major browser except IE8/9
See below
https://developer.mozilla.org/en-US/docs/Web/API/FormData

A: Another option would be to base64 encode the file contents and send it as a string, decoding it at the back-end.

A: Simply use submit event on form to send the files and prevent default form action
$('#form').submit(function(e) { return false; });
and get the file on the server side via
$_FILES['inputName'];


text:
Q: Div is showing only when page loading is complete I have a php page with multiple simplexml_load_file($url) requests that put data into a table.
I'd like to show a "loading.." DIV because page loading time is about 7 seconds.
This is the page structure:

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

What happens is that page loader  is rendered only when page load is complete and it is closed immediatly.
Why loader  is not loaded immediatly?

A: Try to think/solve like so:

*

*make the "loader" visible by default at page load no matter what

*when all data is loaded hide the "loader"
In other words:

*

*do not set the visibility of the "loader" with javascript! Because you can assume (no matter how fast your page is) it has to load anyways. If the loader is only visible for 1ms it's fine. If the data needs longer to load you will see the "loader" for longer and when ever the page is ready you only hide the "loader" via javascript.

Side note, I recommend adding/removing a class to the loader which then has the styles accordingly from CSS. Adding inline styles via javascript can be annoying at some stage.
Sample code:

var loader = document.querySelector('#loader');

setTimeout(function(){

    // assume your page has finished loading here
    // after 3.5 sec
    loader.classList.remove('loading');

}, 3500);
#loader {
    background-color: orange;
    display: none;
}
#loader.loading {
    display: block;
}

loading....

assume data is/was loading


text:
Q: How can I disable a superuser in postgres On a server I have two databases ( say db1 and db2 ). I have a superuser called user1.
My requirement is to disable user1(super user) for database db1.
So that using user1 I can only connect to db2 and not to db1.
How can this be done.
Note : postgres version is 8.0 and both the databases are on same database cluster.

A: Remove their superuser rights entirely. Make them the owner of db2 (ALTER DATABASE db2 OWNER TO whatever_user), so they can do anything to db2 except limited superuser-only operations like loading C extensions.
You cannot restrict superusers. That's the point. Superuser-only operations are ones that break through the usual access control rules. For example, loading a user-defined C function allows you to write and load a function that opens pg_hba.conf and rewrites it, or just manipulates the system catalogs directly. Similarly, the adminpack functions let you do direct file system access, so they're superuser-only.
If they're a superuser, they can just read pg_hba.conf, see that your user ID has the right to log in to db1, then change your password then log in as you.
Asking to limit a superuser to one DB is like asking if you can make a user root, but only for one subdirectory. (OK, so with SELinux you can kind-of do that, but it's complicated).
If you truly must do this, the only way to do it is to split db1 and db2 into different PostgreSQL servers running under different unpriveleged system user IDs. Each has its own separate shared_buffers, data directory, listening (ip-address, port) combo, WAL, user IDs, database lists, etc. Since they're running under different system users they don't have the right to read or write each others' data directories, so they are isolated.  They must listen on different ports and/or different IP addresses, though you can use PgBouncer to make them appear to be the same server to external clients.


text:
Q: Query with multiple ManyToOne joins I have a model with the following classes:
public class Organization  {

    private Person person;

}

public class PersonAddress  {

    private Person person;
    private Address address;

}

public class Address {

    ...

}

There's not a direct association between Person and Address, nor Person and PersonAddress, nor Address and PersonAddress. PersonAddress is the ManyToMany association between Person and Address, but we're trying to avoid mapping the corresponding collections because their abusive use may lead to some performance issues.
I'm trying to create a querydsl method passing an organization as a parameter and getting a projected result with the organization, person and address data, but my best attempt so far is giving me a query with a cross join.
Can I build this query in a way that the cross join is avoided? And also avoiding creating the collection associations.
Here is the querydsl query and the generated SQL:
QueryDSL:
QOrganization organization = QOrganization.organization;
QPerson person = QPerson.person;
QPerson personOrganization = new QPerson("personOrganization");
QAddressPerson addressPerson = QAddressPerson.addressPerson;
QAddress address = QAddress.address;
QCity city = QCity.city;
JPQLQuery<Organization> query = newQuery().from(addressPerson,organization)
    .join(organization.person, person)//
    .join(addressPerson.address, address)//
    .join(address.city, city)//
    .leftJoin(addressPerson.person, personOrganization);
    BooleanBuilder builder = new BooleanBuilder();
    builder.and(organization.eq(organizationParam));
    query.where(builder)//
        .select(create(organization.id, organization.type, //
            QPerson.create(person.id, person.type, //
            QAddressPerson.create(addressPerson.id, //
            QAddress.create(address.id, //
            QCity.create(city.id, city.name), address.zipcode)))));

Resulting SQL:
select
    organization1_.org_id as col_0_0_,
    organization1_.org_tp as col_1_0_,
    person2_.pes_id as col_4_0_,
    person2_.pes_tp as col_5_0_,
    addresspe0_.enp_id as col_10_0_,
    address3_.end_id as col_11_0_,
    city4_.cid_id as col_12_0_,
    city4_.cid_nm as col_13_0_,
    address3_.END_VR_CEP as col_15_0_
from
    address_person addresspe0_
inner join
    address address3_
        on addresspe0_.end_id=address3_.end_id
inner join
    city city4_
        on address3_.cid_id=city4_.cid_id
left outer join
    person person5_
        on addresspe0_.pes_id=person5_.pes_id cross
join
    organization organization1_
inner join
    person person2_
        on organization1_.pes_id=person2_.pes_id
where
    and organization1_.org_id=?

A: This part is causing the cross join
newQuery().from(addressPerson,organization)

You need to move either addressPerson or organization to an inner or left join.


text:
Q: Spacified columnized on-the-left line formatting to columnized data? xxxxxxxxxxxxx1.11xxxxxxxxxx1.11xxxxxxxxxxx1.11
xxxxxxxxxxxxx1.11xxxxxxxxxx1.11xxxxxxxxxx11.11

*

*Is there some ready module in Python with which I could easily do above like formatting 17signs, 14 signs and then 15 signs?

*How can you get the thing n.b. the small difference with 1.11 and 11.11?

N.b. the numbers could be larger but not greater than 10 signs. The linewise count 46 (=17+14+15) is constant.
[Update] Notice that I am using Python 2.6.5 so getting error ValueError: zero length field name in format with suggestions.

A: You don't need a module or library to do this, use string formatting. To avoid the ValueError, specify what index your parameter is in the supplied values:
"{0:>17}".format(11.1)

A: String formatting is built-in:

*

*http://docs.python.org/library/string.html#format-specification-mini-language
Examples for Python 2.7/3.1
>>> '{:x>17}'.format(s)
'xxxxxxxxxxxx11.11'

>>> '{:x>17}{:x>14}{:x>15}'.format(11.1, 11.1, 11.1)
'xxxxxxxxxxxxx11.1xxxxxxxxxx11.1xxxxxxxxxxx11.1'

A: Someone commented the right answer but removed it so I will post it here. I will remove it if s/he post it so the credits go to the right person.
('%17.2f%14.2f%15.2f' % (1.11, 1.11, 11.11))


text:
Q: Suspicious startup program entries on Windows 8.1 I just viewed my "Software Environment->Start-up Programs" in the System Information app on Windows 8.1 and found a couple of entries that look a bit odd (see the top 2 entries on the image).
There are no programs associated with these entries, the command name is Chinese, Japanese or something similar and they are owned by the legitimate users "NT AUTHORITY\SYSTEM" and ".DEFAULT"
Are these legitimate programs? Can anyone throw any light on what these might be?
Thanks.
Screenshot image


text:
Q: Can't get value in my controller using ajax ? i don't know if i asked the right question but anyway that is my problem : i followed a tutorial showing how to use ajax with Java ee and i made a simple example and it worked, but i tried to apply what i learned in my project and it didnt work, here is my jsp file :

     <form>
     <input type="hidden" class="adore1" name="aime" value="${post.id}">
     <input type="button" class="adore2" value="J'aime">
     </form>

     <c:if test="${ post.adore == 0 || post.adore == 1 }">

${ post.adore } personne aime ça

     </c:if>

     <c:if test="${ post.adore != 0 && post.adore != 1 }">

${ post.adore } personnes aiment ça

     </c:if>

What i wanted is to get the value in the hidden input by clicking on my button( input button) so here is my jquery file :
    $(".adore2").click(function(){
    var aime = $(this).parent().find(".adore1").val()
    var value=$(this).parent().parent().siblings().find(".nbrAdore").text()
    alert(value)

    $.ajax({
        type:"POST",
        data: {aime:aime},
        url:"acceuilServlet",
        success:function(result){
             $(this).parent().parent().siblings().find(".nbrAdore").html(result)
        }
    })

})

And i wanted to see the result in the console ( as a test ) so here is a part of my Controller ( doPost method ) but i am getting any response.
    resp.setContentType("text/plain");

    int aime = Integer.parseInt(req.getParameter("aime"));
    aime++;
    System.out.println("hello "+aime);

Any help would be much appreciated.

A: first you need to register your servlet in Web.xml like below. Then it knows to accept the requests.
<web-app>
      <servlet>
        <servlet-name>yourServlet</servlet-name>
        <servlet-class>com.java.YourServlet</servlet-class>
      </servlet>

      <servlet-mapping>
        <servlet-name>yourServlet</servlet-name>
        <url-pattern>*</url-pattern>
      </servlet-mapping>
    </web-app>


text:
Q: How to display unique entries from a table? I got this table
╔════╦══════════════╦══════╗
║ ID ║  Name        ║ Age  ║
╠════╬══════════════╬══════╣
║  1 ║ John         ║   36 ║
║  2 ║ Andre        ║   48 ║
║  3 ║ John         ║   21 ║
║  4 ║ Joel         ║   59 ║
╚════╩══════════════╩══════╝

How can I display only those names from table that are unique?

A: You can use aggregation:
select name
from t
group by name
having count(*) = 1;

A: A simpler method is to use the DISTINCT keyword
SELECT DISTINCT Name FROM t;


text:
Q: WebBackgrounder Register new job I have configured WebBackgrounder in my asp.net mvc application and I have it working, I'm registering a job at the start of the application in WebBackgrounderSetup in App_Start.
Now I need to register another job from a controller action, how can I register it? I don't see any method for this in JobManager, isn't it possible?


text:
Q: Input to a Java program - keyboard input v/s file I have a Java program that accepts input text typed in from standard input
is there a way to find if the user has typed in the text or redirected input from a file?
$ java prog
this text is typed in from the keyboard
$ java prog < file.txt
Thanks!

A: Judging from the JLine source code, you have to use JNI to make native OS calls to determine whether stdin is a TTY. If you're certain to be in a Unix-like environment, you can do what they do there.


text:
Q: ksh loop: "for dir in find .. do" not working, unlike "for dir in ls .. do" Both of the following lines do return the list of dirs of one of my directories.
The first of them use a name pattern whereas I need to choose dirs given they really are directories to then process them in a loop. I thus would like to use the second:
ls -l  | awk '{print $9}' | grep 'dirsPrefix*'

find . -maxdepth 1 -type d | grep -v \\.$ | awk -F'./' '{print $2}'

But within a ksh for loop, the first is working unlike the second ...
Why ? :
(workaround:
for dir in `find . -maxdepth 1 -type d -exec echo "{}" \; | awk -F'/' {print $2}`
do
  echo "dir: $dir"
done

will work)
This also works:
for dir in `ls -l  | awk '{print $9}' | grep 'dirsPrefix*'`
do
  echo "dir: $dir"
done

But this does not:
for dir in `find . -maxdepth 1 -type d | grep -v \\.$ | awk -F'./' '{print $2}'`
do
  echo "dir: $dir"
done

A: You're trying way too hard to get the directories in the current directory. All you need to do is:
for dir in */; do echo "dir: $dir"; done
# .........^^

If you want to store them in an array:
dirs=( */ )

A: Change it to this:
for dir in $(find . -maxdepth 1 -type d | grep -v \\.$ | awk -F'./' '{print $2}')
do
  echo "dir: $dir"
done

I can't explain why it works but I know you should pretty much always use $() over backticks.

A: You need to realize that the command that you are running, viz.,
for dir in `find . -maxdepth 1 -type d | grep -v \\.$ | awk -F'./' '{print $2}'`

there are 2 levels of quote interpretation. In the first level, that is at the level of the command line where from the command is issued, the text under the backquotes `....` is first scanned for backslashes and $variables, just as in a double quotes interpolation. Since that $ is sitting lonesome at the end, so it won't be expanded. There's no harm in escaping it though.
So this shall leave that grep -v \\.$ ----> grep -v \.$
Now after this step is over, it shall be handed over to a subshell for running. And in that subshell the command grep -v \.$ is parsed and the backslash is taken away so what grep executable gets at the end of this phase is:   grep -v .$
Now all the nonempty lines will match this pattern and find generated all nonempty lines, for the simple reason that filenames mustn't be nonempty.
So that means all find's output are gonna be selected and hence the inverse of that implies that no output from find shall be selected. So awk is all dressed up but has really nowhere to go.
Solution:
There are many things you can take up to fix the issue.

*

*Add one more backslash to the grep, making it :   grep -v \\\.$
Based on what happens in each step of quote expansion for this scenario, convince yourself that this fix works.

*Use the $() form of command interpolation as in this format the quoting begins anew withing the $() unlike the `` form of backquoting.

*Use single quotes in the grep, making it: grep -v '\.$'

*Use character classes to escape the . :   grep -v '[.]$'

*Do everything in find command itself:

find . -maxdepth 1 -type d ! -name . -exec sh -c '
   for d do printf "dir: %s\n" "${d:2}"; done
' sh {} +

A: There is a problem with your grep-expression. It will match all directory names ending with ., but it also seems to skew the output somehow to make for confused. There are many things you can do about this.

*

*Changing the grep expression to grep -v "^\.$" will probably be more correct (as it will match only the . directory), and it will work in your for-loop

*As as already pointed out by @Jesse_b, it is better, for many reasons, to use the $(..) expression for execution. This will solve your immediate problem, but not fix the potential bug.

*You can use find all the way, making this script a bit simpler:
for dir in `find . -maxdepth 1 -type d ! -name "." -printf "%f "`
do
   echo $dir
done

Not that all of these solutions will likely be trouble if there are directories with spaces () in their names.


text:
Q: Exclude rows where two columns BOTH have a value of zero, not one or the other In SQL, I have two interger columns and I want to exclude rows where BOTH columns have a value of zero.
So in the below example, I would want rows 2 and 3 excluded only.
    Col 1   Col 2
1   0.00    1.53
2   0.00    0.00
3   0.00    0.00
4   6.84    0.00

I have tried the below to test if it brings me just rows where one column holds 0.00 but the other does not, and there are no rows. Which means, my first argument is not working.
WHERE
        (COL1 > 0.00 AND COL2 > 0.00)
        AND (COL1 = 0.00
        OR COL2 = 0.00)

A: You would use AND with a NOT to filter results so that if both columns contain 0, they are filtered:
SELECT * FROM mytable WHERE NOT(col1 = 0 AND col2 = 0)

If you want numbers to appear that have NO 0 in them such as a row: 12,12 the Exclusive OR XOR / <> will not work.
Your best practice is to use the WHERE NOT example I have listed.

A: Typically it is best to include example code showing what you have tried along with what is happening versus what you expect to happen. Based on the wording of this question it looks like all you would need in your WHERE clause is something like this. If this doe snot answer your question please be more specific as to why and what you have tried.
Proposed WHERE clause:
WHERE

  -- This is going to only include rows
  -- where one or both column values are non-zero
  Col1 <> 0
  OR Col2 <> 0


text:
Q: Generate a 100*2 array from a t distribution with degree 30 I'm struggling with a Python Scipy question for my Python class. I'm trying to keep it simple and straightforward so I can learn for myself.
Any help with this question would be appreciated. Thanks.

A: If you specifically want to use scipy to do this, you can use the stats module. This lets you create an object for a distribution with your chosen parameters, from which you can then generate random variables drawn from that distribution. So for a student's t with  dof=30, you could do:
from scipy.stats import t

my_t = t(30)

my_arr = my_t.rvs((100, 2))

A: np.random.standard_t(30, (100, 2))

array([[ 0.2900961 , -0.49184654],
       [-0.66369036,  0.29856974],
       [-0.81205354, -0.73274099],
       [ 0.03983057, -1.63843224],
       [-1.48501012,  0.37018367],
       [-0.02788238, -2.73851282],
       [ 0.02121366, -0.29790155],
       [-0.06538505, -0.30493695],
       [ 1.35973227, -1.12887598],
       [ 0.02135389,  1.27192716],
       [ 0.45889757,  0.83632908],
       [ 0.11450415, -1.23755654],
       [ 0.75822006, -0.10754588],
       [ 1.17461175, -1.08492382],
       [ 1.53760935, -0.55211614],
       [ 1.7442242 , -0.51923315],
       [ 0.92816422, -1.93624871],
       [ 0.75735932,  0.31273475],
       [-0.71536809,  0.04971693],
       [-0.4094555 ,  0.85412734],
       [ 1.23209227, -1.01814822],
       [-0.83653207,  0.5476101 ],
       [-0.93710566, -0.68810908],
       [-0.33276732,  2.3529951 ],
       [ 1.78781951, -0.30588975],
       [ 0.38020327, -0.68367237],
       [ 0.32864593,  1.26141535],
       [-1.21311796, -1.25318568],
       [-0.82619795, -0.49099708],
       [-0.00987192,  1.24385043],
       [ 0.50069202, -0.67335928],
       [-1.10908519,  1.48047345],
       [ 0.84272651,  0.88305515],
       [ 1.03803068, -0.78190559],
       [-2.18620032,  1.35880684],
       [ 0.59731946, -0.10586537],
       [-0.06889232, -1.93968476],
       [ 0.91114411,  0.16464482],
       [ 1.63996227, -0.44997124],
       [ 0.63459803,  0.17235393],
       [ 0.14484818,  1.97338409],
       [ 0.19124964,  0.25048341],
       [ 1.05005178, -2.03222472],
       [ 0.39245172,  1.6927919 ],
       [-0.78692079,  1.00297447],
       [ 0.17231872,  1.87670916],
       [-0.5570899 , -1.12292151],
       [ 1.6123502 , -1.23264286],
       [-1.09187624, -1.12123467],
       [-1.25814082, -1.03345077],
       [-0.70254563,  0.52535811],
       [ 0.1981361 ,  0.98231126],
       [ 0.35442413,  2.22361201],
       [-1.15538729, -0.90178065],
       [ 0.58262176, -0.14912307],
       [-0.12245958, -0.7622139 ],
       [ 2.02454963, -1.23601746],
       [ 1.80337422, -1.26433357],
       [ 1.55435051, -0.30136764],
       [ 1.02185468, -1.01947832],
       [-0.97216339,  0.45184081],
       [ 0.70142966,  1.24516373],
       [-2.03826058, -0.22819802],
       [ 2.15868138, -0.75028286],
       [-0.13703708, -2.42009844],
       [ 0.11059006, -0.77753454],
       [ 0.60928961, -2.42947059],
       [-0.06756108, -0.24126194],
       [ 0.32133117,  0.5354973 ],
       [ 1.55587524,  0.02437769],
       [-0.08989499,  0.26808396],
       [ 0.32481833, -0.49148255],
       [ 1.37278471,  1.28359455],
       [ 1.11240391, -0.46442478],
       [-0.23700156,  3.52282209],
       [ 1.52313794,  0.32729436],
       [ 0.03314825,  0.48151337],
       [ 1.36774946, -1.36015715],
       [ 0.79938481,  1.88828935],
       [ 0.23314392, -2.19733862],
       [-1.76801664,  0.13285706],
       [ 0.72678452,  0.89537934],
       [ 0.69842504, -0.56114374],
       [ 1.01189122, -0.13459648],
       [-0.34997372, -0.5946139 ],
       [ 0.29432587,  1.47568117],
       [-1.39008419,  0.22297323],
       [-0.68324715, -0.12054717],
       [-0.44935036, -0.22928693],
       [-0.80951017,  1.48290706],
       [-0.34331734, -1.25514126],
       [-1.95957181, -0.2914293 ],
       [-0.74272681,  0.57470058],
       [-0.42099781, -0.25268629],
       [-2.26217783, -1.740979  ],
       [-0.25803757, -1.37507365],
       [-0.60466318, -0.81158367],
       [-0.0189305 , -0.27809122],
       [ 0.53366222, -1.01032679],
       [ 0.68300556,  0.27805818]])


text:
Q: Cordova not finding avd After following the instructions for setting up Cordova for Android development on the Cordova documentation, I encountered this error:
Error: No emulator images (avds) found.
1. Download desired System Image by running: /Users/Jacob/Library/Android/sdk/tools/android sdk
2. Create an AVD by running: /Users/Jacob/Library/Android/sdk/tools/android avd
HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver

Every other post I found only said to add an emulator, but I have already done that. In Android Studio, I have in fact made three!
It is also worth mentioning that Cordova used to be able to run the emulator, but in attempting to fix another problem, I ran into this one. I did run into a problem with permissions, and now have to use sudo every time I run a Cordova command. Could that have anything to do with it?
Here is my .bash_profile:
ANDROID_HOME=/Users/Jacob/Library/Android/sdk
PATH=${PATH}:/Users/Jacob/Library/Android/sdk/platform-tools:/Users/Jacob/Library/Android/sdk/tools
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home

I have been trying to use the Android API level 23 with Android 5.1.1 in Cordova.
After trying everything I could think of (as a Terminal newbie :p), I'm out of ideas. I have tried reinstalling the Android SDK with all the packages, node.js (perhaps not entirely cleaning log files/caches), and Cordova, but to no avail. Is there anything in particular I could just reinstall so that the problem would probably disappear without much fixing?
Thanks!

A: Got it! After some messing around, I found two files:
/Users/Jacob/.config/configstore/update-notifier-cordova.json
/Users/Jacob/.config/configstore/update-notifier-phonegap.json

By pressing CMD+I, I could see that their permissions did not include the admin (my name). So after adding my name to their permissions, I don't have to use sudo nearly as much and the emulator worked perfectly! :)

A: I have a similar issue and have found one way around it.
Try opening your Android SDK manager > tools > Manage SDKs...
Select an AVD and click start. Once booted, try the comment cordova run android (with sudo if necessary) and it should work on the running emulator.
When debugging, I find it much better to plug in an actual device - the experience is much smoother and you get better feel for what the app actually looks and runs like on a real device, whereas on the SDK emulator Cordova often runs quite slowly.
You can find instructions for that here.

A: what you mean by 'I  have been trying to use the Android API level 23 with Android 5.1.1' ?
Api 23 = marshmallow = android 6
You must have updated cordova i guess.i use ionic i got this after updating cordova and ionic.
either dcrease the target sdk in manifest or download latest system-image/sdk for api 23. since cordova/equivalent framework will always try building with latest api level.
for now you can try changing target sdk in manifest.config.xml


text:
Q: Returning "0" everytime when fetching keychain saved passcode from keychain access for ios app I am using KeychainItemWrapper class(integrated .h and .m file in project) for saving passcode in Keychain for iOS App. Also imported "Security" Framework and "keychianItemWrapper.h" class in the project wherever it is needed.(#import  , #import "KeychainItemWrapper.h" )
I am using below code in app delegate method for saving passcode in keychain access :
if([textfieldPassword1.text isEqual:textfieldPassword2.text]){

                NSLog(@"CONGRATS !! PASSCODE MATCHED !!!");

                //converting "textfieldPassword1" to NSNumber
                NSNumber *textfieldPasscode1Num = [NSNumber numberWithInt:[textfieldPassword1.text intValue]];

                //saving passcode to the keychain access
               [keychain setObject:textfieldPasscode1Num forKey:(__bridge id)kSecValueData];

           //    [keychain setObject:[NSNumber numberWithInt:[textfieldPassword1.text intValue]] forKey:(__bridge id)kSecAttrAccount];

                // if passcode matches then load Show Lock Screen Page
                self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
                self.viewController = [[ViewController alloc] init];
                [self.window addSubview:self.viewController.view];
                [self.window makeKeyAndVisible];
            }

AND HERE AM RESETTING PASSCODE USING BELOW CODE :
if(_isResetPasscode){
                NSLog(@"Code here for Update Passcode in Keychain Access !!!");
                _isResetPasscode = FALSE;

              // "keychain" is object of "KeychainItemWrapper" class
                [keychain resetKeychainItem];

/* Again setting the new passcode entered by user in keychain access.. IT IS NOT SAVING IN keychain access, where above the same line of code was working for saving passcode in keychain access
/*
                [keychain setObject:resetPasscodeNum forKey:(__bridge id)kSecValueData];

                NSLog(@"----Passcode Re-Setted ----!! %@\n",resetPasscodeNum);
            }

When I am printing keychain passcode in console every time it is printing "0".
Please guide me where i am doing wrong... Your help would be appreciated !!
Thanks in Advance

A: You haven't specified what format the entered password could be. I am assuming it could be any sort of text.  If that is the case, then this line will fail if the entered text is not actually a number:
[textfieldPassword1.text intValue]

and will return 0;


text:
Q: How to disable springfox import on openApi generation? I would like to replace openapi generator plugin from 5.0.0 to 5.1.0. If I build my project it automatically imports import springfox.documentation.annotations.ApiIgnore; to my all generated by API interfaces.
How can I ignore this implementation?

A: Update openapi generator plugin to 5.3.0 or more

A: Need to add next settings
additionalProperties: [
   apiFirst: true
]

Here a code where useSpringfox property populated.
Link to the similar conversation.

A: add dependency to project: implementation "io.springfox:springfox-core"


text:
Q: $myform.textinput.$isvalid is true when it should not The whole form should not be valid until stuff[] has at least one item added to it. When the user enters in a value into the text box and then clicks add it then adds the value to stuff[], only at this point when a value has been added to stuff[] should the submit button be enabled. However, as soon as the user types anything into the text box without clicking add, and thus nothing in stuff[], it makes the form valid and enables the submit button.
<form ng-app="myApp" ng-controller="myCtrl" name="myForm" ng-submit="submit()" novalidate>

{{things}}

    <input type="text" name="app" ng-model="input" ng-required="!stuff[0]" />

    <button ng-disabled="!input" ng-click="add()">
         add
    </button>

    <input type="submit" value="Submit" ng-disabled="myForm.$invalid" />

</form>

A: [EDIT]
To answer your question directly: !stuff[0] is TRUE when there is nothing in the array, and FALSE otherwise. When it is TRUE, then input is required, making the form 'initially' invalid. As soon as you type something into the input, then the requirement is now fulfilled, meaning that the form is valid, and you can now click the submit button. The condition actually has nothing to do with actually putting something into the array.
This is fixable by attaching a condition to stuff.length as proposed by my answer below. It won't make the form invalid (which you can easily do with this condition elsewhere) but it will at least disable the submit button.
[/EDIT]
I don't understand why you have ng-required there, as you are wanting to disable the submit button, meaning the logic should be attached to the submit button, not the input text box.
I would do this instead:
<input type="text" name="app" ng-model="input"/>

<button ng-disabled="!input" ng-click="add()">
     add
</button>

<input type="submit" value="Submit" ng-disabled="stuff.length == 0" />

Which will disable the submit button if there is nothing in stuff.


text:
Q: Atoll values for negative numbers in C I'm trying to use atoll to convert a string of numbers with spaces. I want to make a loop in C that will only take positive numbers.
So far, from what I understand, atoll on a char would return 0, likewise with a combination of an int and char, such as "3a". However, is there a range of values for negative numbers for atoll on a negative number?
I found that the result of -1 is 18446744073709551615, -2 is 18446744073709551614, -3 is 18446744073709551613, etc, based on my first print statement.
for(arg = 1; arg < argc; ++arg)
{
   printf("%llu\n", atoll(argv[arg]));

   if(atoll(argv[arg]) == 0 || atoll(argv[arg]) >= xxxxx))
   {
     printf("Enter a valid number.");
   }
   else
   {
     printf("irrelevant code here");
   }
}

A: From your code fragment it is not possible to figure out several important things. Did you include correct headers, did you use correct format specifiers and length modifiers in printf? In example bellow you can find correct includes an correct format for long long.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("%lld\n", atoll("-1"));
    return 0;
}

/* this example prints correct output of -1 */


text:
Q: Input terminal command to embedded terminal in GUI I'm pretty new to Python, so bear with me on this. I looked at the possible duplicate of my question, and wasn't able to get it to work for me. I'm assuming I just don't understand the answer code enough, but I can't seem to get the terminal command I want, just the one used in the answer.
The answer I'm referring to can be found here: Giving a command in a embedded terminal
I've got a simple GUI that I've embedded a terminal into. The purpose of this is to run tcpdump to capture packets. I wrote a simple script that did this just fine, but I'm looking to make it easier to use on a touch screen, hence the GUI.
I set up a button that runs the following code:
os.system('sudo tcpdump')

But it doesn't execute in the embedded terminal.
Could someone explain how to make this command run in the terminal that's embedded in the GUI?
Here's all the code I have for the GUI so far:
from tkinter import *
import os

class PcapGUI:
    def __init__(self, master):
        self.master = master
        master.title("Packet Captures")

        self.start_button = Button(master, text="Start", command=self.start)

        self.termf = Frame(root, height=400, width=500)

        self.wid = self.termf.winfo_id()

        os.system('xterm -into %d -geometry 70x20 -sb &' % self.wid)

    def start(self):
        os.system('sudo tcpdump')

root = Tk()
gui = PcapGUI(root)
root.mainloop()

Any help is appreciated!


text:
Q: Seaborn time axis: show date instead of nanoseconds I have a pandas dataframe with a date column (RankingDate).
This date field is initially a string loaded from a csv in the the format "2006-11-03"
After running df["RankingDate"]=pd.to_datetime(df["RankingDate"]), the data type becomes '<M8[ns]'
I then plot multiple lines over time using seaborn:
f, ax = plt.subplots(figsize=(16, 8))
sns.tsplot(data, time='RankingDate', unit='Dummy', condition='Player', value='Points', ax=ax)

However this gives me a chart where the date axis is labelled in nanoseconds (i.e. 1e10^18), instead of a nice date format like "2006-11-03".
How can I get seaborn to display a date instead of nanoseconds?
Example code:
import numpy as np
import pandas as pd
import seaborn as sns
RankingDate = ['2015-03-02','2015-03-03','2015-03-04','2015-03-05','2015-03-06']
Player = ['Player1','Player2','Player2','Player1','Player1']
Points = np.random.randn(5)
df = pd.DataFrame({'RankingDate': RankingDate , 'Player': Player, 'Points': Points})
df["RankingDate"]=pd.to_datetime(df["RankingDate"])
df["Dummy"]=0

f, ax = plt.subplots(figsize=(16, 8))
sns.tsplot(df, time='RankingDate', unit='Dummy', condition='Player', value='Points', ax=ax)


text:
Q: RabbitMQ Delivery Acknowledgement Timeout I am using a managed RabbitMQ cluster through AWS Amazon-MQ. If the consumers finish their work quickly then everything is working fine. However, depending on few scenarios few consumers are taking more than 30 mins to complete the processing.
In that scenarios, RabbitMQ deletes the consumer and makes the same messages visible again in the queue. Becasue of this another consumer picks it up and starts processing. It is happing in the loop. Therefore the same transaction is getting executed again and I am loosing the consumer as well.
I am not using any AcknowledgeMode so I believe it's AUTO by default and it has 30 mins limit.
Is there any way to increase the Delivery Acknowledgement Timeout for AUTO mode?
Or please let me know if anyone has any other solutions for this.

A: Reply From AWS Support:
Consumer timeout is now configurable but can be done only by the service team. The change will be permanent irrespective of any version.
So you may update RabbitMQ to latest, and no need to stick with 3.8.11. Provide your broker details and desired timeout, they should be able to do it for you.

A: This is the response from AWS support.
From my understanding, I see that your workload is currently affected by the consumer_timeout parameter that was introduced in v3.8.15.
We have had a number of reach outs due to this, unfortunately, the service team has confirmed that while they can manually edit the rabbitmq.conf, this will be overwritten on the next reboot or failover and thus is not a recommended solution. This will also mean that all security patching on the brokers where a manual change is applied, will have to be paused. Currently, the service does not support custom user configurations for RabbitMQ from this configuration file, but have confirmed they are looking to address this in future, however, is not able to an ETA on when this will available.
From the RabbitMQ github, it seems this was added for quorum queues in v3.8.15 (https://github.com/rabbitmq/rabbitmq-server/releases/tag/v3.8.15 ), but seems to apply to all consumers (https://github.com/rabbitmq/rabbitmq-server/pull/2990 ).
Unfortunately, RabbitMQ itself does not support downgrades (https://www.rabbitmq.com/upgrade.html )
Thus the recommended workaround and safest action form the service team, as of now is to create a new broker on an older version (3.8.11) and set auto minor version upgrade to false, so that it wont be upgraded.
Then export the configuration from the existing RabbitMQ instance and import it into new instance and use this instance going forward.


text:
Q: CLI StdIn Scala I have created a console-interface application as todo-list in Scala. My data access layer works with Slick 3 and my interface works using simple StdIn methods. But I have some troubles with reading lines. My main menu works fine while inner menu acts weirdly sometimes. In particular, when I enter a command for the first time I do not get any result just the same menu is displayed again. Then I enter any command and I get the result. And if I try to enter some command for the 3d time my program just stops with System.exit.
Here is the code for my interface:
object UserInterface {
  def displayMainMenu(): Unit ={
    println("Main menu:" + " \n1 - Login" + "\n2 - Exit")
    println("\nChoose the operation you want to perform:")
    val inputMainMenu = readInt()
    buildMainMenu(inputMainMenu)
  }

  def buildMainMenu(inputNumber: Int) =  inputNumber match {
    case 1 => enterSystem()
    case 2 => System.exit(0)
    case _ => println("Your input was wrong. Try again"); displayMainMenu()
  }

  def enterSystem(): Unit ={
    println("Input you login, please:")
    val inputLogin = readLine()
    println("Input you password, please:")
    val inputPassword = readLine()

    val checkLogin = Await.result(DAO.checkUserLogin(inputLogin, inputPassword), Duration.Inf).toString
    val userId = DAO.selectUserId(inputLogin)

    def changeOutputs(checkLogin: String):Unit = checkLogin match {
      case "true" => println("You have successfully entered"); displayInnerMenu(); buildMenu(userId)
      case "false" => println("Your input for login or password is wrong. Please, try again"); displayMainMenu()
      case _ => println("Your input is wrong"); displayMainMenu()
    }
    changeOutputs(checkLogin)
  }

  def buildMenu(userId: Long): Unit ={
    def chooseOption(number: Int):Unit = number match {
      case 1 => displayFinishedTasks(userId)
      case 2 => displayUnfinishedTasks(userId)
      case 3 => addTask(userId)
      case 4 => deleteTask()
      case 5 => markTaskAsFinished(userId)
      case 6 => displayMainMenu()
      case _ => println("Your input is wrong"); displayMainMenu()
    }
    val inputNum = displayInnerMenu()
    chooseOption(inputNum)

  }

  def displayInnerMenu():Int ={
    println("TODO List:" + "\n1 - Display finished tasks" + "\n2 - Display unfinished tasks"
      + "\n3 - Add task" + "\n4 - Delete task" + "\n5 - Mark task as finished" + "\n6 - Get back to the main menu")
    println("\nChoose the operation you want to perform:")
    val inputNum = readInt()
    inputNum
  }

  def displayAllTasks(id: Long) = {
    println()
    println("User's tasks:\n" + Await.result(DAO.selectTasksByUser(id), Duration.Inf).toList.toString)
    displayInnerMenu()
  }

  def displayFinishedTasks(id: Long) = {
    println()
    println("User's finished tasks:\n" + Await.result(DAO.selectFinishedTasks(id), Duration.Inf).toList.toString)
    displayInnerMenu()
  }

  def displayUnfinishedTasks(id: Long) = {
    println()
    println("User's unfinished tasks:\n" + Await.result(DAO.selectUnfinishedTasks(id), Duration.Inf).toList.toString)
    displayInnerMenu()
  }

  def addTask(id: Long) = {
    println()
    println("Input the task name you want to create, please:")
    val taskName = readLine()
    Await.result(DAO.addTask(taskName, id), Duration.Inf)
    displayInnerMenu()
  }

  def deleteTask() = {
    println()
    println("Choose the task you want to delete, please:")
    val taskId = readLong()
    Await.result(DAO.deleteTask(Some(taskId)), Duration.Inf)
    displayInnerMenu()
  }

  def markTaskAsFinished(id: Long) = {
    println()
    println("Choose the task you want to mark as finished, please:")
    val taskId = readLong()
    Await.result(DAO.finishTask(Some(taskId), id), Duration.Inf)
    displayInnerMenu()
  }

}

What I want is some kind of infinite cycle so I could perform my commands as many times as I need or set the limit. So what changes I can introduce in this code? I would be very grateful for some help!

A: Your particular troubles seem to come from the fact that changeOutputs in
 enterSystem calls displayInnerMenu which reads an Int from input but does nothing useful with it. Probably you should have called buildMenu in most of the places where displayInnerMenu is called.
Also it seems that you should improve your debugging skills. This is a crucial skill and this code is not that hard to debug.
Taken more broadly this is a complicated topic with no simple best answer. But there are certainly bad ones and unfortunately yours is one of those. The thing I don't like most in your code is big separation in the code between the menu item title and menu item action. (Just imagine what it takes to add new menu item in the middle. Or what would it take to create a deeper menu with some items shared between levels.) So I would re-write most of the code. Being more of an OOP-guy than a FP-guy, I would do something like this:
object UserInterface {

  // should be non-generic for simplicity of the rest of the code
  trait MenuAndStateNG {
    def runMenu(): MenuAndStateNG
  }

  trait MenuItem[S] {
    val name: String

    def doAction(state: S, curMenu: MenuAndStateNG): MenuAndStateNG
  }

  case class Menu[S](header: String, items: Seq[MenuItem[S]]) {}

  case class MenuAndState[S](menu: Menu[S], state: S) extends MenuAndStateNG {

    def runMenu(): MenuAndStateNG = {
      var inputNum: Int = -1
      var isFirstRun = true

      // we use 1-based indices in the menu
      while (inputNum <= 0 || inputNum > menu.items.length) {
        if (!isFirstRun) {
          println("Your input was wrong. Try again")
        }
        isFirstRun = false

        println(menu.header + ":")
        println(menu.items.zipWithIndex.map({ case (item, index) => s"${index + 1} - ${item.name}" }).mkString("\n"))
        println("Choose the operation you want to perform:")

        inputNum = StdIn.readInt()
      }
      println()
      val nextMenu = menu.items(inputNum - 1).doAction(state, this)
      nextMenu
    }
  }

  // most of menu items doesn't change current menu
  // let's make it easier to implement
  trait SimpleMenuItem[S] extends MenuItem[S] {
    override def doAction(state: S, curMenu: MenuAndStateNG): MenuAndStateNG = {
      doSimpleAction(state)
      curMenu
    }

    def doSimpleAction(state: S): Unit
  }

  def start(): Unit = {
    var curMenu: MenuAndStateNG = MenuAndState(mainMenu, ())
    var isFirstRun = true
    while (true) {
      if (!isFirstRun) {
        println
      }
      isFirstRun = false
      curMenu = curMenu.runMenu()
    }
  }

  private val loginItem = new MenuItem[Unit] {
    override val name = "Login"

    override def doAction(state: Unit, curMenu: MenuAndStateNG): MenuAndStateNG = {
      println("Input you login, please:")
      val inputLogin = StdIn.readLine()
      println("Input you password, please:")
      val inputPassword = StdIn.readLine()

      val checkLogin = Await.result(DAO.checkUserLogin(inputLogin, inputPassword), Duration.Inf).toString
      val userId = DAO.selectUserId(inputLogin)

      checkLogin match {
        case "true" =>
          println("You have successfully entered")
          MenuAndState(userMenu, userId)
        case "false" =>
          println("Your input for login or password is wrong. Please, try again")
          curMenu
        case _ =>
          println("Your input is wrong")
          curMenu
      }
    }
  }

  private val exitItem = new MenuItem[Unit] {
    override val name = "Exit"

    override def doAction(state: Unit, curMenu: MenuAndStateNG): MenuAndStateNG = {
      System.exit(0)
      null // null is bad but it doesn't matter by now
    }
  }

  private val displayFinishedTasks = new SimpleMenuItem[Int] {
    override val name: String = "Display finished tasks"

    override def doSimpleAction(state: Int): Unit = {
      println("User's finished tasks:\n" + Await.result(DAO.selectFinishedTasks(id), Duration.Inf).toList.toString)
    }
  }

  private val displayUnfinishedTasks = new SimpleMenuItem[Int] {
    override val name: String = "Display unfinished tasks"

    override def doSimpleAction(state: Int): Unit = {
      println("User's unfinished tasks:\n" + Await.result(DAO.selectUnfinishedTasks(id), Duration.Inf).toList.toString)
    }
  }

  private val displayAllTasks = new SimpleMenuItem[Int] {
    override val name: String = "Display all tasks"

    override def doSimpleAction(state: Int): Unit = {
      println("User's tasks:\n" + Await.result(DAO.selectTasksByUser(id), Duration.Inf).toList.toString)
    }
  }

  private val addTask = new SimpleMenuItem[Int] {
    override val name: String = "Add task"

    override def doSimpleAction(state: Int): Unit = {
      println("Input the task name you want to create, please:")
      val taskName = readLine()
      Await.result(DAO.addTask(taskName, id), Duration.Inf)
    }
  }
  private val deleteTask = new SimpleMenuItem[Int] {
    override val name: String = "Delete task"

    override def doSimpleAction(state: Int): Unit = {
      println("Choose the task you want to delete, please:")
      val taskId = readLong()
      Await.result(DAO.deleteTask(Some(taskId)), Duration.Inf)
    }
  }

  private val markTaskFinished = new SimpleMenuItem[Int] {
    override val name: String = "Mark task as finished"

    override def doSimpleAction(state: Int): Unit = {
      println("Choose the task you want to mark as finished, please:")
      val taskId = readLong()
      Await.result(DAO.finishTask(Some(taskId), id), Duration.Inf)
    }
  }

  private val logoutTask = new MenuItem[Int] {
    override val name = "Get back to the main menu"

    override def doAction(state: Int, curMenu: MenuAndStateNG): MenuAndState[Unit] = {
      MenuAndState(mainMenu, ())
    }
  }

  val mainMenu: Menu[Unit] = Menu("Main menu", List(loginItem, exitItem))

  val userMenu: Menu[Int] = Menu("User menu", List(
    displayAllTasks,
    displayFinishedTasks,
    displayUnfinishedTasks,
    addTask,
    deleteTask,
    markTaskFinished,
    logoutTask))

}

The main ideas are following:

*

*Join menu action and title into a single MenuItem

*Let the MenuItem select next "menu state" (MenuAndState)

*MenuAndState from the outside looks like MenuAndStateNG - i.e. something that just can be run to get next MenuAndStateNG. From the inside it is split into a "fixed part" (Menu) = header + list of items and "variable part" = state. By introducing this separation I was able to make userMenu actually a constant rather than def

*Most of the menu items doesn't change menu and just return to their parent. To simplify code for this scenario curMenu is passed as an argument to the doAction and there is a SimpleMenuItem that just always returns it\

Given such design all you need is:

*

*create a val for each menu item

*create mainMenu and userMenu vals  effectively as lists of those menu items

*run an infinite loop starting from the mainMenu (done in start)

Note that because MenuAndStateNG returns the next MenuAndStateNG from its runMenu I can use an infinite loop instead of deepening the stack on each menu iteration (which is generally a bad idea).


text:
Q: jQuery load() function cumulate delay until it fails I'm coding a site that will load all the content on a single page with jquery. Everything function works fine on itself, but when I begin to navigate, thus calling load functions one after the other, every instance is a bit slower, until the page completely crashes.
Is this a structural problem with ajax (i think not, but who knows?) or am I doing something wrong?
I sometimes have callback functions in the load function, but them also works fine.
EDIT
Ok, I was just wondering wether it was something common, but apparently it is not, so I'll show you some code:
// click and load part
$("#about").click(function(){
    $("#c1").load('<?php echo get_site_url(); ?>/?page_id=5',
        layout();
    });
});

//callback function, basically some css injection
function layout() {
        windowHeight = $(window).height();
        $(".column-content").css('height',windowHeight-(containerTop+20)+'px');
        $(".column-content_mode").css('height',windowHeight-(containerTop+60)+'px');
        $(".container-column").css('height',windowHeight-(containerTop+20)+'px');
}

Everything is wrapped within a $(document).ready({ //all the js });
Thank you a lot for the quickness of your intervention.

A: Without looking at your code, I can tell you the most common cause for this problem:
$(function() {
    $('#target').load('/your/url', function() {
        $('.someclass').click(function() {
            // Click handler for the new elements you just added
        })
    });
});

The problem here is that you are not only adding the handlers to the new elements that were just loaded, but you are also adding handlers to all of the existing elements on the page. It compounds exponentially!
To get around this, use the on method to add the handlers once, and it'll automatically add them for new elements.
$(function() {
    $('#target').on('click','.someclass',function() {
        // Click handler for the new elements you will add in the future
    });
    $('#target').load('/your/url', function() {
        // Nothing to do here now
    });
});

Edit
$("#about").click(function(){
    $("#c1").load('<?php echo get_site_url(); ?>/?page_id=5',
        layout();
    });
});

The second argument to load should be a function reference. Get rid of the () there so you don't immediately call that function. You just want to pass the name, not execute it. Also, your } is unmatched. Doublecheck it here.

A: Allright, so. It turned out that the failure was caused by the js recursively loading itself.
I did that by mistake because I wanted it to refresh each time an ajax event occurred.
Using $('#id').live('click', function(){...}); instead of $('#id').click(function(){...}); allowed me to refresh the js correctly and with no delay whatsoever.
Thanks everyone for your help!


text:
Q: How can I set the name for a file that is to be downloaded in a Koa response? I make a image proxy (to download a image not open) use node and koa.
the url /proxy/image code is :
...
const PassThrough = require('stream').PassThrough
let query = qs.parse(url.parse(ctx.request.url).query)
let passThroughStream = new PassThrough()
ctx.body = request(query.src).pipe(PassThrough())
...

The image downloaded name is image, but I want to rename the image, how could I do?

A: If I understand your question correctly, you should be able to do this by using ctx.attachment() which is an alias for ctx.response.attachment(). So you can do something like:
ctx.attachment('my-image.png')

This attachment method is basically a shorthand of the following header:
ctx.set('Content-disposition', 'attachment; filename=my-image.png');


text:
Q: How to relocate MyLocationView in Mapbox Android SDK? I want to change the location of MyLocationView in MapView of Mapbox. I don't want to use a custom marker. Because calculating bearing and adding this to a marker (like in navigation apps) is difficult for me(Sensor Fusion & GPS bearing should be done) and also MyLocationView is smoother than a marker in relocating and changing bearing operations. I'm continuing with Mapbox MyLocationView. I have done bearing tracking integration and showing location on the MapView. What i have done is:
mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(MapboxMap mapboxMap) {
        map = mapboxMap;

        map.setMyLocationEnabled(true);
        map.getTrackingSettings().setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
        map.getTrackingSettings().setMyBearingTrackingMode(MyBearingTracking.COMPASS);
        map.getTrackingSettings().setDismissBearingTrackingOnGesture(false);
        map.getMyLocationViewSettings().setForegroundDrawable(iconDrawable, iconDrawable);
        map.getMyLocationViewSettings().setBackgroundTintColor(Color.parseColor("#56B881"));
        map.getMyLocationViewSettings().setForegroundTintColor(Color.parseColor("#FFFFFF"));
        map.getMyLocationViewSettings().setAccuracyTintColor(Color.parseColor("#56B881"));
    }
});

My View:

So i want to ask is it possible to update MyLocationView's Location in Mapbox Android SDK? I do lots of search but i can not figure out that. Maybe there is a trick about this.

A: Firstly, you should implement ProgressChangeListener in your Activity from this package
com.mapbox.services.android.navigation.v5.listeners.ProgressChangeListener
After that in the next overrided method you can update your location
@Override
public void onProgressChange(Location location, RouteProgress
routeProgress) {
    Log.e(TAG, "onProgressChange" + location);
    Log.d(TAG, "onProgressChange: fraction of route traveled: %f"
    + routeProgress.getFractionTraveled());
    if(mapboxMap.getMyLocation()!=null){
         mapboxMap.getMyLocation().setLatitude(location.getLatitude());
         mapboxMap.getMyLocation().setLongitude(location.getLongitude());
    }
}

And for userOffRoute method from implemented OffRouteListener you can do the same.
Also I'd like to notice that in build.gradle I have next dependencies
compile('com.mapbox.mapboxsdk:mapbox-android-sdk:5.1.0@aar') {
    transitive = true
}
compile 'com.mapbox.mapboxsdk:mapbox-android-ui:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-services:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-telemetry:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.3.1'
compile 'com.mapbox.mapboxsdk:mapbox-java-core:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-geojson:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-services:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-services-rx:2.1.3'

A: I use listener and it works well
mapboxMap.setOnMyLocationChangeListener(myLocationChangeListener);
mapboxMap.setMyLocationEnabled(true);

private MapboxMap.OnMyLocationChangeListener myLocationChangeListener = new MapboxMap.OnMyLocationChangeListener() {

    @Override
    public void onMyLocationChange(@Nullable Location location) {

    }
};

after
 myLocationChangeListener.onMyLocationChange(location);


text:
Q: Need help in java algorithm for finding max and min I need to write a java algorithm that receive 5 numbers from type int and print the max and min by using only 6 times with the Conditional Exchange:
If (x>y) {
    Int tmp = x;
    x=y;
    y=x;
}

The problem is that I only manage to do this algorithm with 7 conditional exchange and not 6. Can someone help me to understand what I'm missing?
    Scanner myScanner = new Scanner(System.in);
    int a = myScanner.nextInt();
    int b = myScanner.nextInt();
    int c = myScanner.nextInt();
    int d = myScanner.nextInt();
    int e = myScanner.nextInt();

    if(a>b)
    {
        int tmp = b;
        b = a;
        a = tmp;
    }

    if(a>c)
    {
        int tmp = c;
        c = a;
        a = tmp;
    }

    if(a>d)
    {
        int tmp = d;
        d = a;
        a = tmp;
    }

    if(a>e)
    {
        int tmp = e;
        e = a;
        a = tmp;
    }

    if(b>e)
    {
        int tmp = e;
        e = b;
        b = tmp;
    }

    if(c>e)
    {
        int tmp = e;
        e = c;
        c = tmp;
    }

    if(d>e)
    {
        int tmp = e;
        e = d;
        d = tmp;
    }

    System.out.println(a);
    System.out.println(e);

A: Think about it like a merge sort: break the problem down to finding the min and max for pairs of numbers; then for pairs of pairs etc.
if (a >= b) swap(a, b); // logically swap them; you can't actually write a method to do this.

Now a = min(a, b) and b = max(a, b).
if (c >= d) swap(c, d);

Now c = min(c, d) and d = max(c, d).
if (a >= c) swap(a, c);
if (b >= d) swap(b, d);

Now a = min(a, b, c, d) and d = max(a, b, c, d).
Then it's just a matter of handling e:
if (a >= e) swap(a, e);
if (d >= e) swap(d, e);

The min is in a; the max is in e.

A: Comparing two pairs first, then you can save a comparison knowing than the first pair smaller must be compared with the second pair smaller and the first pair bigger must be compared with the second pair bigger. We have a number left that must be compared with the current smaller and bigger in case it fits there.
Implementation:
Scanner myScanner = new Scanner(System.in);
int a = myScanner.nextInt();
int b = myScanner.nextInt();
int c = myScanner.nextInt();
int d = myScanner.nextInt();
int e = myScanner.nextInt();

myScanner.close();

// First pair
if(a>e)
{
    int tmp = e;
    e = a;
    a = tmp;
}

// Second pair
if(c>d)
{
    int tmp = d;
    d = c;
    c = tmp;
}

// Smaller
if(a>c) {
    int tmp = a;
    a = c;
    c = tmp;
}

// Bigger
if(d>e) {
    int tmp = d;
    d = e;
    e = tmp;
}

// Remaining value bigger
if(b>e) {
    int tmp = b;
    b = e;
    e = tmp;
}

// Remaining value smaller
if(a>b) {
    int tmp = b;
    b = a;
    a = tmp;
}

System.out.println(a);
System.out.println(e);

A: // Compare your numbers in pairs, I've paired up a-b and c-d and e will be compared separately
Scanner myScanner = new Scanner(System.in);

int a = myScanner.nextInt();
int b = myScanner.nextInt();
int c = myScanner.nextInt();
int d = myScanner.nextInt();
int e = myScanner.nextInt();

int min ; int max ;
int min1 = a, max1 = b;
int min2 = c, max2 = d ;

if(a > b ){
      min1 = b ;
      max1 = a ;
      // Here I set original min and max to min1 and max2 to save extra conditionals
      min = min1 ;
      max = max1 ;
}

if(c > d ){
      min2 = b ;
      max2 = a ;
}

if(min1 > min2)
      min = min2 ;
if(max2 > max1)
      max = max2 ;

// One last comparison for e and we've found what were looking for :)
if( e > max){
      max = e ; }
if( e < min){
      min = e ; }

A: Put Every single element in an Array (arr1), And then import collections and Arrays
import java.util.Arrays;
import java.util.Collections;

int min = Collections.min(Arrays.asList(arr1));  // arr1 will be your array
int max = Collections.max(Arrays.asList(arr1));


text:
Q: What log entries should I expect after an unexpected Mac Mini reboot? My 2 GHz Intel Core 2 Duo Mac Mini suffers unexpected shut-downs from time to time.
I suspect this is because it gets too hot - iStat Menu shows the CPU temperature reaching 98 C when it's working hard.  However, after the reboot there's nothing at all in the Console logs to indicate what went wrong.
Is there somewhere else I can look for log entries that would help me diagnose this ?

A: If it's getting hot under load, and you're not doing anything that you've not been doing before, I'd suspect it's more physical factors than software problems, more specifically inadequate cooling! You should open the machine and check for dust and operation of any and all fans.  You might also consider removing, reapplying thermal paste, and reseating the heatsink on the processor, although that may be easier said than done in a small-form factor Mac (I'm not familiar with the internals on this so I couldn't say myself).


text:
Q: MYSQL Recuperar copia me encuentro con una situación que no se me había dado hasta ahora.
Tengo una aplicación cuya base de datos es MYSQL. El otro día algo pasó y se perdieron algunos registros.
Ahora me han recuperado la copia de la madrugada en la que paso es perdida y he de recuperar algunos registros de dos tablas de la copia de seguridad.
Lo que me han recuperado es el contenido de la carpeta DATA del MYSQL pero ahora no se como añadir dicha copia con otro nombre para poder extraer los datos que faltan.
Agradezco toda ayuda. Gracias

A: Gracias al amigo Track3r lo he resuelto de esta manera.
La copia del MYSQL es sistema innodb y lo que he hecho ha sido llevar la copia a otro server, la he añadadido y una vez añadida y visible he sacado los datos que me faltaban con un dump y finalmente los he recuperado en la base de datos buena.
Gracias Track3r


text:
Q: PHP - Limit number of invoices by user based on subscription package i'm building this CRM system which providing small business owners to manage their clients & billing.
on my system there is 3 subscription packages

*

*Free (30 days)

*Gold (1 year)

*Silver (6 months)

free - free package is available for users with no price & users on this package will be able to manage 3 clients & 12 invoices.
Gold - gold users package is a paid  one & users on gold package will be able to manage unlimited clients & invoices.
Siliver - paid package, 50 clients & 100 invoices
what i need to know is how can i limit the number of invoices & clients created  by a user using php & MYSQL
i would like if some one can explain me in detals.
Help appreciated.

A: Well, whenever a user clicks on the 'create new invoice' or 'create new client' button, you count how many exist already. If more than allowed, tell the user he needs to upgrade.

A: Create another table in your database and log the number of invoices and clients remaining for each user. Then every time your users create either a client or an invoice, you check if there are invoices remaining and decrement accordingly.


text:
Q: How to save a figure in MATLAB from the command line? Is there a command in MATLAB which allows saving a figure in FIG or JPEG or both formats automatically?

A: Use saveas:
h=figure;
plot(x,y,'-bs','Linewidth',1.4,'Markersize',10);
% ...
saveas(h,name,'fig')
saveas(h,name,'jpg')

This way, the figure is plotted, and automatically saved to '.jpg' and '.fig'. You don't need to wait for the plot to appear and click 'save as' in the menu. Way to go if you need to plot/save a lot of figures.
If you really do not want to let the plot appear (it has to be loaded anyway, can't avoid that, else there is also nothing to save), you can hide it:
h=figure('visible','off')

A: When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:
hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');

This will do exactly as manually saving the figure.
source:
http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C

A: I don't think you can save it without it appearing, but just for saving in multiple formats use the print command. See the answer posted here: Save an imagesc output in Matlab

A: If you want to save it as .fig file, hgsave is the function in Matlab R2012a.
In later versions, savefig may also work.

A: imwrite(A,filename) writes image data A to the file specified by filename, inferring the file format from the extension

A: These days (May 2017), MATLAB still suffer from a robust method to export figures, especially in GNU/Linux systems when exporting figures in batch mode. The best option is to use the extension export_fig
Just download the source code from Github and use it:
plot(cos(linspace(0, 7, 1000)));
set(gcf, 'Position', [100 100 150 150]);
export_fig test2.png

A: try
plot(var);
saveFigure('title');
it will save as a jpeg automatically


text:
Q: Half-life and muon decay Imagine that we have a single muon. It has a life span of 2.2 microseconds on average. So normally, after that amount of time, the muon will decay.
Now imagine we have two groups of muons. Group A has 20 muons and the other group, B , 10 muons. Since muons have a half life of 2.2 microseconds, group A will lose 10 muons in that time but group B will lose 5 muons. Why is this so? If the a sinle muons decays in 2.2 microseconds, normally, all the muons should decay in that time as they are all muons and so decay in 2.2 microseconds. Group A lost more muons in the same time than group B. This can only be if the muons in group a decayed faster than the muons in group B. how can this be? Is the life of muons inversely proportional to the amount of muons present?

A: Imagine two groups of students, where group A has 20 members and group B has 10.  Each student flips a coin, and we find that 10 coins from group A and 5 coins from group B land face-up.
Does the probability of the coin landing face-up depend on the size of the group?  No, of course not.  The probability of a coin landing face-up is simply 1/2, which means that we'd expect to see it in about half of the coins in a group of any size.  Larger groups flip more heads because more coins are being tossed, that's all - and precisely the same is true for radioactive decay.

A: No, muon decay is a statistical process with a constant half life. After  2.2 microseconds there is a 50% chance that the muon has decayed. This means that on average half of the muons have decayed. For group A half is 10 and for B it is 5. Note that muons that are generated in the atmosphere by cosmic rays live much longer as they travel at near light speed.

A: Imagine you had two group Bs each with 10 muons at the start.
According to your arithmetic both group Bs will have have lost 5 muons after 2.2 microseconds ie two groups of type B have lost 10 muons in total.
So two group Bs do exactly the same as one group A.


text:
Q: In Magento2 file_get_contents any library i am using file_get_contents in magento2 is there any framework or core function for this already in magento2?

A: Have a look at the Interfaces available inside Magento\Framework.
For example, Magento\Framework\Filesystem\DriverInterface gives you access to a fileGetContents function:
/**
 * Retrieve file contents from given path
 *
 * @param string $path
 * @param string|null $flag
 * @param resource|null $context
 * @return string
 * @throws FileSystemException
 */
public function fileGetContents($path, $flag = null, $context = null);

Which is implemented inside Magento\Framework\Filesystem\Driver
/**
 * Retrieve file contents from given path
 *
 * @param string $path
 * @param string|null $flag
 * @param resource|null $context
 * @return string
 * @throws FileSystemException
 */
public function fileGetContents($path, $flag = null, $context = null)
{
    clearstatcache();
    $result = @file_get_contents($this->getScheme() . $path, $flag, $context);
    if (false === $result) {
        throw new FileSystemException(
            new \Magento\Framework\Phrase(
                'Cannot read contents from file "%1" %2',
                [$path, $this->getWarningMessage()]
            )
        );
    }
    return $result;
}

Hope this helps.

A: In case file located in your filesystem, use Magento\Framework\Filesystem\Driver
In case you have to fetch file content from URL try Magento\Framework\HTTP\ClientInterface
$this->clientInterface->get($url);
$fileContent = $this->clientInterface->getBody();


text:
Q: Java JXTA - where is the JAR file? Where can I download JXTA/JXSE? I mean the JAR file of this library, because I found project code here
http://java.net/projects/jxta-jxse/sources/svn/show
downloaded by SVN and I have no idea how to link all classes this to NetBeans.
any help please?

A: See this download page. You can manually download artifacts/jars from there.


text:
Q: when should one add a column as an index to a dataframe in pandas I am a bit confused about when one should make a column an index in a df. My understanding was that indices identified unique observations within the df (i.e. id, time for example). However, why have those be an index instead of just columns in the df? It looks as if pretty much all operations in pandas can be done using columns rather than indices (merge, selection using query, etc). There must be very specific cases when indices prove beneficial: could someone provide some examples?

A: Probably faster look up will be possible if you make an index from a column.
Check this out, https://stackoverflow.com/a/27238758/9968677


text:
Q: Magento 2 : Change store view when currency is changed Is it possible to change the store view when currency is changed?
For example, On my site, I have 3 currency and 3 stores view, Now when I'm switching my currency USD then storeview also needs to change to an English store view.
Can anyone help me to do that?
Any help would be appreciated thanks in advance.

A: You should use post dispatch event and check fullaction name

event name :: controller_action_postdispatch

action name :: directory_currency_switch

PHP file

    public function execute(\Magento\Framework\Event\Observer $observer) {
        if ($this->_request->getFullActionName() == 'directory_currency_switch'){
            // your condition to change store view here
        }
    }