text:
Q: Improve a car battery's performance with capacitors These days, it got very cold in my area, and I started to think I need a new car battery. But then, as long as temperatures are above -10°C, my battery works fine. It just can't support the high current needed to start the engine when the temperatures are below -10°C. So my thought was:
Can I add capacitors to my car battery, that will help supply the needed current?
I found 6 Capacitors with \$2.7\text{ V}\$ and \$500\text{ F}\$ each on ebay for a total of 25$. If I put them in series, their capacitance should be \$\frac{1}{\frac{1}{500}\cdot6}\approx 83\text{ F}\$ at \$16.2 \text{ V}\$.
The energy in watt seconds would then be:
\$0.5\cdot83\cdot16.2^2\approx 10891 \text{ Ws}\$, which should be enough to start my small little engine (small gasoline engine rarely takes more than a second to start, even in cold temps, so that would be about 130 Amps for one sec).
Unfortunately, that's about as far as my knowledge of electronics goes. Can I really just attach the 6 Capacitors, which I connected in series, to the Battery? Is there something here I am not seeing, which would make it extremely impractical to do that? I can't seem to find anyone on the Internet doing this, which makes me sceptical. There are some people that use capacitors instead of batteries, but that seems like a bad idea to me since it won't last more than one start...

A: Putting capacitors in series to add up their voltage ratings isn't very wise. Their difference in leakage current will lead to an imbalance in the voltage they'll have across them (see https://electronics.stackexchange.com/a/80589/107479), and some of the capacitors could easily experience overvoltage (especially given the low voltage ratings supercapacitors have). The solution for that would be to add a resistor ladder in parallel to compensate this, but that would increase your standby battery drain, which is not a good idea either.
Moreover, your computation is wrong, since the capacitor will be charged to the battery voltage (~13V), not the full capacitor voltage rating. And I doubt it requires less than one second to start.
And, when you say in your comment:

The top rated answer in the post that PlasmaHH linked, suggests doing exactly what I want to do, using capacitors in addition to the batterie, so the battery can store lots of energy, and the capacitor can deliver it at high rates for short times.

you're mistaken: this answer you're referring to, when it mentions "short times", it means "a few ms", for example to smooth the big current spikes due to the inrush of the starter. Not for the starter the whole starting time. This is where it begins not making sense.
Finally, if your car doesn't start when it is -10°C outside, you simply have a problem somewhere with your car. Bring it to your mechanic. He'll fix it, and he surely won't fix it by adding capacitors. He'll find the actual faulty component (which, by the way, you don't seem to have really checked - you're assuming it's the battery, but it could be anything: glow plug/starter motor/some sensors/whatever/...) and replace it (because when such a component starts to fail, trying to fix it by adding capacitors or duct tape is futile - you replace it).

A: There is a company that sells capacitor banks that completely eliminate the need for a lead acid storage battery for automotive as well as other applications. Since they are non chemical based they are not affected as much by  extreme low temperatures. Here is a link to check out and tease yourself silly with ideas.
http://www.maxwell.com/products/ultracapacitors/cells
This link contains specs as well as product line and company contact info. I read somewhere a while ago that these units will charge in about 3 secs.

A: Using supercapacitors to boost overall starting current is good, but there are several practical limitations:

*

*You would need short (and thick) wires to connect the supercap pack to the battery (so you do not add too much wire resistance in series with caps), which means the supercaps will have to most likely sit inside the hood. Engine can get very hot and so do the caps. You will have to make sure the caps do not get damaged at the highest temperature they can see inside the hood. You may have to find a place where it is not too hot and measure the temperature at that spot with a thermometer when running the car for certain time to verify that it is indeed a good spot to anchor the capacitor pack.

*Nominally the alternator may provide 13.8V to charge the battery. But I have seen it going to 14.4V when I crank up the engine. Since we are dealing with the magnetic circuit of the alternator, load dumps, etc. it is possible that the battery will sometimes see voltage spikes that are much higher than 14.4V, or 15V or even 16V. If a supercap is rated at 2.7V and you have six or seven in series across the battery, you will have to make sure that each cap will not see more than its rated voltage any time, i.e. you may need protection circuitry (mainly transient absorbers) across each supercap in the pack. You will have to then watch out for the leakage current in the transient absorbers when they are not active.

*If you connect a bunch of capacitors in series, the voltage across them when charged may not be equal. The voltage depends on the actual value of the capacitance of each supercap. Usually there is a tolerance to the value of all capacitors. I have seen supercaps having as much as +/-20% tolerance in their value. I.e. a supercap with nominal capacitance of 500F may have actual value anywhere between 400F and 600F. Unless you can screen many supercaps and pick those with values within a small range, you are stuck with what you get. A +/-20% variance in capacitance translates to a similar variation in voltage across the caps when connected in series and connected across the battery. i.e. If you have six supercaps in series, connected across a 12V battery, they will not have 12/6=2V across each (Q=CV, so V=Q/C, all caps in series will have the same amount of charge because the current going through them when charging will be the same since they are in series). Caps with smaller capacitance (say 400F) will have higher voltage across them than the caps with bigger (600F) capacitance. You will have to have enough caps in series so that because of tolerance of capacitance, voltage across a cap never exceeds its rated voltage or it will develop defects and either become useless (i.e. develop intrenal short circuit) or burn up. People use charge (i.e. voltage) balancing circuits across each cap to equalize voltage across all caps. But these circuits can have leakage current, so when the car engine is off, they are draining the battery.

*Even without charge balancing circuits across them, supercaps have their own leakage current. Leakage current can be tens to hundreds of micro Amps. That is not much, but if you have not started a car in a long time for any reason, it all adds up. There are super-low-leakage supercaps but they come with price premium.

You can make your supercap string across car battery work, but please make sure you have addressed all the above issues. If you have overcome them, please post your solution so the rest of us can learn from it.

*

*Anoop Hegde

A: Conceptually sound but not likely to work in practice. The starter needs lots of current, and you will need a lot of capacitance to make a difference.

A: Simple solution - get a car starter kit and keep it somewhere warm.
For example

The market offers plenty of small jump starters for every purpose, but
  which packs the most punch? Here's our verdict

A: I added six 2.7V 500F supercapacitors in series with a protection board and that drained my car battery in six hours, so I decided to remove all the protection boards and not use them.  Now I have seven 2.7V 500F supercapacitors in series and paralleled with my car battery. Everything works perfectly.  The capacitor does not over charge since my alternator maximum charge is only 13.8V.
My supercapacitors in series have 18.9V and 71.4 farads total.
Make sure you install an 80A fuse as protection.

A: What a lot of these people seem to misunderstand is what is nede dto stat s motor is power.  As the bat can not cope with demand its votage drops,  and  as the volts drop the cap  releases.its stored power.  Lots of vids on u tube.  Seems like drop in voltage starting is less than a third.  EVEN BETTER when it's cold and battery IS LESS EFFICIENT.  Yes people have tried caps only but I would be inclined to have both.  Need to disconnect caps when goes to garage for service, and probably precharge before connecting to bat.  I EXPECT REDUCING STRESS on battery will give it a longer life so I would do it to cope with a year then get new bat which will last longer.
Best of luck and please feed in reports on how it worked.  Ps  I understand in deep cold caps are more efficient  must be even better..


text:
Q: What is the distribution of the sum of independent normal variables? Just need to check the answer for the following question:
Question
Suppose $X$ and $Y$ are two independent standard normal variables:
$X \sim \mathcal N (0,1)$
$Y \sim \mathcal N (0,1)$
What is the distribution of $X + Y$ ?
My Working
$X+Y \sim \mathcal N ( \mu_1 + \mu_2$, $\sqrt{\sigma_1^2 + \sigma_2^2}) $
$= X+Y \sim \mathcal N (0 + 0$,$\sqrt{1^2+1^2}) $
$= X+Y \sim \mathcal N ( 0, \sqrt{2}) $
Does this look correct?

A: To sum up the long series of comments:
Yes, your working is correct.  More generally, if $X$ and $Y$ are independent
normal random variables with means $\mu_X$, $\mu_Y$ respectively
and variances $\sigma_X^2$ and $\sigma_Y^2$ respectively, then
$aX+bY$ is a normal random variable with mean $a\mu_X+b\mu_Y$
and variance $a^2\sigma_X^2 + b^2\sigma_Y^2$.
The various comments by whuber, cardinal, myself, and the Answer
by Tai Galili are all occasioned by the fact that there are at least
three different conventions for interpreting $X \sim N(a,b)$ as
a normal random variable.  Usually, $a$ is the mean $\mu_X$
but $b$ can have  different meanings.

*

*$X \sim N(a,b)$ means that the standard deviation of $X$ is $b$.
(This is the convention you are using).

*$X \sim N(a,b)$ means that the variance of $X$ is $b$.

*$X \sim N(a,b)$ means that the variance of $X$ is $\dfrac{1}{b}$.
Fortunately, $X \sim N(0,1)$ (which is what you asked about)
means that $X$ is a standard
normal random variable in all three of the above conventions!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems logging out - have to click logout twice I'm hoping someone can help with an issue which, intuitively, should be simple, but the answer eludes me.  For some reason, when my user logs out, he has to click log out twice to make it work.   I've read this:
Any idea why I have to click the logout button twice to logout?
But it doesn't seem to be working.  Here is my logout button code.  Any thoughts?  Thank you!

    <?php
    include('includes/APILogin.php');

    if ( isset( $_POST['logout_btn'] ) )
    {
        unset($_COOKIE['kp_emailID']);
        unset($_COOKIE['kp_pass']);
        session_destroy();
    }

    // Check for login cookie - skip if session is available
    if ( isset($_COOKIE['kp_emailID']) && isset($_COOKIE['kp_pass']) && !isset($_SESSION['kp_accountID']) )
    {
        $username = $_COOKIE['kp_emailID'];
        $pass = $_COOKIE['kp_pass'];
        $get_account_parameters = array(
                               'session' => $session_id,
                               'module_name' => 'kd_kp',
                               'query' => "kd_kp_cstm.username_c = '" . $_COOKIE['kp_emailID'] . "'",
                               'order_by' => "",
                               'offset' => '0',
                               'select_fields' => array(
                                                    //'username_c',
                                                    //'password_c',
                                                    //'id',
                                                    //'name',
                                                    ),
                               'link_name_to_fields_array' => array( ),
                               'max_results' => '1',
                               'deleted' => '0',
                               'Favorites' => false,
                               );
        $get_account_result = call('get_entry_list', $get_account_parameters, $url);
        //echo '
'; print_r($get_account_result); echo '
';

        if ( $_COOKIE['kp_pass'] != $get_account_result->entry_list[0]->name_value_list->password_c->value )
        {
            // not logged in
            session_unset();
            session_destroy();
            ?>

                    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
                        <input type="text" placeholder="EMAIL" value="<?=$_COOKIE['kp_emailID']?>" name="signIn_email" id="signIn_email"/>
                        <input type="password" placeholder="PASSWORD" id="signIn_pwd" name="signIn_pwd" />
                        <input type="submit" value="SIGN IN" name="login_btn" id="login_btn" />

                    </form>

            <?php
        } else {
            // is logged in
            $_SESSION['kp_accountID'] = $get_account_result->entry_list[0]->name_value_list->id->value;
            $_SESSION['kp_name'] = $get_account_result->entry_list[0]->name_value_list->name->value;
            // set cookies
            $hour = time() + 3600;
            setcookie("kp_emailID", $get_account_result->entry_list[0]->name_value_list->email1->value, $hour, "/", "kp.com");
            setcookie("kp_pass", $get_account_result->entry_list[0]->name_value_list->password_c->value, $hour, "/", "kp.com");
            ?>

WELCOME, <?=$get_account_result->entry_list[0]->name_value_list->name->value?>
                <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
                <input type="submit" value="LOG OUT" name="logout_btn" id="logout_btn" />
                </form>

            <?php
        }
    }

    //if the login form is submitted
    if ( isset( $_POST['login_btn'] ) )
    {
        // checks it against the database
        if ( !get_magic_quotes_gpc() )
        {
            $_POST['signIn_email'] = addslashes($_POST['signIn_email']);
        }

        $get_account_parameters = array(
                                       'session' => $session_id,
                                       'module_name' => 'kd_kp',
                                       'query' => "kd_kp_cstm.username_c = '".$_POST['signIn_email']."'",
                                       'order_by' => "",
                                       'offset' => '0',
                                       'select_fields' => array(
                                                    //'username_c',
                                                    //'password_c',
                                                    //'id',
                                                    //'name',
                                                    ),
                                       'link_name_to_fields_array' => array( ),
                                       'max_results' => '1',
                                       'deleted' => '0',
                                       'Favorites' => false,
                                       );
        $get_account_result = call('get_entry_list', $get_account_parameters, $url);

        //Gives error if user dosen't exist
        if ( $get_account_result->result_count == 0 )
        {
            ?>

                Click Here to Register

            <?php
        }

        $_POST['pass'] = md5( stripslashes($_POST['signIn_pwd']) );

        //gives error if the password is wrong
        if ( $_POST['pass'] != stripslashes($get_account_result->entry_list[0]->name_value_list->password_c->value) )
        {
            //if ( !isset($get_account_result->entry_list[0]->name_value_list->password_c->value) )
            {
            ?>

                    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
                    <input type="text" placeholder="EMAIL: TRY AGAIN" name="signIn_email" id="signIn_email"/>
                    <input type="password" placeholder="PASSWORD" id="signIn_pwd" name="signIn_pwd" />
                    <input type="submit" value="SIGN IN" name="login_btn" id="login_btn" />

                </form>

            <?php
            }
            //echo '
'; print_r($_POST); echo '
';
        } else {
            // if login is ok then we update session vars
            $_SESSION['kp_emailID'] = stripslashes($_POST['signIn_email']);
            //$_SESSION['kp_pass'] = $_POST['pass'];
            $_SESSION['kp_accountID'] = $get_account_result->entry_list[0]->name_value_list->id->value;
            $_SESSION['kp_name'] = $get_account_result->entry_list[0]->name_value_list->name->value;
            ?>

WELCOME, <?=$get_account_result->entry_list[0]->name_value_list->name->value?>

             <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
                <input type="submit" value="LOG OUT" name="logout_btn" id="logout_btn" />
                </form>

            <?php
        }
    } else {
        // check for active session
        if ( isset($_SESSION['kp_accountID']) )
        {
        ?>

WELCOME, <?=$_SESSION['kp_name']?>

            <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
            <input type="submit" value="LOG OUT" name="logout_btn" id="logout_btn" />
            </form>

        <?php
        } else {
        // if they are not logged in
        ?>

            <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
                <input type="text" placeholder="EMAIL" name="signIn_email" id="signIn_email"/>
                <input type="password" placeholder="PASSWORD" id="signIn_pwd" name="signIn_pwd" />
                <input type="submit" value="SIGN IN" name="login_btn" id="login_btn" />

            </form>

    <?php
        }
    }

    //echo '

'; print_r($_POST); echo '

';
    //echo '

'; print_r($_SESSION); echo '

';
    //echo '

'; print_r($_COOKIE); echo '

';
    ?>

Thank you!

A: Probably because this code isn't running before the part of the page that shows the user is logged in loads. Thus, the HTML shows that he is logged in but really he isn't.

A: After you destroy the session, redirect to the login page, so that the page refreshes.

A: The browser doesn't recognize cookie changes until after a page reload.
Your first click is unsetting the cookies, but the user remains logged in.
Your second click is "reloading" the page, where the cookies are now unset, and it appears to work.
Add a redirect to the same page (after unsetting and destroying the session) to simulate a refresh, and your button should work.
p.s.
This is a simplified version of how cookies work, but it's basically accurate.
Since you're unsetting the cookie on the server, you have to request the page again to be given the new http headers that DON'T contain the old cookie information.  That's what the reload would do.

A: If you are logged into a third party website via FB, you must log out twice to complete the logout.


text:
Q: delta writestream .option("mergeSchema", "true") issue I have a delta table of 3 columns with data. Now, I have an incoming data with 4 columns so the DF.writeStream has to update the data location atleast with 4 columns automatically, so we can recreate the table on the top of the data location. hence the old records will have nulls in the newly added columns, and the recent data will have 4 columns populated
eg:
id  name   addr             id  name   addr   phone
1   lok    UK      ---->     1  lok    UK     null
                             2  ram    US     +1234

but while I use the following command as per databricks wesite, it shows,
 df.writeStream
      .option("mergeSchema", "true")
      .format("delta")
      .outputMode("append")
      .option("path","/data/")
      .option("checkpointLocation","/checkpoint/")
      .start()
      .awaitTermination()

ERROR: A schema mismatch detected when writing to the Delta table
To enable schema migration, please set:
'.option("mergeSchema", "true")'.

But I am already using mergeSchema in options. Please advice..
NOTE: .saveAsTable or .table functions are also not allowed in writeStream

A: You probably need to change the checkpoint location.
For details, see the document here .

A: You can try using foreach batch and then write the batch as delta format. This works for me.


text:
Q: Android keep send information to server I built a similar app Shazam, however it only works in sending an entire file of 10seconds of audio.
My doubt is: In android, there's any thing to keep like Shazam of while music is playing and the database is searching? Or it's own Shazam service technology?

A: Shazam developed that audio fingerprint matching technlogy. It's not available in the default Android SDK.

A: The Shazam technology is proprietary. The base algorithm was documented since by its creator:

The algorithm uses a combinatorially hashed time-frequency constellation analysis of the
  audio, yielding unusual properties such as transparency, in which multiple tracks mixed together may each be identified.

This is very novel and efficient, but the principles for fingerprinting audio stay the same. Among which certainly a FTT (fast fourier transform) to at least detect the BPM. Its even possible to convert sound to an image (the simplest being a spectogram), which can be further processed by audio-unrelated software.
If you need an audio analysis library, written in Java you could look into MusicG for example which is said to be simple to use on Android.


text:
Q: What is the formula behind Scikit-learn PolynomialFeatures? Whenever I am using Sklearn's Polynomial Features and converting 'X' values to make it Polynomial by this code,
Before that My X value are:-
[[ 1 11]
 [ 2 12]
 [ 3 13]
 [ 4 14]
 [ 5 15]
 [ 6 16]
 [ 7 17]
 [ 8 18]
 [ 9 19]
 [10 20]]

Note: It has multiple X values that mean it has more than one independent variable
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
print(X_poly)

Sklearn is returning this matrix having more columns besides having all Squared values,
[[  1.   1.  11.   1.  11. 121.]
 [  1.   2.  12.   4.  24. 144.]
 [  1.   3.  13.   9.  39. 169.]
 [  1.   4.  14.  16.  56. 196.]
 [  1.   5.  15.  25.  75. 225.]
 [  1.   6.  16.  36.  96. 256.]
 [  1.   7.  17.  49. 119. 289.]
 [  1.   8.  18.  64. 144. 324.]
 [  1.   9.  19.  81. 171. 361.]
 [  1.  10.  20. 100. 200. 400.]]

I have seen this Stackoverflow Answer https://stackoverflow.com/a/51906400/12188405 when I web searched for my issue.
So can anyone please tell me a general formula OR a python code that can return that matrix respective to any degree value? In simple words, I want to make a python program that can do it having one Parameter that is a degree (which can be any value from 0 to infinity) and it will return me that Matrix-like Sklearn gives.

A: I suggest you read the source code of Sklearn PolynomialFeatures in this link.
It has two different options:

*

*interaction_only=True

*

*combinations('ABCD', 2) AB AC AD BC BD CD

*interaction_only=False

*

*combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD

The first one uses the combinations method of itertools package, and the second one uses combinations_with_replacement for creating new features.

A: You could use the get_feature_names()  method to check the names of the columns in the returned matrix:
from sklearn.preprocessing import PolynomialFeatures
import numpy as np

X = np.arange(6).reshape(3, 2)

poly = PolynomialFeatures(10)
poly.fit(X)
poly.get_feature_names(['first', 'second'])

which will output
Out[12]:
['1',
 'first',
 'second',
 'first^2',
 'first second',
 'second^2',
 'first^3',
 'first^2 second',
 'first second^2',
 'second^3',
 'first^4',
 'first^3 second',
 'first^2 second^2',
 'first second^3',
 'second^4',
 'first^5',
 'first^4 second',
 'first^3 second^2',
 'first^2 second^3',
 'first second^4',
 'second^5',
 'first^6',
 'first^5 second',
 'first^4 second^2',
 'first^3 second^3',
 'first^2 second^4',
 'first second^5',
 'second^6',
 'first^7',
 'first^6 second',
 'first^5 second^2',
 'first^4 second^3',
 'first^3 second^4',
 'first^2 second^5',
 'first second^6',
 'second^7',
 'first^8',
 'first^7 second',
 'first^6 second^2',
 'first^5 second^3',
 'first^4 second^4',
 'first^3 second^5',
 'first^2 second^6',
 'first second^7',
 'second^8',
 'first^9',
 'first^8 second',
 'first^7 second^2',
 'first^6 second^3',
 'first^5 second^4',
 'first^4 second^5',
 'first^3 second^6',
 'first^2 second^7',
 'first second^8',
 'second^9',
 'first^10',
 'first^9 second',
 'first^8 second^2',
 'first^7 second^3',
 'first^6 second^4',
 'first^5 second^5',
 'first^4 second^6',
 'first^3 second^7',
 'first^2 second^8',
 'first second^9',
 'second^10']


text:
Q: Android alarmmanager not being very reliable I am having a problem with the Alarmmanager functions for the Android.
The problem is alarms that have over an hour or so to wait fail to go off.
My application initially creates an alarm like so:-
PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
             am.set(AlarmManager.RTC_WAKEUP, mCal.getTimeInMillis(), sender);

When the alarm goes off it triggers my RecieverHandler class, specifically this function:-
public void onReceive(Context context, Intent intent)
    {
        try {
             Bundle bundle = intent.getExtras();

             Intent newIntent = new Intent(context, MessageDispatcher.class);
             newIntent.putExtras(bundle);
            // newIntent.addFlags(Intent.FLAG);
             context.startService(newIntent);

            } catch (Exception e) {
             Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
             e.printStackTrace();

            }

    }

This then launches a service by the name of MessageDispatcher and this function is called:-
public int onStartCommand(Intent intent, int flags, int startId)

This function gets the next alarm time from my Database, this I am sure is working correctly, it then sets a new alarm based on the date from the database like so:-
PendingIntent sender = PendingIntent.getBroadcast(this, 192837, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, mCal.getSendAt().getTimeInMillis(), sender);

This creates the alarm for the next message.
I have tested this over a short amount of time and it appears to work and have tested it over large amounts of time by changing my date and time within the phone. It appears to fire off successfully.
Then when this alarm goes off it gets the next alarm to go off and schedules this. I am nearly 100% sure these parts are working fine.
So I am stuck with only some theories of why it's not working.
I thought it might be related to me disconnecting the phone from the debugger but the alarm seems to work over short amounts of time in that case.
So my main theory is that the alarmmanager I am creating is being deleted after a certain amount of time? If this is true this a big problem since I need this to be working no matter how much time has passed.
Any help into ensuring my alarm remains is greatly appreciated, thanks.

A:
So my main theory is that the alarmmanager I am creating is being deleted after a certain amount of time?

Alarms that are registered remain registered until you cancel them, or until the next reboot, or until the user kills your application with a "task killer" on Android 2.1 and earlier.
You have not indicated:

*

*how you are determining whether the alarm is "going off"

*what the BroadcastReceiver is doing

Without that information, it is impossible to say where you are going wrong.
Make sure that either you are doing all your work in the BroadcastReceiver (if the work is very quick) or that you are maintaining your own WakeLock as you pass control to the IntentService that is doing the rest of the work. Check out WakefulIntentService for more.
Also, you might try to create unique Intents per alarm, rather than updating the current one in place. I am not aware that there is a particular problem here, but it makes me nervous.


text:
Q: Caesar cipher not decrypting When I try to decrypt a message, the output isn't what it should be. I looked up Caesar Cipher and I understand the concept, but from what I looked at everything seems to be right. Could it be that I'm using a switch statement?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void){
   char phrase[100], option, ph;
   int key;

printf("Would you like to encrypt (e) or decrypt (d)? \n");
scanf(" %c", &option);
    printf("Enter a message (100 characters or less): \n");
scanf(" %s", phrase);

            printf("Enter key: \n");
            scanf(" %i", &key);
switch(option){
    case 'e':
     {
        for(int i = 0; phrase[i] != '\0'; i++){
                ph = phrase[i];
                    if(ph >= 'a' && ph <= 'z'){
                        ph = ph + key;

                        if(ph > 'z'){
                            ph = ph - 'z' + 'a' - 1;
                        } //end of if
                        phrase[i] = ph;
                    } // end of if
                    else if(ph >= 'A' && ph <= 'Z'){
                        ph = ph + key;

                        if(ph > 'Z'){
                            ph = ph - 'Z' + 'A' - 1;
                        }
                        phrase[i] = ph;
                    } // end of else if
                } // end of for
                printf("Encrypted message: %s\n", phrase);
                break;
            } // end of case 'e'
    case 'd':
        {
            for(int i = 0; phrase[i] != '\0'; i++){
                    //~ phrase[i] = phrase[i] + 3;
                ph = phrase[i];
                    if(ph >= 'a' && ph <= 'z'){
                        ph = ph + key;

                        if(ph > 'z'){
                            ph = ph - 'z' + 'a' + 1;
                        }
                        phrase[i] = ph;
                    } // end of if
                    else if(ph >= 'A' && ph <= 'Z'){
                        ph = ph + key;

                        if(ph > 'Z'){
                            ph = ph - 'Z' + 'A' + 1;
                        } // end of if
                        phrase[i] = ph;
                    } // end of else if
                } // end of for
                printf("Decrypted message: %s\n", phrase);
                    break;
                } // end of case 'd'

    } // end of switch
} // end of function

GCC output for encrypting:
Would you like to encrypt (e) or decrypt (d)?
e
Enter a message (100 characters or less):
hello
Enter key:
3
Encrypted message: khoor

GCC output for decrypting:
Would you like to encrypt (e) or decrypt (d)?
d
Enter a message (100 characters or less):
khoor
Enter key:
3
Decrypted message: nkrru

A: Your encryption logic and decryption logic are the same, i.e. for decryption you're adding the key when you should be subtracting.  You also need to change the overflow check for going below 'a':
case 'd':
    {
        for(int i = 0; phrase[i] != '\0'; i++){
                //~ phrase[i] = phrase[i] + 3;
            ph = phrase[i];
                if(ph >= 'a' && ph <= 'z'){
                    ph = ph - key;   // subtract

                    if(ph < 'a'){    // switch wraparound check
                        ph = ph + 'z' - 'a' - 1;
                    }
                    phrase[i] = ph;
                } // end of if
                else if(ph >= 'A' && ph <= 'Z'){
                    ph = ph - key;   // subtract

                    if(ph < 'a'){    // switch wraparound check
                        ph = ph + 'Z' - 'A' - 1;
                    } // end of if
                    phrase[i] = ph;
                } // end of else if
            } // end of for
            printf("Decrypted message: %s\n", phrase);
                break;
            } // end of case 'd'


text:
Q: How do I access Apache error logs via the Terminal in Mac OS X 10.6.8? I am having trouble with serving up my rails app on a remote computer after upgrading from Rails 3.0 to 3.1. So I want to take a look at what exactly is going wrong when Apache attempts to start up my app and it fails. How can I find the errors that Apache (or maybe Passenger?) is throwing via the Terminal?

A: in terminal, have you tried
cat /var/log/apache2/error_log

A: only to complemente the others answers, I'm using the version 10.9.3 and to me, the address is:
/private/var/log/apache2

A: Try:
cat /private/var/log/apache2/error_log


text:
Q: Windows Command line : start blocking task which opens a window, ask that window to get focus I want to run a command that opens a blocking window, but since that window won't come to focus (and thus come out in front of all other windows) I'd like to tell it to do that.
However if I run :
 <blocking command> & <command to request focus>
 <rest of script>

this runs in parallel i.e. the <command to request focus> will execute without waiting for <blocking command> and then <rest of script> will immediately run.
This is bad for me because it looses the blocking effect. This is important to me, as the blocking command holds a temporary file which I need to delete in <rest of script> after <blocking command> has released it).
I tried to marry the following two approaches :

*

*Script to request focus which is composed of three subcommands (and I do not want this in a separate file because some of these subcommands depend on the value of local variables)

*Script to launch two commands in parallel and wait on all which offers to run a block in parentheses of start commands and waits on the end of the block.
 (
     start qtcreator.exe -block "$tmp"
     start echo (new ActiveXObject("WScript.Shell")).AppActivate("$tmp"); > focus.js ; cscript //nologo focus.js ; del focus.js
 ) set -P "="
 rm "$tmp";

The problem is I think : 1. is composed of multiple commands and 2. uses start : and it seems that start is supremely unhappy with multiple commands (indeed, it is hard to parse out when another command that start needs to run begins, or when the start command itself is finished).
I am also fully aware that when running in parallel, nothing promises me that my app will have opened its window as per the first command before window focus is requested as per the second command, but this is okay in my use case, and at worst I can implement a small waiting thing. I just want to know how to run those two things in parallel if they are more than just single commands, in a way that does not require of me to have batch files every where that are called (to hide the complexity).
Any suggestions ? Either for a command that nicely does both (open my blocking window and requests focus) or on how to run two commands in parallel ?


text:
Q: How can I export the total value of the APDEX index from Jmeter's hmtl report? I would like to take the total value of the apdex jmeter and copy this value to a database or file.
is it possible to do something like this?


text:
Q: Opening a file to read and write, create it if it doesn't exist I was trying to create a file in both read and write modes, but it doesn't create the file, what can be the problem?
This is code:
fstream file("NameFile.txt", ios::out| ios::in);

The program will start, but it will not create any files.

A: When you open the file using fstream:

*

*To read, the file is required to exist;

*To write you need to specify a write mode, ofstream would do that for you, but with fstream you need to do it yourself:

Replaces the contents of the file when you write (ofstream default mode).
  std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::trunc);
                                                                   ^^^^^^^^^^^^^^^

Appends to the existing data in the file when you write.
  std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::app);
                                                                   ^^^^^^^^^^^^^

Note that after reading or writing you'll need to set the offset position in the file, for instance:
std::string s = "my string";
std::string in;

file << s;
file >> in;

file >> in will not read anything, the position indicator is at the end of the file after file << s, you'll need to reset it if you want to read previously written data, for example:
file << s;
file.seekg(0);
file >> in;

This resets the read position indicator to the beggining of the file, before the file is read from, more about it here:
https://en.cppreference.com/w/cpp/io/basic_fstream

A: well, you initialized an object, now to create a file use
file.open();

see
fstream won't create a file


text:
Q: How to Find & Replace a String Within Files with Find / Grep / Sed I have a folder of 500 *.INI files that I need to manually edit. Within each INI file, I have the line Source =. I would like that line to become Source = C:\software\{filename}.
For instance, a dx4.ini file would need to be fixed to become: Source = C:\software\dx4
Is there a quick way to do this with Find, Grep, or Sed functions?

A: You can try with sed
For example
Input file contents:
file.txt
Source =
some lines..

script:
newstring='Source = C:\software\dx4'
oldstring='Source ='
echo `sed "s/$oldstring/$newstring/g" file.txt` > file.txt

After running the above commands
output:
Source = C:\software\dx4
some lines..

A: If you want to edit a file in a script, I think ed is the way to go. Combined with a shell for loop:
for file in *.INI; do
    base=$(basename "$file" .INI)
    ed -s "$file" <<EOF
/^Source =/s/=/= C:\\\\software\\\\$base/
w
EOF
done

(This does assume that filenames will not have newlines or ampersands in their names)

A: With GNU awk for the 3rd arg to match(), gensub(), and "inplace" editing:
awk -i inplace '
    match($0,/(.*Source = C:\\software\\){filename}(.*)/,a) {
        fname = gensub(/\..*/,"",1,FILENAME)
        $0 = a[1] fname a[2]
    }
1' *.INI

The above assumes you're running in a UNIX environment though your use of the term folder instead of directory and that path starting with C: and containing backslashes makes me suspicious. If you're on Windows then save the part between the 2 's (exclusive) in a file named foo.awk and execute it as awk -i inplace foo.awk *.INI or however it is you normally execute commands like this in Windows.

A: find *.ini -type -f > stack

while read line
do
sed -i s"@Source =@Source = C:\\software\\dx4@" "${line}"
done < stack

Assuming that a} You have sed with "-i" (the insert flag, which AFAIK is not always portable) and b} sed doesn't crap itself about a double escape sequence, I think that will work.


text:
Q: Git, lost my changes this prolebme is mainly because of bad wifi connection in the cafe I am in.
I did a number of changes on my local repo, eveyr time I did one I would push properly.
The latest one I did the Internet connection was on and off, so It did push and git log would show the commit , but git status showed a discrepancy between my local and remote.
Since my last push was a success, I thought I would do this
git fetch origin
git reset --hard origin/master

But crap, this got rid of all commit I did today and head is now some commit I did yesterday, and when I go to bitbucket to see the repo it doesn;t even show today's changes.
Someone please tell me I didn't just screw myself over? is there a solution for this?

A: Check the git reflog to see commit hashes for all your recent activity.
Git won't garbage collect unreachable commits for at least 2 weeks (unless you explicitely tell it to)
Alternatively, git log -g might help you:

-g, --walk-reflogs
Instead of walking the commit ancestry chain, walk reflog entries from
  the most recent one to older ones.


text:
Q: PHP Youtube Video displaying on page with database I'm making "Social Network" and i want to be able to display youtube video when user put in Youtube Link and some description, just like on Facebook.
I managed to make when user put link it display video from database, but i can't figure out how to not show video when user don't put link and I want to show Youtube video when user put a link and description and send it to database.
Can anyone help?
Update
if(preg_match("/youtube.com(.+)v=([^&]+)/", $url)) {
  preg_match("/v=([^&]+)/", $url, $matches);
  if(isset($matches[1])) {
    $test = 'http://www.youtube.com/embed/'.$matches[1];
  }
}

I've found this , this grabs everything i need , but when i type like: "link" and some text,
How can i stop taking all after link???


text:
Q: How to hide bottom system bar in android tablet I am developing an application for tablet only, where the requirement is to run the app on the full screen of the tablet.
For this I have used following code in my main activity:
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

This code snippet only removes the title bar and action bar. But in tablets, there is a bottom system bar (having home and back button). I also want to remove or hide this system bar too.
I have searched but there is only following solution:

*

*There is no API to remove or hide the system bar.

*You can use some android app to hide system bar. (for example:
surelock, hidebar, etc)

My question is :

*

*Is it really not possible in android?

*Above available app (i.e surelock, hide bar, etc) also hiding bar.
It means they are using something to do so. Can be use this
something in our app so the user will not require to download these
app seperatly.
Please guide me.
I know this is not a good idea. But My app is only for tablet having Android 4.0 or greater and that tablet will run only this single app so we do not need to go back and use home button. That's why my requirement is to use the app in full screen.

A: If you have root access you can use this code other wise it is not allowed
try{
    //REQUIRES ROOT
    Build.VERSION_CODES vc = new Build.VERSION_CODES();
    Build.VERSION vr = new Build.VERSION();
    String ProcID = "79"; //HONEYCOMB AND OLDER

    //v.RELEASE  //4.0.3
    if(vr.SDK_INT >= vc.ICE_CREAM_SANDWICH){
        ProcID = "42"; //ICS AND NEWER
    }

    //REQUIRES ROOT
    Process proc = Runtime.getRuntime().exec(new String[]{"su","-c","service call activity "+ ProcID +" s16 com.android.systemui"}); //WAS 79
    proc.waitFor();

}catch(Exception ex){
    Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}

See this

A: From Android API 4.0 and later you can use the following code to hide the bottom system bar.
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
          | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

A: This is not possible unless you've root access. Alternatively, you can create a launcher application.
Otherwise it will be beyond the scope of your Application to Hide System/Navigation bar.

A: After a lot of searching on the internet, I managed to get the System Bar to hide and appear in a 4.2 device using:
To Hide:
Runtime.getRuntime().exec("service call activity 42 s16 com.android.systemui");

Or use 79 instead of 42 for API less than 14. You may also need to include the SET_DEBUG_APP permission, in which case you need to have the application signed with the system key or installed in the /system/app/ directory.
To Show:
Runtime.getRuntime().exec("am startservice --user 0 -n com.android.systemui/.SystemUIService");

Alternatively some people have used the -a (instead of -n) option, though this was causing an error on my device:
Error: Not found; no service started.


text:
Q: how to connect these antennas wirelesslly? I know the qustion in little strange, but i need to connect between these three antennas by wireless channel (with distance d as a name) and  (what is the possible options)
also whats is the possible options for antennas or nodes (another shape in latex). so i can put it in the paper
and thanks

\documentclass[12pt,a4paper]{article}
\usepackage{circuitikz}
\usetikzlibrary{positioning}
\usetikzlibrary{shapes,arrows}
\tikzset{block/.style = {draw, fill=white, rectangle,
              minimum height=3em, minimum width=2cm},
    input/.style = {coordinate},
    output/.style = {coordinate},
    pinstyle/.style = {pin edge={to-,t,black}}
    radiation/.style={{decorate,decoration={expanding waves,angle=90,segment   length=4pt}}}

}
%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
  \begin{tikzpicture}[auto, node distance=2cm,>=latex']
\node[block](tx){Base Station};
\node[antenna] at (tx.east) {};
\node[block,below  = 2cm of tx](ttx){GSM900 Tower};
\node[antenna] at (ttx.east) {};
\node[block,right = 5cm of tx](rx){Sensor Node};
\node[antenna,xscale=-1] at (rx.west) {};
\end{tikzpicture}
\end{document}

Note: is saw this code in this website but i changed it

A: Another wireless option

\documentclass[12pt,a4paper]{article}
\usepackage{circuitikz}
\usetikzlibrary{positioning}
\usetikzlibrary{shapes,arrows,decorations.pathreplacing}
\tikzset{block/.style = {draw, fill=white, rectangle,
              minimum height=3em, minimum width=2cm},
    input/.style = {coordinate},
    output/.style = {coordinate},
    pinstyle/.style = {pin edge={to-,t,black}},
    radiation/.style={decorate,decoration={expanding waves,angle=12,segment length=4pt}}
}
%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
  \begin{tikzpicture}[auto, node distance=2cm,>=latex']
\node[block](tx){Base Station};
\node[antenna] at (tx.east) {};
\node[block,below  = 2cm of tx](ttx){GSM900 Tower};
\node[antenna] at (ttx.east) {};
\node[block,right = 5cm of tx](rx){Sensor Node};
\node[antenna,xscale=-1] at (rx.west) {};

\draw[radiation] ([shift={(1cm,2cm)}]tx.east)-- node [above=5mm] {d} ([shift={(-1cm,2cm)}]rx.west);

\draw[radiation] ([shift={(1cm,2cm)}]ttx.east)--node [below right=8mm] {d}([shift={(-1cm,2cm)}]rx.west);
\end{tikzpicture}
\end{document}

A: Something like this?

\documentclass[border=3mm]{standalone}
\usepackage{circuitikz}
\usetikzlibrary{arrows,calc,positioning,quotes}% added "calc" and "quotes"
\tikzset{%
    block/.style = {draw, fill=white, rectangle, minimum height=3em, minimum width=2cm},
    input/.style = {coordinate},
   output/.style = {coordinate},
 pinstyle/.style = {pin edge={to-,t,black}}
radiation/.style = {{decorate,decoration={expanding waves,angle=90,segment   length=4pt}}},
   zigzag/.style = {% added for solution
    to path={ -- ($(\tikztostart)!.55!-9:(\tikztotarget)$) --
                 ($(\tikztostart)!.45!+9:(\tikztotarget)$) -- (\tikztotarget)
             \tikztonodes},sharp corners}
        }

\begin{document}
  \begin{tikzpicture}[auto, node distance=2cm,>=latex']
\node[block](tx){Base Station};
\node[antenna] (ant1) at (tx.east) {};
\node[block,below  = 2cm of tx](ttx){GSM900 Tower};
\node[antenna] (ant2) at (ttx.east) {};
\node[block,right = 5cm of tx](rx){Sensor Node};
\node[antenna,xscale=-1] (ant3) at (rx.west) {};
% added as solution
\coordinate (A1) at ($(ant1)+(0.5,2)$);
\coordinate (A2) at ($(ant2)+(0.5,2)$);
\coordinate (A3) at ($(ant3)+(-0.5,2)$);
\draw[draw=red,very thick,shorten >=1mm,->] (A1) to [zigzag,"$d$"] (A3);
\draw[draw=red,very thick,shorten >=1mm,->] (A2) to [zigzag,"$d$"] (A3);
\end{tikzpicture}
\end{document}


text:
Q: Unable to start the Windows Phone Emulator I've seen this error several times. Each time I google deeply and finally made me reinstall my windows and all stuffs. Please help, I don't want to reinstall everything again. The error is:
Windows Phone Emulator

Unable to start the Windows Phone Emulator

Windows Phone Emulator is unable to start because
the hypervisor is not running. The likely cause is
that hardware-assisted virtualization is not enabled.

Check your computer's BIOS to ensure that hardware-
assisted virtualization and hardware-assisted data
execution features are enabled.

But yesterday I debugged really normally on Windows Phone using Emulator and I really sure
I've turned on Virtualization in BIOS and also in Turn Windows features on or off :

Sometimes when I hit f5 the IDE come with another error: 0x80131500

My PC: windows 8.1 ultimate 64b, 4gb ram, i3, Visual Studio 2013 RC3

A: If the accepted answer doesn't work for you - as it unfortunately did not for me - also be sure to enable Data Execution Prevention (DEP) in your BIOS.
The article below outlines what BIOS settings to enable for Hyper-V:
https://msdn.microsoft.com/en-us/library/windows/apps/jj863509%28v=vs.105%29.aspx
In my case, I had hardware-assisted virtualization enabled in the BIOS, but not data execution prevention (DEP). I also had Hyper-V enabled via Windows Features. After enabling DEP in the BIOS, I was able to run the Windows phone emulator.

A: Finally after struggling all day, I solved it ^^
I post the solution here so that somebody don't have to waste time just like me to solve such a silly error!

*

*Just simple disable Hyper-V option in Turn Windows features on or off
(you could open this by hit the combination Windows + S, this will open the search box, then type "Turn Windows features on or off"

*restart your PC

*enable the Hyper-V option by using the same way as step 1.

Enjoy coding :D

A: CMD with admin rights:
bcdedit /set hypervisorlaunchtype auto

and reboot.


text:
Q: How to include class dependency jar in JRuby? I'm having trouble figuring out how to include/import/require mydependency.jar which MyJavaClass (within a MyJavaClass.class file) depends on. MyJavaClass contains many import statements importing classes from mydependency.jar. Everything is in the same directory.
When I run java -cp '.:mydependency.jar' MyJavaClass on the command line, I get no error and by putting some calls in main I can get it to run how I want, but when I run ruby my_ruby_file.rb with JRuby on the command line I get NoClassDefFoundError for the first class imported (which is being imported from mydependency.jar) within the MyJavaClass.class file. The stack trace for the error points to the java_import line in my_ruby_file.rb so it seems like it's not properly finding the classes imported from mydependency.jar that are included in my MyJavaClass.class file, even though it runs fine in the normal Java environment.
# contents of my_ruby_file.rb

require 'java'
require './mydependency.jar'

java_import 'MyJavaClass'

MyJavaClass.new.myJavaInstanceMethod('argument')

A: My $CLASSPATH environment variable was not set, which it needs to be in order for JRuby to be able to find my jar. After I ran export CLASSPATH=".:mydependency.jar" on the command line and removed the line require './mydependency.jar', it worked.


text:
Q: Why does PrintStream extend FilterOutputStream and not OutputStream? System.out and System.err are both PrintStreams; and PrintStream extends FilterOutputStream.
From the FilterOutputStream's javadoc:

This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality.
The class FilterOutputStream itself simply overrides all methods of OutputStream with versions that pass all requests to the underlying output stream. Subclasses of FilterOutputStream may further override some of these methods as well as provide additional methods and fields.

(emphasis mine)
FilterOutputStream itself extends OutputStream.
I am at a loss here. Is there any reason why PrintStream needs to extend FilterOutputStream instead of OutputStream?
Sample code appreciated...

A: FilterOutputStream applies the composition pattern where it delegates all the calls to its instance variable out:
/* The underlying output stream to be filtered. */
protected OutputStream out;

FilterOutputStream also has default implementations for the abstract class OutputStream:
public void write(int b) throws IOException {
    out.write(b);
}

public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
}

public void write(byte b[], int off, int len) throws IOException {
    if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
        throw new IndexOutOfBoundsException();

    for (int i = 0 ; i < len ; i++) {
        write(b[off + i]);
    }
}

public void flush() throws IOException {
    out.flush();
}

public void close() throws IOException {
    try {
      flush();
    } catch (IOException ignored) {
    }
    out.close();
}

Now, any class including PrintStream can extend FilterOutputStream and override the appropriate methods. Note that they still need to delegate their calls to out. For example PrintStream#flush():
public void flush() {
    synchronized (this) {
        try {
            ensureOpen();
            out.flush();
        }
        catch (IOException x) {
            trouble = true;
        }
    }
}

A: The PrintStream must implement various filters, handling character encodings, and most ultimately, printing non-character data as characters.
The general contract of FilterOutputStream fits this best, so that is the class used.

A: Any higher level Stream that needs to filter the input or output of a nested lower-level Stream, needs to first extend FilteredOutputStream, and the same is true for InputStreams. So it makes sense that all of the higher-level OutputStreams extend the FilteredOutputStream class, in other words, all Streams that allow for and in fact require the nesting of other Streams to function, must extend this class.
I don't know what the class does internally, but I imagine it somehow massages the data to allow the higher level streams to be able to make sense out of them. To know more, I'm guessing that you're going to have to delve into the source code.


text:
Q: WebSockets performance I'm thinking about implementing a HTML5 mmog where there is a fast running object involved. Players constantly alter the direction of that object by shooting at it. I thought about WebSockets etc. (socket.io) and canvas.
I reckon that the calculation of the direction change has to be done client- AND serverside and then synchronized - with the server being master to avoid cheating.
My worries are that regardless of how fast the server is, latency will cause lag and therefore kill synchronization.
Is there a good way of solving this puzzle? How to achieve real time syncronization of this amount of data where all info is critical to not miss a direction change. All players need to get the new direction of the moving object without delay to not corrupt the gameplay.
I assume this problem has been solved in existing mmogs.
Any ideas?

A: The best thing you can do in these kinds of situations is to try and predict the movement client-side (dead reckoning), and then correct the position/velocity with data from the server if/when necessary.
For example, say your fast running object is moving left to right across the screen at a speed of 5, and a player shoots at it and it changes direction so it is now moving upwards on the screen at that speed of 5 (90 degree turn).
The client-side app will probably be updating far more frequently than it is getting data from the server (e.g. 60 updates per second client-side, and 10 packets per second received from the server). Let's say that, in real time, the object changed direction with 5 frames left to go before the server update will come. On the client-side, the object will continue to move along its current trajectory until it receives the update from the server that it changed direction (i.e. it doesn't just stop when it's not receiving data from the server), at which point, the client will correct the position and velocity of the object.
How you do the correction will determine how jumpy the animation will look. You could just zap it to the correct position instantly, thus causing a little jump but instantly giving the correct position, or you could change it's velocity in such a way that it moves in a smooth transition to that position, causing no jump, but having a slightly inaccurate position during the mean-time of the correction.
You'll always have some situations where these corrections will end up being pretty big (e.g. someone has a really bad connection, dropped packets, sky-high latency, etc.). That's when you get the crazy anomalies people usually refer to as lag in online games, like when an object skips large distances or moves really fast to "catch up" to where it should be. There's just no way to be 100% in sync all the time. All you can do is make really good guesses as to where things should be.
Here are some articles with more detail, good luck!
http://gmc.yoyogames.com/index.php?showtopic=415538
http://www.gamasutra.com/view/feature/3230/dead_reckoning_latency_hiding_for_.php

A: The server is the right place to synchronize all your events.  You don't want each player sending its input data to the other "n" players as it creates too many communication paths.
The server will take the player data and determine the new trajectory of the moving object and then send updates to each player.  This can be done in fixed units of virtual game time, which I will call "ticks".
From the server point of view this gives you a loop like the following:

*

*Receive inputs from players

*Update game state

*Distribute game state changes to players

You will need to deal with cases such as not receiving input from players within a certain amount of time (e.g., maybe ignore that player for that frame).
On the client side, while you are waiting for the next game tick update from the server, you can keep moving the object along its previous trajectory, rendering frames as time passes.
When an update is received from the server for the current game tick, the new game state must be applied.
If the object's new real position is very close to the position you've extrapolated, you can just set the new position and render it next frame.
If the new position is "far" from the extrapolated position, then you need to decide whether to warp the object instantly to the destination or do some sort of accelerated or linear motion to move it there over a short period of time.


text:
Q: Is it correct to say: I am with pain? Is it correct to say: I am with pain?
thank you very much for your help

A: I think the phrase you're looking for is "I am in pain".

Be in pain
If you are in pain, you feel pain in a part of your body, because you are injured or ill.

collins dictionary


text:
Q: [logic]Give sample of 3-element set M so that M is not satisfiable, but every 2-element subset of M is satisfiable. This is the Exercise 7 in 《Logic for Computer Scientist》(Uwe Schoning)
Exercise 7: Give an example of a 3-element set M so that M is not
satisfiable, but every 2-element subset of M is satisfiable. Generalize your
example to n-element sets.

I am stuck in this question for a while. I intuitively thought it was easy, while it was not for me at least :(.
I think there may be something wrong in my understanding and this answer should help me a lot .
Thanks.

A: For $3$ elements:
$$a,b,(\text{not }(a \text{ and } b))$$
For $n$ elements:
$$a_1,a_2,\ldots,a_{n-1},(\text{not }(a_1 \text{ and } a_2 \text{ and }\ldots\text{ and }a_{n-1}))$$

A: After a few hours thinking regarding the answers of quasi & Fabio, here is my answer.
I am willing to find a "pattern" or "constraint" so that any set of formulas meeting this "pattern" will apply to the question.
My induction :

*

*from the first premise " 3 element is not satisfiable", so there are the  constraints :
$(A\wedge{B}\rightarrow\neg{C}) \wedge (A\wedge{C}\rightarrow\neg{B}) \wedge (B\wedge{C}\rightarrow\neg{A}) $   .
After equivalence, it shows the same thing : $A\wedge{B}\rightarrow\neg{C}$.

*from the second premise " any 2 elements subset is satisfiable", so we have the constraints:
$A\rightarrow{B},  B\rightarrow{C},C\rightarrow{A},B\rightarrow{A},C\rightarrow{B},C\rightarrow{A}
  i.e. (C\leftrightarrow{B})\vee(A\leftrightarrow{B})\vee(A\leftrightarrow{C})$

*join the constraints from step1/step2, we finally get the constraint $A\wedge{B}\rightarrow\neg{C}$.
So for any formula set which met this constraint will apply to the question.
By testing the samples given by quasi&Fabio, it is valid solutions.


text:
Q: How can I do an inner join of two collections in mongodb // orders collection
[
  {
    "id": 1,
    "orderName": "a",
    "seqId": 100,
    "etc": [],
    "desc": [],
  },
  {
    "id": 2,
    "orderName": "b",
    "seqId": 200,
    "etc": [],
    "desc": []
  },
  {
    "id": 3,
    "orderName": "c",
    "seqId": 100,
    "etc": [],
    "desc": [],
  },
]

// goods collection
[
  {
    "id": 1,
    "title": "example1",
    "items": [
      {
        "id": 10,
        "details": [
          {
            "id": 100
          },
          {
            "id": 101,
          }
        ]
      },
      {
        "id": 20,
        "details": [
          {
            "id": 102,
          },
          {
            "id": 103,
          }
        ]
      },
    ]
  },
[
  {
    "id": 2,
    "title": "example2",
    "items": [
      {
        "id": 30,
        "details": [
          {
            "id": 200
          },
          {
            "id": 201
          }
        ]
      },
      {
        "id": 40,
        "details": [
          {
            "id": 202
          },
          {
            "id": 203
          }
        ]
      },
    ]
  },
]

When the value of the seqId field of the document whose etc field and desc field arrays of the orders collection are empty and the value of the "goods.details.id field of the goods collection are the same, I want to get the following output. How can I do that?
[
  {orderName: "a", title: "example1"},
  {orderName: "b", title: "example2"},
  {orderName: "c", title: "example1"},
]

Additionally, I would like to perform a sum operation based on the title of the goods
collection.
[
  {"example1": 2},
  {"example2": 1}
]

A: Simply perform a $lookup between orders.seqId and goods.items.details.id. Use $unwind to eliminate empty lookups(i.e. inner join behaviour). Finally, do a $group with $sum to get the count.
db.orders.aggregate([
  {
    "$match": {
      "etc": [],
      "desc": []
    }
  },
  {
    "$lookup": {
      "from": "goods",
      "localField": "seqId",
      "foreignField": "items.details.id",
      "pipeline": [
        {
          $project: {
            _id: 0,
            title: 1
          }
        }
      ],
      "as": "goodsLookup"
    }
  },
  {
    "$unwind": "$goodsLookup"
  },
  {
    $group: {
      _id: "$goodsLookup.title",
      cnt: {
        $sum: 1
      }
    }
  }
])

Mongo Playground


text:
Q: Disk allocation I installed ubuntu 15.04 and used entire space(640 GiB) for ext4 partition but now it is showing that used space = 30.91 GiB, free space = 24.96 GiB and 536.40 GiB unallocated space. I tried to extend the space of file system using Gparted but its not working. So could any one please tell me how can I extend or allocate the space.

output after command

sudo parted -l

Gparted is not showing option for resize thats the problem.

A: You can allocate the free space (with GParted) by Right-Clicking it > New. Set its new space to 536.4 GB, label it and create the new partition. Apply the action by clicking that green V under the Device tab. Then you will be able to create an extended partition.


text:
Q: Skilled vs Skilful
For example, to discover what had caused the war between them, he
  travelled extensively and questioned many people. He was a skilful
  writer, producing works that are informative and lively.

The answer key to my schoolbook suggests skilful as the only possible answer here. However, can't we use skilled as well?
(It is a CAE Part 3 task, in which you have to transform a word. In this case, SKILL)
The following links introduce us to a pretty similar meaning which I cannot make sense of, to be honest.
http://www.learnersdictionary.com/qa/the-difference-between-skilled-and-skillful
I'd be more than grateful if you let me know about anything obvious that I might be missing here.

A:
He was a _______ writer, producing works that are informative and lively.

The OP's task was to transform the word SKILL in order to fill in the blank space.
But if the OP had to find a word, they could have opted for any of the following: gifted, talented, accomplished, or even polished.
Note that none of the preceding adjectives have the suffix -ful. In fact, giftful, talentful, accomplishedful, and polishful are all ungrammatical today.  But in the case of skill, either one of the two suffixes -ed (skilled) and -ful (skillful) can be applied.
Oxford Dictionaries says that skilled means

1. Having or showing the knowledge, ability, or training to perform a certain activity or task well.

1.1 Based on or proceeding from the ability to do something well.
1.2 (of work) requiring special abilities or training.

Whereas for skilful, there is only one definition

Having or showing skill.

*

*'Not only is he a brilliantly skillful footballer, he is also captain and leader of this Czech side.'

*'For thousands of years, this has been admired as the most skillful accomplishment in war.'

The writer in the citation can be called skilled because they have the knowledge, and the ability to produce informative and entertaining works. They can also be called skilful because they have a natural talent or have acquired the ability (i.e. the skill) to write well.
In conclusion, both forms are more than acceptable. The answer "skilful", supplied by the OP's book, was unnecessarily restricted.
Google Ngram showing the  British Corpus agrees that either adjective is suitable for writer, but skilled writer has a narrow advantage.

Google Ngram with the American English spelling skillful, suggests that  skilled writer is also the preferred form since the mid-1980s.

A: I disagree with the linked explanation. I think that they are close enough that no one would notice if you used one instead of the other, but if you wanted to be really picky:
Skilled applies to a person, as in "he was a highly skilled professional."
Skillful applies to an action or the result of an action, as in "his skillful execution saved the day."
As requested, we can observe the relative frequencies of these two examples against their opposite with the help of Google n-grams:
skilled professional vs skillful professional
skillful execution vs skilled execution
This difference probably stems from the fact that only skillful has an adverbial form: we can say "she skillfully carried out the task", but not that she carried it out "skilledly".

A: Others have discussed definitions and statistics regarding the words skilled and skillful (also spelt skilful), so I'll take those as read.
As you noticed, M-W tackles your question with the following conclusion:

In sum, skilled means having lots of training/experience and it is the best word to use when talking about workers and laborers. Skillful means expert at a particular job, but not necessarily because of training or experience.
  - The difference between skilled and skillful, Learner's Dictionary

You say:

I'd be more than grateful if you let me know about anything obvious that I might be missing here.

The nuanced difference is that skilled relates more to training and skillful to talent. Both work, but the context "producing works that are informative and lively" suggests an element of creativity that favours the answer 'skillful'.


text:
Q: Master Interface for All Class I want to create an Interface that has default method (Save, Update, Delete, Select, SelectByID) for all classes that will inherit this Interface. How can I make a method in an Interface that can accept any class name with object?
interface IMasterActions
{
    int Save(Class_Name obj);

    int Update(Class_Name obj);
}

public class Student
{
    public int RollNo{get;set;}
    public String Name{get;set;}
}

public class Book
{
    public String Author{get; set;}
    public decimal Price{get; set;}
}

public class StudentManager:ImasterActions
{
     public int Save(Student std)
     {
         ........
     }
}

public class BookManager:IMasterActions
{
    public int Save(Book book)
    {
        .............
    }
}

A: You should use generics to allow for the dynamic nature of the interface implementations.  Your interface and implementations would be defined as follows:
public interface IMasterActions<T> where T : class
{
    int Save(T obj);

    int Update(T obj);
}

public class StudentManager:IMasterActions<Student>
{
    public int Save(Student std)
    {
       ... .....
    }
}

A: You can use generics to achieve this.
interface IMasterActions<T>
{
 int Save(T obj);

 int Update(T obj);
}

public class StudentManager:ImasterActions<Student>
{
  public int Save(Student std)
  {
   ........
  }
}

More details here: http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx


text:
Q: How to fetch the conversion factor for any unit conversion When you convert between 2 entities, you usually do it via the UnitConverter. How should I find out what the conversion factor is? For example:
public static final Unit<Length> KILOMETRE = METER.times(1000);
public static final Unit<Length> CENTIMETRE = METRE.divide(100);

I would like to get the conversion factor programmatically from the converter interfaces (i.e. 1000 b/w KILOMETRE and METER or 1/100 in case of CENTIMETER to METRE)
I am not sure how to fetch this information from the UnitConverter interface.
EDIT1
protected double getConvFactor(Unit<Length> from, Unit<Length> to) {
    double factor = -1;

    UnitConverter unitConverter = from.getConverterTo(to);

    if (unitConverter instanceof MultiplyConverter) {
        MultiplyConverter multiplyConverter = (MultiplyConverter) unitConverter;
        factor = multiplyConverter.getFactor();
    } else if (unitConverter instanceof AddConverter) {
        AddConverter addConverter = (AddConverter) unitConverter;
        factor = addConverter.getOffset();
    } else if (unitConverter instanceof RationalConverter) {
        RationalConverter rationalConverter = (RationalConverter) unitConverter;
        double divisor = rationalConverter.getDivisor().doubleValue();
        double dividend = rationalConverter.getDividend().doubleValue();
        factor = divisor;
    }
}

A: Edit after further code posted by OP:
UnitConverter is an abstract class, so one must derive from it to create a converter for the specific units you have in mind.
If you're already using a class derived from UnitConverter, you'll have to check it's interface to see if the designer of that class was good enough to expose a method that returns the multiplication factor.
Looking at some of the jscience classes derived from UnitConverter:

*

*MultiplyConverter has a getFactor() method which returns the factor being used in the conversion.

*AddConverter has a getOffset() method which returns the offset the converter adds in the conversion.

*RationalConverter, if I understand it correctly, converts by multiplying the value being converted by the quotient of two numbers - the dividend and the divisor. The class has methods, getDividend() and getDivisor() for returning the dividend and the divisor, so you could perform the division yourself to approximate the quotient.

So I think your code (below) is in error. The factor is NOT the divisor, as you have here - it's the quotient.
RationalConverter rationalConverter = (RationalConverter) unitConverter;
double divisor = rationalConverter.getDivisor().doubleValue();
double dividend = rationalConverter.getDividend().doubleValue();
factor = divisor;


text:
Q: Is there any way to paste an image at the cursor in a Word 2016 document? Is there a way to simply paste an image in a Word document at the cursor?
Regardless of the Advance Word Options I have set (In Line with Text or Top and Bottom); images are pasted at some random location.  Sometimes images wind up at some random location on another page.
I used to be able to place images in table cells, but this does not seem to work any more.


text:
Q: Bayesian Stochastic Optimal Control, MCMC I have a Stochastic Optimal Control problem that I wish to solve, using some type of Bayesian Simulation based framework. My problem has the following general structure:
s_t+1 = r*s_t(1 - s_t) - x_t+1 + epsilon_t+1
x_t+1 ~ Beta(u_t+1, w_t+1)
u_t+1 = f_1(u_t,w_t, s_t, x_t)
w_t+1 = f_2(u_t,w_t, s_t, x_t)
epsilon_t ~ Normal(0,sigma)
objective function: max_{x_t} E(Sigma_{t=0}^{T} V(s_t,x_t,c) * rho^t)

My goal is to explore different functional forms of f_1, f_2, and V to determine how this model differs w.r.t a non-stochastic model and another simpler stochastic model.
State variables are s_t, control variables are x_t with u_t and w_t representing some belief of the current state. The objective function is the discounted maximum from gains (function V) over the time period t=0 to t=T.
I was thinking of using Python, specifically PyMC to solve this, though I am not sure how to proceed, specifically how to optimize the control variables. I found a book, published 1967, Optimization of Stochastic Systems by Masanao Aoki, that references some bayesian techniques that may be useful, is there a current Python implementation that may help? Or is there a much better way to simulate a optimal path, using Python?

A: The first guess coming to my mind is to try neural network packages like chainer or theano which can track derivative of your cost function with respect to control function parameters; they also have a bunch of optimization plug-in routines. You can use numpy.random to generate samples (particles), compose your control functions from the libraries components, and run them through explicit Euler scheme for first try. This will give you cost function on your particles and its derivative with respect to parameters, which can be fed to the optimizers.
The issue that can arise here is that solver's iterations will create a host of derivative-tracking objects.
update:  Please see this example on Github
Also there is a number of hits on Github with keywords particle filter python:
https://github.com/strohel/PyBayes
https://github.com/jerkern/pyParticleEst
Also there is a manuscript around which mentions that the author implemented filters in Python, so you might want to contact them.


text:
Q: Merging JSON elements with the same keys I've been struggling with JSON transformation using Python. I have JSON in the below format:
{
    "Children": [{ "child": "Child 0"}],
    "Parent": "Parent 10"
},
{
    "Children": [{ "child": "Child 1"}],
    "Parent": "Parent 10"
},
{
    "Children": [{ "child": "Child 2"}],
    "Parent": "Parent 11"
},

But instead of having duplicated parents, I would like to merge children together to get that:
{
    "Children": [{ "child": "Child 0"}, { "child": "Child 1"}],
    "Parent": "Parent 10"
},
{
    "Children": [{ "child": "Child 2"}],
    "Parent": "Parent 11"
},

A: Take a look at the itertools groupby function. Here's an example with your data grouped by Parent.
>>> from itertools import groupby
>>> import pprint

>>> data = [{
    "Children": [{ "child": "Child 0"}],
    "Parent": "Parent 10"
},
{
    "Children": [{ "child": "Child 1"}],
    "Parent": "Parent 10"
},
{
    "Children": [{ "child": "Child 2"}],
    "Parent": "Parent 11"
}]

>>> data_grouped = {k: list(v) for k, v in groupby(data, key=lambda x: x["Parent"])}

>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(data_grouped)

{   'Parent 10': [   {   'Children': [{'child': 'Child 0'}],
                         'Parent': 'Parent 10'},
                     {   'Children': [{'child': 'Child 1'}],
                         'Parent': 'Parent 10'}],
    'Parent 11': [{'Children': [{'child': 'Child 2'}], 'Parent': 'Parent 11'}]}

Here I've placed your example dicts inside a list and group by the Parent entry in each dict. This is all wrapped up inside a dict comprehension to give a meaningful output.

A: You can also use a collections.defaultdict() to do this, which can be serialized at the end:
from collections import defaultdict
from json import dumps

data = [
    {"Children": [{"child": "Child 0"}], "Parent": "Parent 10"},
    {"Children": [{"child": "Child 1"}], "Parent": "Parent 10"},
    {"Children": [{"child": "Child 2"}], "Parent": "Parent 11"},
]

d = defaultdict(list)
for dic in data:
    parent, children = dic["Parent"], dic["Children"]
    d[parent].extend(children)

result = []
for k, v in d.items():
    result.append({"Parent": k, "Children": v})

print(dumps(result))

Which gives a JSON array of JSON objects:
[{"Parent": "Parent 10", "Children": [{"child": "Child 0"}, {"child": "Child 1"}]}, {"Parent": "Parent 11", "Children": [{"child": "Child 2"}]}]

You can also group into the data by parent key using a nested defaultdict():
d = defaultdict(lambda : defaultdict(list))
for dic in data:
    parent, children = dic["Parent"], dic["Children"]
    d[parent]["Children"].extend(children)

print(dumps(d))

Which gives this new structure:
{"Parent 10": {"Children": [{"child": "Child 0"}, {"child": "Child 1"}]}, "Parent 11": {"Children": [{"child": "Child 2"}]}}

And will allow easy O(1) lookups for the parent.


text:
Q: Edit property based on library variant gradle android I have an android project with native part in it. I would like to build my native code with different flags, depending on buildType and productFlavor, for instance:
android {
    project.ext.buildFlags = ['-j16', 'all']
    buildTypes {
        debug { project.ext.buildFlags.add('NDK_DEBUG=1')}
    }
    productFlavors {
        pretty {project.ext.buildFlags.add('PRETTY')}
        ugly {project.ext.buildFlags.add('UGLY')}
    }

    task buildNativeCode(type: Exec) {
        commandLine 'ndk-build', project.ext.buildFlags
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn buildNative
    }
}

So, for uglyDebug I would like to build my native library with 'UGLY', and 'NDK_DEBUG' flags, prettyDebug with 'PRETTY' and 'NDK_DEBUG' flags and so on. However, they are always added, regardless of the chosen configuration. From what I gather, this is done during project evaluation and I don't know how to set it up properly. For now I ended up creating many buildNativeXXX tasks that have pretty much the same content. I would love to avoid code repetition.

A: You can use the following commands to modify any tasks afterwards:
afterEvaluate {
    productFlavors.each { productFlavorName ->
        buildTypes.each { buildTypeName ->

        project.ext.buildFlags.add('NDK_DEBUG=1')

        if (productFlavorName.equals("pretty")) {
           //enter code here
            project.ext.buildFlags.add('PRETTY')
        } else {
            project.ext.buildFlags.add('UGLY')
        }
    }
    }
}

Now you have full control of how gradle adds the buildFlags for you. :)
If you want to use the buildConfig variables, you can set them using:
applicationVariants.all { variant ->
            variant.buildConfigField "String", "COMMIT_HASH", "HASH123456789"
}


text:
Q: Suggested way to retrieve Fragment managed by Adapter I have fragments in a FragmentActivity, that has an ActionBar and Tab navigation. My problem is that I want to call a method on the Fragment. I cannot use findFragmentBy[Id|Tag], because the fragments are initiated and attached by the adapter, and it assigns a custom tag. I saw several solution based on keeping references to fragments, but I really want to avoid keeping any reference to my fragments, as they are handled by the FragmentPagerAdapter. Now I have everything in my Fragment (which is a workaround in my view), but the question still bothers me.
What is the best way to access a fragment instance from my activity, not added by my to FragmentManager, but the FragmentPagerAdapter?

A: I solved this problem by writing my own Adapter. Since they are pretty straightforward, they are easy to be implemented.


text:
Q: Java: Filter when forwarding from servlet to servlet is it possible to use a filter when forwarding a request from one servlet to another? In the web.xml of my project, I've tried this filter-mapping:
<filter-mapping>
  <filter-name>myFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>INCLUDE</dispatcher>
</filter-mapping>

Forwarding from servlet to JSP works fine. Forwarding from servlet to servlet doesn't call the filter. I wonder if I'm doing something wrong or it's just not possible.

A: Its working in case of jsp because request goes to client and then comes back to server  but in case of servlet it is not redirected to client so your filter does not comes into picture there.
If you want then use sendRedirect instead of forward .
Check below link to see difference b/w sendRedirect and forward.
When you use SendRedirect container transfers the request to client or browser so url given inside the sendRedirect method is visible as a new request to the client.
Read more: http://javarevisited.blogspot.com/2011/09/sendredirect-forward-jsp-servlet.html#ixzz4QvHxSVFF


text:
Q: React: How to change position of footer component depending on route I have a simple footer component. It is used in about and support pages. In my sass, I have set the position to relative.
I want to change this position based on the route. If it's /about then position: relative and it's /support then position: fixed.
Is it possible to achieve this?
function GeneralFooter() {
  return (

                  Help

                <NavLink to="/about" className="nav-link">
                  About
                </NavLink>

                <NavLink to="/support" className="nav-link">
                  Support
                </NavLink>

  );
}

A: I'm not sure if you are using any libraries, but without, you can use the following code.
Using the style prop:
function GeneralFooter() {
  const location = useLocation();
  const pathName = location.pathname;

  return (

      ...

Using the className prop
.footer--about {
  position: relative;
}

.footer--support {
  position: fixed;
}

function GeneralFooter() {
  const location = useLocation();
  const pathName = location.pathname;
  const extraClassName = pathName === '/about' ? 'footer--about' : pathName === '/support' ? 'footer--support' : '';

  return (
    <div
      className={`container ${extraClassName}`}
    >
      ...

With classNames dependency:
function GeneralFooter() {
  const location      = useLocation();
  const rootClassName = classNames('container', {
    'footer-about': location.pathname === '/about',
    'footer-support': location.pathname === '/support',
  });

  return (

      ...


text:
Q: How to customize the format for a field that is a duration? In my model.groovy, i have an entity with a lot of fields that are of type duration.
For a particular field, I would be able to customize the format for either enter or display the data.
Example :  instead of entering "90 minutes" that is the default format, I would be able to enter 1h30.

A: Unfortunately, as of Jspresso 4.3, this is not possible. Feel free to open a RFE on GitHub for it.


text:
Q: How to make Non Removable Footer Credit I add a HTML footer like :

Copyright 2014

        Designed by XYZ

Now, I need your help. It is that the users use my theme cannot remove footer.
It means the users cannot:

*

*Add display:none; visibility:hidden or the same actions.

*Remove it from code.
(cannot hide or remove)
How jQuery can do it? (I will encrypt jQuery code)
Thank for your help.

A: Basically you cannot do this. There's no way of protecting it completely.


text:
Q: Select query in row_to_json function For example ,
I use the following function to convert rows into json in PostgreSQL 9.2
select row_to_json(row(productid, product)) from gtab04;

and this will returns below results
row_to_json
---------------
{"f1":3029,"f2":"DIBIZIDE M TAB"}
{"f1":3026,"f2":"MELMET 1000 SR TAB"}
{"f1":2715,"f2":"GLUCORED FORTE"}
{"f1":3377,"f2":"AZINDICA 500 TAB"}

*

*unfortunately it loses the field names and replaces them with f1, f2, f3, etc.

*How can I get the actual field names or cast field name?

A: To work around this we must either create a row type and cast the row to that type or use a subquery. A subquery will typically be easier.
select row_to_json(t)
from (
   select productid, product from gtab04
) t

A: If one wants to prevent a sub-query, json_build_object() might be a solution. It does not map the column name, but let's your set the JSON keys explicitly.

Query
SELECT json_build_object('productid', productid, 'product', product) FROM gtab04;

json_build_object
------------------
{"productid":3029,"product":"DIBIZIDE M TAB"}
{"productid":3026,"product":"MELMET 1000 SR TAB"}
{"productid":2715,"product":"GLUCORED FORTE"}
{"productid":3377,"product":"AZINDICA 500 TAB"}

View on DB Fiddle


text:
Q: How does the substrate voltage change the state of the MOSFET? I understand some formulas for determining whether a NMOS transistor is activeis VGS > Vth and if its in saturation you take the drain-to-source voltage VDS => VGS - Vth
But how does the substrate voltage play a part in determining this behavior? For example the image below

If I were to change the substrate voltage from 0 to 5V. Could I turn ON/OFF the transistor and affect the region of operation?

A: No, you can't increase the substrate voltage to 5V...that would cause the substrate-to-source PN junction to become forward biased.
However, you can change the substrate-to-source voltage and thereby change the transistor's threshold voltage...this is called the "body effect". Making the substrate more negative with respect to the source will increase the transistor's threshold voltage. MOS circuits usually do not allow the substrate voltage to be higher than the source voltage, so the lowest transistor threshold voltage would occur when the source and substrate are tied together.


text:
Q: Station coverage area I have many points(stations with coordinates) and I want to find out their coverage area (further find out the average travel distance). People in these areas will go to the station in the area centre.
My basic thought is to draw some buffers which are tangent to each other (with no overlaps, each buffer only has one station). Then these buffers become the coverage area. I am not sure these areas are circle or random shapes.
I believe there could be some algorithms in Python or GIS softwares to address this. Any suggestions? Thanks.


text:
Q: Dump when using Drop down for create or edit opearation I have created/generated this very simple MVC program (1 minute ) ,the steps are
1. create MVC5 asp program and Create new model class - the test model
2.go to the controller add -> scaffold and provide the model and the context class.
the crud operation was generated and everything is working fine
what I want now is that wnen the user click on create in the gender he will have drop down list which he can choose,I write this code which I've from previous post and I got dump in the html drop down,what am I missing here?
the model
using System.Collections.Generic;
using System.Data.Entity;
using System.Web.Mvc;

namespace TestropDownCreate.Models
{
    public class TestModel
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public string SelectedGender { get; set; }

        public IEnumerable<SelectListItem> Gender
        {
            get
            {
                return new[]
            {
                new SelectListItem {Value = "M", Text = "Male"},
                new SelectListItem {Value = "F", Text = "Female"}
            };
            }
        }
    }

        public class TestModelDBContext : DbContext
        {
            public DbSet<TestModel> TestModel { get; set; }
        }

}

The generated view by scaffold ,you can see that I comment the generated code and put the
@Html.DropDownListFor which cause the dump ,how should I solve it.
@model TestropDownCreate.Models.TestModel

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

TestModel

        @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)

            @Html.LabelFor(model => model.SelectedGender, new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.SelectedGender, Model.Gender)
                @*@Html.EditorFor(model => model.SelectedGender)
                @Html.ValidationMessageFor(model => model.SelectedGender)*@

                <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

A: I would make a bold suggestion based on experience that you are getting an ArgumentNullException exception because the value of SelectedGender hasn't been set. So, what's happening is that here...
@Html.DropDownListFor(model => model.SelectedGender, Model.Gender)

asp.net is trying to pre-select the dropdownlist with some value and to do that, it looks at the value of SelectedGender and attempts to match it with any of the values provided in Gender, however, there's nothing set for SelectedGender because it is null. Now, to address this issue you can follow two approaches:

*

*initialize SelectedGender with a default value that matches one of the values specified in Gender...either M or F

*Initialize SelectedGender with dummy default value such as an empty string, then add a default value to Gender as below...
public IEnumerable<SelectListItem> Gender
{
    get
    {
        return new[]
    {
        new SelectListItem {Value = "", Text = "--Select a gender--"},
        new SelectListItem {Value = "M", Text = "Male"},
        new SelectListItem {Value = "F", Text = "Female"}
    };
    }
}

A suggestion as Jhoon pointed out in a comment you don't really need to keep gender values in the database,but I understand this is out of the scope of your question


text:
Q: Finding pairs of racers where racer `a` have beaten racer `b` in all races I've got a challenge and I would like to ask you to guide me a little. I have number n (number of racers)and two lines containing n integers(the integer actually represents the racer) each. Those lines represent order in which racers have ended the race.
I have to find all doubles/pairs where a racer a have beaten racer b in both races. Can You guide me a bit?
Example
Input :
3
1 2 3
2 3 1
Output :1 (only 2 and 3 have met the condition)

A: First of all, finding the length of a number is very simple. In c++, it is just ceil(log10(number)) when using math.h.  On to your code, you can use a very simple function to turn the input of numbers into a vector.  For example:
//input number of racers (int racerNum)
//input number of races (int raceNum)
vector<vector<int>> result(raceNum, vector<int>(racerNum));
for (int race=0; race<raceNum; race++){
    //input race results as one string of integers without spaces (int rResult)
    int curVal = rResult;
    for (int place = racerNum-1, input=0; place >= 0; place--, input++){
        curVal = floor(rResult/pow(10,place));
        result.at(race).at(place) = curVal;
        rResult -= curVal*pow(10, place);
    }
}

Or, you may want to use the example you had before, where you input the results with spaces.  This will allow you to have more than 9 racers, and it is probably simpler.  It utilizes the fact that cin will separate a string with spaces into smaller strings. For example:
//get number of racers (int racerNum)
//get number of races (int raceNum)
vector<vector<int>> raceResults;
for (int race=0; race<raceNum; race++){
    vector<int> singleResult;
    cout << "Results of race " << race+1 << ":";
    //get input with spaces
    for (int counter=0; counter<racerNum; counter++){
        int result;
        cin >> result;
        singleResult.push_back(result);
    }
    raceResult.push_back(singleResult);
}

I would recommend the second example, but the first will also work just as well.  The first is just the purely mathematical approach, and the second utilizes the way cin gets input.  Either way, you will be left with a vector or races, each of which is a vector of the results, in the proper order.  I think that this should be enough to get you started, but if you need any help with the rest of the code or with this code, I can help.


text:
Q: How can I send a signal to a running jenkins job Our integration test runs on jenkins(with docker plugin) and selenium. When a test fails, we would like the containers still be running so we can inspect the situation. In order to prevent the containers from stopping, we have a script running an infinite loop at the end of the job when things go wrong.
When the test passes, the loop does not run which works fine.  When the test fails, the containers are still running which is good, but the job will run forever.  We have to the abort the job but the test will not be marked as failed.
So I'm wondering if one can send a signal to a failing test to break the loop and end the test normally? Sorry for the wordiness. Thank you for reading my question.

A: You can use docker kill to send signal to running container.
# docker kill --help

Usage:  docker kill [OPTIONS] CONTAINER [CONTAINER...]

Kill a running container

  --help=false         Print usage
  -s, --signal=KILL    Signal to send to the container

For example,there is a running container named jenkins.
The command is  docker kill --signal=SIGTERM jenkins
Note:Only one process which pid=1 in the container can receive this signal.


text:
Q: ionic build --prod error: The pipe 'safe2' could not be found Everything works perfectly fine when I do ionic serve.
I have a viewReport page, which opens a modal, named viewModal page.
I created a pipe, when I called that pipe in viewModal.module.ts, it was giving error. Someone from Stack Overflow guided me to add it in the viewReport.module.ts page. I did it and it worked.
But now when I am making a production build using ionic build --prod, it is giving error:
ERROR in The pipe 'safe2' could not be found ("
    <ion-text>
      {{daily_report_desc }}
      ]daily_report_desc | safe2: 'html'">{{daily_report_desc}}
      </ion-text>
    <ion-text>
")

[ERROR] An error occurred while running subprocess ng.

...

Code of viewReport.module.ts
import { Safe2Pipe } from './../pipes/safepipe2/safe2.pipe';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    ViewdailyreportPageRoutingModule
  ],
  declarations: [ViewdailyreportPage,ShortenPipe,ViewdreportmodalPage,SafePipe,Safe2Pipe],
  entryComponents: [ViewdreportmodalPage],
  exports:[Safe2Pipe]
})
export class ViewdailyreportPageModule {}
...

Code of viewModal.page.html
<ion-text>
  {{daily_report_desc }}
  {{daily_report_desc}}
</ion-text>

Everything working fine with ionic serve but gives error with ionic build --prod.
Edit 1
Added safe2pipe in app.module.ts, see below image , now when I open viewReport page (which opens viewModal page), it gives error -
"): ng:///ViewReportPageModule/ViewModalPage.html@18:25
The pipe 'safe2' could not be found ("
    <ion-text>
      {{daily_report_desc }}
      ]daily_report_desc | safe2: 'html'">{{daily_report_desc}}
      </ion-text>

Edit 2
Code of safe2pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe2'
})
export class Safe2Pipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

 public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
            case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
            case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
            case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
            case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
            case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
            default: throw new Error(`Invalid safe type specified: ${type}`);
        }
  }
}

A: Here is the stackblitz:
https://stackblitz.com/edit/ionic-c7zfbm
The steps are:

*

*Create Modal (with module)

*Import pipe on Modal Module

*Import modal module on app.module

*Put the modal page on entryComponents of app.module.

*Call the pipe on the modal html

Please note that the stackblitz for ionic is outdated and to work I made some workarounds. To see the content, inspect and look for the html code.


text:
Q: Show duration (in minutes) to hours I want to display the duration of a movie. Right now the movie.duration is shown in minutes (integer)
%b Duration: #{ @movie.duration } # 134 mins

Does rails have a time helper to show this is in a more human-readable way? Something like this:
Duration: 2h 23min

A: distance_of_time_in_words might help you.
You can use it like this:
distance_of_time_in_words(0, 143.minutes)
# => "about 2 hours"

To use an integer / float you'd need to convert to seconds manually:
distance_of_time_in_words(0, 143 * 60)

You could also calculate it like this:
"#{@movie.duration/60}h #{@movie.duration % 60}min"

The division will give you the hours, while the modulo will give you the minutes.

Finally, for the format specified in your question, there's a Gist you can use for the code here.

A: Try Following
def formatted_duration(total_minute)
  hours = total_minute / 60
  minutes = (total_minute) % 60
  "#{ hours }h #{ minutes }min"
end