Programs & Examples On #Protect from forgery

How to change the interval time on bootstrap carousel?

        You need to set interval in  main div as data-interval tag .
        so it is working fine and you can give different time to different slides.

       <!--main div -->
      <div data-ride="carousel" class="carousel slide" data-interval="100" id="carousel-example-generic">
  <!-- Indicators -->
  <ol class="carousel-indicators">
                                <li data-target="#carousel-example-generic" data-slide-to="0" class=""></li>
                             i>
                                            </ol>

  <!-- Wrapper for slides -->
  <div role="listbox" class="carousel-inner">
       <div class="item">
          <a class="carousel-image" href="#">
           <img alt="image" src="image.jpg">
          </a>
        </div>
    </div>
 </div>

How exactly to use Notification.Builder

I was having a problem building notifications (only developing for Android 4.0+). This link showed me exactly what I was doing wrong and says the following:

Required notification contents

A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()

Basically I was missing one of these. Just as a basis for troubleshooting with this, make sure you have all of these at the very least. Hopefully this will save someone else a headache.

What is the difference between AF_INET and PF_INET in socket programming?

AF_INET = Address Format, Internet = IP Addresses

PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP

AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part sticking with AF_INET for socket programming over a network is the safest option.

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.

PF_INET refers to anything in the protocol, usually sockets/ports.

How to enable mod_rewrite for Apache 2.2

There are many ways how you can fix this issue, if you know the root of the issue.

Problem 1

Firstly, it may be a problem with your apache not having the mod_rewrite.c module installed or enabled.

For this reason, you would have to enable it as follows

  1. Open up your console and type into it, this:

    sudo a2enmod rewrite

  2. Restart your apache server.

    service apache2 restart

Problem 2

  1. You may also, in addition to the above, if it does not work, have to change the override rule from the apache conf file (either apache2.conf, http.conf , or 000-default file).

  2. Locate "Directory /var/www/"

  3. Change the "Override None" to "Override All"

Problem 3

If you get an error stating rewrite module is not found, then probably your userdir module is not enabled. For this reason you need to enable it.

  1. Type this into the console:

    sudo a2enmod userdir

  2. Then try enabling the rewrite module if still not enabled (as mentioned above).

To read further on this, you can visit this site: http://seventhsoulmountain.blogspot.com/2014/02/wordpress-permalink-ubuntu-problem-solutions.html

CSS white space at bottom of page despite having both min-height and height tag

The problem is how 100% height is being calculated. Two ways to deal with this.

Add 20px to the body padding-bottom

body {
    padding-bottom: 20px;
}

or add a transparent border to body

body {
    border: 1px solid transparent;
}

Both worked for me in firebug

In defense of this answer

Below are some comments regarding the correctness of my answer to this question. These kinds of discussions are exactly why stackoverflow is so great. Many different people have different opinions on how best to solve the problem. I've learned some incredible coding style that I would not have thought of myself. And I've been told that readers have learned something from my style from time to time. Social coding has really encouraged me to be a better programmer.

Social coding can, at times, be disturbing. I hate it when I spend 30 minutes flushing out an answer with a jsfiddle and detailed explanation only to submit and find 10 other answers all saying the same thing in less detail. And the author accepts someone else's answer. How frustrating! I think that this has happend to my fellow contributors–in particular thirtydot.

Thirtydot's answer is completely legit. The p around the script is the culprit in this problem. Remove it and the space goes away. It also is a good answer to this question.

But why? Shouldn't the p tag's height, padding and margin be calculated into the height of the body?

And it is! If you remove the padding-bottom style that I've suggested and then set the body's background to black, you will see that the body's height includes this extra p space accurately (you see the strip at the bottom turn to black). But the gradient fails to include it when finding where to start. This is the real problem.

The two solutions that I've offered are ways to tell the browser to calculate the gradient properly. In fact, the padding-bottom could just be 1px. The value isn't important, but the setting is. It makes the browser take a look at where the body ends. Setting the border will have the same effect.

In my opinion, a padding setting of 20px looks the best for this page and that is why I answered it this way. It is addressing the problem of where the gradient starts.

Now, if I were building this page. I would have avoided wrapping the script in a p tag. But I must assume that author of the page either can't change it or has a good reason for putting it in there. I don't know what that script does. Will it write something that needs a p tag? Again, I would avoid this practice and it is fine to question its presence, but also I accept that there are cases where it must be there.

My hope in writing this "defense" is that the people who marked down this answer might consider that decision. My answer is thought out, purposeful, and relevant. The author thought so. However, in this social environment, I respect that you disagree and have a right to degrade my answer. I just hope that your choice is motivated by disagreement with my answer and not that author chose mine over yours.

How to import a .cer certificate into a java keystore?

  • If you want to authenticate you need the private key - there is no other option.
  • A certificate is a public key with extra properties (like company name, country,...) that is signed by some Certificate authority that guarantees that the attached properties are true.
  • .CER files are certificates and don't have the private key. The private key is provided with a .PFX keystore file normally. If you really authenticate is because you already had imported the private key.
  • You normally can import .CER certificates without any problems with

    keytool -importcert -file certificate.cer -keystore keystore.jks -alias "Alias" 
    

How can I calculate the difference between two dates?

Checkout this out. It takes care of daylight saving , leap year as it used iOS calendar to calculate.You can change the string and conditions to includes minutes with hours and days.

+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate
{
    NSDateComponents *components;
    NSInteger days;
    NSInteger hour;
    NSInteger minutes;
    NSString *durationString;

    components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate: startDate toDate: endDate options: 0];

    days = [components day];
    hour = [components hour];
    minutes = [components minute];

    if(days>0)
    {
        if(days>1)
            durationString=[NSString stringWithFormat:@"%d days",days];
        else
            durationString=[NSString stringWithFormat:@"%d day",days];
        return durationString;
    }
    if(hour>0)
    {        
        if(hour>1)
            durationString=[NSString stringWithFormat:@"%d hours",hour];
        else
            durationString=[NSString stringWithFormat:@"%d hour",hour];
        return durationString;
    }
    if(minutes>0)
    {
        if(minutes>1)
            durationString = [NSString stringWithFormat:@"%d minutes",minutes];
        else
            durationString = [NSString stringWithFormat:@"%d minute",minutes];

        return durationString;
    }
    return @""; 
}

Cannot find module cv2 when using OpenCV

Try this out:

sudo ldconfig

sudo nano /etc/ld.so.conf.d/opencv.conf

and add this following line in the opencv.conf not in the command window

/usr/local/lib

Then:

sudo ldconfig

sudo nano /etc/bash.bashrc

and add this two lines in the bash.bashrc not in the command window

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig       
export PKG_CONFIG_PATH

at last reboot your Pi sudo reboot now

and try import cv2

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

Change color of bootstrap navbar on hover link?

_x000D_
_x000D_
.navbar-default .navbar-nav > li > a{_x000D_
  color: #e9b846;_x000D_
}_x000D_
.navbar-default .navbar-nav > li > a:hover{_x000D_
  background-color: #e9b846;_x000D_
  color: #FFFFFF;_x000D_
}
_x000D_
_x000D_
_x000D_

Find the number of columns in a table

Here is how you can get a number of table columns using Python 3, sqlite3 and pragma statement:

con = sqlite3.connect(":memory:")    
con.execute("CREATE TABLE tablename (d1 VARCHAR, d2 VARCHAR)")
cur = con.cursor()
cur.execute("PRAGMA table_info(tablename)")
print(len(cur.fetchall()))

Source

How to vertically center a "div" element for all browsers using CSS?

This worked in my case (only tested in modern browsers):

.textthatneedstobecentered {
  margin: auto;
  top: 0; bottom: 0;
}

PHP/MySQL: How to create a comment section in your website

I'm working on this right now as well. You should also add a datetime of the comment. You'll need this later when you want to sort by most recent.

Here are some of the db fields i'm using.

id (auto incremented)
name
email
text
datetime
approved

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I also had the same problem, as a quick workaround, I used blend to determine how much padding was being added. In my case it was 12, so I used a negative margin to get rid of it. Now everything can now be centered properly

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Check if xdebug is working

Run

php -m -c

in your terminal, and then look for [Zend Modules]. It should be somewhere there if it is loaded!

NB

If you're using Ubuntu, it may not show up here because you need to add the xdebug settings from /etc/php5/apache2/php.ini into /etc/php5/cli/php.ini. Mine are

[xdebug]
zend_extension = /usr/lib/php5/20121212/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000

How to put a symbol above another in LaTeX?

${a \atop \#}$

or

${a \above 0pt \#}$

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

We got an error because we have missing vendor folder in our project, The vendor directory contains our Composer dependencies.

Need /vendor folder because all packages are there and including all the classes Laravel uses, A problem can be solved after following just two steps:

composer update --no-scripts 
composer update
  • --no-scripts: Skips execution of scripts defined in composer.json
  • composer update: This will check for newer versions of the libraries you required in your project. If a newer version is found and it's compatible with the version constraint defined in the composer.json file, it will replace the previous version installed. The composer.lock file will be updated to reflect these changes.

These two commands, we will Recreate the vendor folder in our project and after that our project will be working smoothly.

How to customise file type to syntax associations in Sublime Text?

In Sublime Text (confirmed in both v2.x and v3.x) there is a menu command:

View -> Syntax -> Open all with current extension as ...

Defining TypeScript callback type

I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.

the syntax is the following:

public myCallback: (name: type) => returntype;

In my example, it would be

class CallbackTest
{
    public myCallback: () => void;

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

Gradle failed to resolve library in Android Studio

To be able to use a lib project you need to include it in your application's settings.gradle add:

include '..:ExpandableButtonMenu:library'

and then in your build.gradle add:

compile project(':..:ExpandableButtonMenu:library') 

place ExpandableButtonMenu project along side your own (same folder)

see this How to build an android library with Android Studio and gradle? for more details.

postgresql duplicate key violates unique constraint

This article explains that your sequence might be out of sync and that you have to manually bring it back in sync.

An excerpt from the article in case the URL changes:

If you get this message when trying to insert data into a PostgreSQL database:

ERROR:  duplicate key violates unique constraint

That likely means that the primary key sequence in the table you're working with has somehow become out of sync, likely because of a mass import process (or something along those lines). Call it a "bug by design", but it seems that you have to manually reset the a primary key index after restoring from a dump file. At any rate, to see if your values are out of sync, run these two commands:

SELECT MAX(the_primary_key) FROM the_table;   
SELECT nextval('the_primary_key_sequence');

If the first value is higher than the second value, your sequence is out of sync. Back up your PG database (just in case), then run thisL

SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1);

That will set the sequence to the next available value that's higher than any existing primary key in the sequence.

Create a custom View by inflating a layout?

Use the LayoutInflater as I shown below.

    public View myView() {
        View v; // Creating an instance for View Object
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.myview, null);

        TextView text1 = v.findViewById(R.id.dolphinTitle);
        Button btn1 = v.findViewById(R.id.dolphinMinusButton);
        TextView text2 = v.findViewById(R.id.dolphinValue);
        Button btn2 = v.findViewById(R.id.dolphinPlusButton);

        return v;
    }

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

Boolean.parseBoolean("1") = false...?

Java is strongly typed. 0 and 1 are numbers, which is a different type than a boolean. A number will never be equal to a boolean.

How can I use "e" (Euler's number) and power operation in python 2.7

Python's power operator is ** and Euler's number is math.e, so:

 from math import e
 x.append(1-e**(-value1**2/2*value2**2))

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

PostgreSQL Crosstab Query

Solution with JSON aggregation:

CREATE TEMP TABLE t (
  section   text
, status    text
, ct        integer  -- don't use "count" as column name.
);

INSERT INTO t VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                   , ('C', 'Inactive', 7); 


SELECT section,
       (obj ->> 'Active')::int AS active,
       (obj ->> 'Inactive')::int AS inactive
FROM (SELECT section, json_object_agg(status,ct) AS obj
      FROM t
      GROUP BY section
     )X

C++ error 'Undefined reference to Class::Function()'

What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.

Also, in your card.cpp, the function should be Card::Card() instead of void Card. The Card:: is scoping; it means that your Card() function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,

void Card(Card::Rank rank, Card::Suit suit)

should be

Card::Card(Card::Rank rank, Card::Suit suit)

Also, in deck.cpp, you are saying #include "Deck.h" even though you referred to it as deck.h. The includes are case sensitive.

jQuery validation: change default error message

This worked for me:

// Change default JQuery validation Messages.
$("#addnewcadidateform").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            email: "required email",
        },
        messages: {
            firstname: "Enter your First Name",
            lastname: "Enter your Last Name",
            email: {
                required: "Enter your Email",
                email: "Please enter a valid email address.",
            }
        }
    })

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I have 2 accounts on my windows machine and I was experiencing this problem with one of them. I did not want to use the sa account, I wanted to use Windows login. It was not immediately obvious to me that I needed to simply sign into the other account that I used to install SQL Server, and add the permissions for the new account from there

(SSMS > Security > Logins > Add a login there)

Easy way to get the full domain name you need to add there open cmd echo each one.

echo %userdomain%\%username%

Add a login for that user and give it all the permissons for master db and other databases you want. When I say "all permissions" make sure NOT to check of any of the "deny" permissions since that will do the opposite.

PostgreSQL how to see which queries have run

While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:

tail -f /var/log/postgresql/*

Ubuntu 18.04, django 2+, python3+

XPath test if node value is number

I'm not trying to provide a yet another alternative solution, but a "meta view" to this problem.

Answers already provided by Oded and Dimitre Novatchev are correct but what people really might mean with phrase "value is a number" is, how would I say it, open to interpretation.

In a way it all comes to this bizarre sounding question: "how do you want to express your numeric values?"

XPath function number() processes numbers that have

  • possible leading or trailing whitespace
  • preceding sign character only on negative values
  • dot as an decimal separator (optional for integers)
  • all other characters from range [0-9]

Note that this doesn't include expressions for numerical values that

  • are expressed in exponential form (e.g. 12.3E45)
  • may contain sign character for positive values
  • have a distinction between positive and negative zero
  • include value for positive or negative infinity

These are not just made up criteria. An element with content that is according to schema a valid xs:float value might contain any of the above mentioned characteristics. Yet number() would return value NaN.

So answer to your question "How i can check with XPath if a node value is number?" is either "Use already mentioned solutions using number()" or "with a single XPath 1.0 expression, you can't". Think about the possible number formats you might encounter, and if needed, write some kind of logic for validation/number parsing. Within XSLT processing, this can be done with few suitable extra templates, for example.

PS. If you only care about non-zero numbers, the shortest test is

<xsl:if test="number(myNode)">
    <!-- myNode is a non-zero number -->
</xsl:if>

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

How do you 'redo' changes after 'undo' with Emacs?

To undo: C-_

To redo after a undo: C-g C-_

Type multiple times on C-_ to redo what have been undone by C-_ To redo an emacs command multiple times, execute your command then type C-xz and then type many times on z key to repeat the command (interesting when you want to execute multiple times a macro)

Awaiting multiple Tasks with different results

If you're using C# 7, you can use a handy wrapper method like this...

public static class TaskEx
{
    public static async Task<(T1, T2)> WhenAll<T1, T2>(Task<T1> task1, Task<T2> task2)
    {
        return (await task1, await task2);
    }
}

...to enable convenient syntax like this when you want to wait on multiple tasks with different return types. You'd have to make multiple overloads for different numbers of tasks to await, of course.

var (someInt, someString) = await TaskEx.WhenAll(GetIntAsync(), GetStringAsync());

However, see Marc Gravell's answer for some optimizations around ValueTask and already-completed tasks if you intend to turn this example into something real.

Checking Bash exit status of several commands efficiently

I've developed an almost flawless try & catch implementation in bash, that allows you to write code like:

try 
    echo 'Hello'
    false
    echo 'This will not be displayed'

catch 
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"

You can even nest the try-catch blocks inside themselves!

try {
    echo 'Hello'

    try {
        echo 'Nested Hello'
        false
        echo 'This will not execute'
    } catch {
        echo "Nested Caught (@ $__EXCEPTION_LINE__)"
    }

    false
    echo 'This will not execute too'

} catch {
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}

The code is a part of my bash boilerplate/framework. It further extends the idea of try & catch with things like error handling with backtrace and exceptions (plus some other nice features).

Here's the code that's responsible just for try & catch:

set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0

# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
           __oo__insideTryCatch+=1; ( set -e;
           trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "

Exception.Capture() {
    local script="${BASH_SOURCE[1]#./}"

    if [[ ! -f /tmp/stored_exception_source ]]; then
        echo "$script" > /tmp/stored_exception_source
    fi
    if [[ ! -f /tmp/stored_exception_line ]]; then
        echo "$1" > /tmp/stored_exception_line
    fi
    return 0
}

Exception.Extract() {
    if [[ $__oo__insideTryCatch -gt 1 ]]
    then
        set -e
    fi

    __oo__insideTryCatch+=-1

    __EXCEPTION_CATCH__=( $(Exception.GetLastException) )

    local retVal=$1
    if [[ $retVal -gt 0 ]]
    then
        # BACKWARDS COMPATIBILE WAY:
        # export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
        # export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
        export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
        export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
        export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
        return 1 # so that we may continue with a "catch"
    fi
}

Exception.GetLastException() {
    if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
    then
        cat /tmp/stored_exception
        cat /tmp/stored_exception_line
        cat /tmp/stored_exception_source
    else
        echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
    fi

    rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
    return 0
}

Feel free to use, fork and contribute - it's on GitHub.

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

How can I use break or continue within for loop in Twig template?

A way to be able to use {% break %} or {% continue %} is to write TokenParsers for them.

I did it for the {% break %} token in the code below. You can, without much modifications, do the same thing for the {% continue %}.

  • AppBundle\Twig\AppExtension.php:

    namespace AppBundle\Twig;
    
    class AppExtension extends \Twig_Extension
    {
        function getTokenParsers() {
            return array(
                new BreakToken(),
            );
        }
    
        public function getName()
        {
            return 'app_extension';
        }
    }
    
  • AppBundle\Twig\BreakToken.php:

    namespace AppBundle\Twig;
    
    class BreakToken extends \Twig_TokenParser
    {
        public function parse(\Twig_Token $token)
        {
            $stream = $this->parser->getStream();
            $stream->expect(\Twig_Token::BLOCK_END_TYPE);
    
            // Trick to check if we are currently in a loop.
            $currentForLoop = 0;
    
            for ($i = 1; true; $i++) {
                try {
                    // if we look before the beginning of the stream
                    // the stream will throw a \Twig_Error_Syntax
                    $token = $stream->look(-$i);
                } catch (\Twig_Error_Syntax $e) {
                    break;
                }
    
                if ($token->test(\Twig_Token::NAME_TYPE, 'for')) {
                    $currentForLoop++;
                } else if ($token->test(\Twig_Token::NAME_TYPE, 'endfor')) {
                    $currentForLoop--;
                }
            }
    
    
            if ($currentForLoop < 1) {
                throw new \Twig_Error_Syntax(
                    'Break tag is only allowed in \'for\' loops.',
                    $stream->getCurrent()->getLine(),
                    $stream->getSourceContext()->getName()
                );
            }
    
            return new BreakNode();
        }
    
        public function getTag()
        {
            return 'break';
        }
    }
    
  • AppBundle\Twig\BreakNode.php:

    namespace AppBundle\Twig;
    
    class BreakNode extends \Twig_Node
    {
        public function compile(\Twig_Compiler $compiler)
        {
            $compiler
                ->write("break;\n")
            ;
        }
    }
    

Then you can simply use {% break %} to get out of loops like this:

{% for post in posts %}
    {% if post.id == 10 %}
        {% break %}
    {% endif %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

To go even further, you may write token parsers for {% continue X %} and {% break X %} (where X is an integer >= 1) to get out/continue multiple loops like in PHP.

How to filter files when using scp to copy dir recursively?

  1. Copy your source folder to somedir:

    cp -r srcdir somedir

  2. Remove all unneeded files:

    find somedir -name '.svn' -exec rm -rf {} \+

  3. launch scp from somedir

Marker in leaflet, click event

Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);

function markerOnClick(e)
{
  alert("hi. you clicked the marker at " + e.latlng);
}

How to see tomcat is running or not

Go to the start menu. Open up cmd (command prompt) and type in the following.

wmic process list brief | find /i "tomcat"

This would tell you if the tomcat is running or not.

How to install a specific JDK on Mac OS X?

As of Mac OS X v10.6 (Snow Leopard), you can run Java 6 in 32-bit mode on either 32-bit or 64-bit Intel processor equipped Macs.

If you cannot upgrade to Snow Leopard, Soy Latte is a pre-compiled version of Java 6 for Intel 32-bit.

C++ display stack trace on exception

If you are using C++ and don't want/can't use Boost, you can print backtrace with demangled names using the following code [link to the original site].

Note, this solution is specific to Linux. It uses GNU's libc functions backtrace()/backtrace_symbols() (from execinfo.h) to get the backtraces and then uses __cxa_demangle() (from cxxabi.h) for demangling the backtrace symbol names.

// stacktrace.h (c) 2008, Timo Bingmann from http://idlebox.net/
// published under the WTFPL v2.0

#ifndef _STACKTRACE_H_
#define _STACKTRACE_H_

#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <cxxabi.h>

/** Print a demangled stack backtrace of the caller function to FILE* out. */
static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames = 63)
{
    fprintf(out, "stack trace:\n");

    // storage array for stack trace address data
    void* addrlist[max_frames+1];

    // retrieve current stack addresses
    int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));

    if (addrlen == 0) {
    fprintf(out, "  <empty, possibly corrupt>\n");
    return;
    }

    // resolve addresses into strings containing "filename(function+address)",
    // this array must be free()-ed
    char** symbollist = backtrace_symbols(addrlist, addrlen);

    // allocate string which will be filled with the demangled function name
    size_t funcnamesize = 256;
    char* funcname = (char*)malloc(funcnamesize);

    // iterate over the returned symbol lines. skip the first, it is the
    // address of this function.
    for (int i = 1; i < addrlen; i++)
    {
    char *begin_name = 0, *begin_offset = 0, *end_offset = 0;

    // find parentheses and +address offset surrounding the mangled name:
    // ./module(function+0x15c) [0x8048a6d]
    for (char *p = symbollist[i]; *p; ++p)
    {
        if (*p == '(')
        begin_name = p;
        else if (*p == '+')
        begin_offset = p;
        else if (*p == ')' && begin_offset) {
        end_offset = p;
        break;
        }
    }

    if (begin_name && begin_offset && end_offset
        && begin_name < begin_offset)
    {
        *begin_name++ = '\0';
        *begin_offset++ = '\0';
        *end_offset = '\0';

        // mangled name is now in [begin_name, begin_offset) and caller
        // offset in [begin_offset, end_offset). now apply
        // __cxa_demangle():

        int status;
        char* ret = abi::__cxa_demangle(begin_name,
                        funcname, &funcnamesize, &status);
        if (status == 0) {
        funcname = ret; // use possibly realloc()-ed string
        fprintf(out, "  %s : %s+%s\n",
            symbollist[i], funcname, begin_offset);
        }
        else {
        // demangling failed. Output function name as a C function with
        // no arguments.
        fprintf(out, "  %s : %s()+%s\n",
            symbollist[i], begin_name, begin_offset);
        }
    }
    else
    {
        // couldn't parse the line? print the whole line.
        fprintf(out, "  %s\n", symbollist[i]);
    }
    }

    free(funcname);
    free(symbollist);
}

#endif // _STACKTRACE_H_

HTH!

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

Delete dynamically-generated table row using jQuery

A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:

 var i = 1;
$("#addbutton").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr({
      'id': function(_, id) {return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;

  applyRemoveEvent();  
});


function applyRemoveEvent(){
    $('button.removebutton').on('click',function() {
        alert("aa");
      $(this).closest( 'tr').remove();
      return false;
    });
};

applyRemoveEvent();

http://jsfiddle.net/Z7fG7/2/

In Excel, sum all values in one column in each row where another column is a specific value

If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:

=SUMIF(B:B,"No",A:A)

or

=SUMIFS(A:A,B:B,"No")

Here is an example that will display the amounts paid and outstanding for a small set of sample data.

 A         B            C                   D
 Amount    Reimbursed?  Total Paid:         =SUMIF(B:B,"Yes",A:A)
 $100      Yes          Total Outstanding:  =SUMIF(B:B,"No",A:A)
 $200      No           
 $300      No
 $400      Yes
 $500      No

Result of Excel calculations

How to check whether a variable is a class or not?

>>> class X(object):
...     pass
... 
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True

How to change options of <select> with jQuery?

If for example your html code contain this code:

<select id="selectId"><option>Test1</option><option>Test2</option></select>

In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId.

var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").html(option);

in this example above i change the old list of option by only one new option.

Angular 2 Scroll to bottom (Chat style)

In angular using material design sidenav I had to use the following:

let ele = document.getElementsByClassName('md-sidenav-content');
    let eleArray = <Element[]>Array.prototype.slice.call(ele);
    eleArray.map( val => {
        val.scrollTop = val.scrollHeight;
    });

How do I close an open port from the terminal on the Mac?

  1. Find out the process ID (PID) which is occupying the port number (e.g., 5955) you would like to free

    sudo lsof -i :5955
    
  2. Kill the process which is currently using the port using its PID

    sudo kill -9 PID
    

Given a filesystem path, is there a shorter way to extract the filename without its extension?

try

System.IO.Path.GetFileNameWithoutExtension(path); 

demo

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''

https://msdn.microsoft.com/en-gb/library/system.io.path.getfilenamewithoutextension%28v=vs.80%29.aspx

Difference between filter and filter_by in SQLAlchemy

It is a syntax sugar for faster query writing. Its implementation in pseudocode:

def filter_by(self, **kwargs):
    return self.filter(sql.and_(**kwargs))

For AND you can simply write:

session.query(db.users).filter_by(name='Joe', surname='Dodson')

btw

session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))

can be written as

session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))

Also you can get object directly by PK via get method:

Users.query.get(123)
# And even by a composite PK
Users.query.get(123, 321)

When using get case its important that object can be returned without database request from identity map which can be used as cache(associated with transaction)

Add php variable inside echo statement as href link address?

If you want to print in the tabular form with, then you can use this:

echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;

Centering FontAwesome icons vertically and horizontally

So I finally got it(http://jsfiddle.net/ncapito/eYtU5/):

.centerWrapper:before {
    content:'';
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}

.center {
    display:inline-block;
    vertical-align: middle;
}

<div class='row'>
    <div class='login-icon'>
        <div class='centerWrapper'>
            <div class='center'> <i class='icon-user'></i></div>
       </div>
    </div>
    <input type="text" placeholder="Email" />
 </div>

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Sometimes you don't control the target machine (e.g. your library needs to run on a locked-down enterprise system). In such a case you will need to recompile your code using the version of GCC that corresponds to their GLIBCXX version. In that case, you can do the following:

  1. Look up the latest version of GLIBCXX supported by the target machine: strings /usr/lib/libstdc++.so.6 | grep GLIBC ... Say the version is 3.4.19.
  2. Use https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html to find the corresponding GCC version. In our case, this is [4.8.3, 4.9.0).

How to replace text in a column of a Pandas dataframe?

In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:

import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'

df['string_col'].str.replace(regular_expression, '', regex=True)

initializing a boolean array in java

Arrays in Java start indexing at 0. So in your example you are referring to an element that is outside the array by one.

It should probably be something like freq[Global.iParameter[2]-1]=false;

You would need to loop through the array to initialize all of it, this line only initializes the last element.

Actually, I'm pretty sure that false is default for booleans in Java, so you might not need to initialize at all.

Best Regards

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Personnaly I encountered this issue while migrating a IIS6 website into IIS7, in order to fix this issue I used this command line :
%windir%\System32\inetsrv\appcmd migrate config "MyWebSite\"
Make sure to backup your web.config

How can you undo the last git add?

  • Remove the file from the index, but keep it versioned and left with uncommitted changes in working copy:

    git reset head <file>
    
  • Reset the file to the last state from HEAD, undoing changes and removing them from the index:

    git reset HEAD <file>
    git checkout <file>
    
    # If you have a `<branch>` named like `<file>`, use:
    git checkout -- <file>
    

    This is needed since git reset --hard HEAD won't work with single files.

  • Remove <file> from index and versioning, keeping the un-versioned file with changes in working copy:

    git rm --cached <file>
    
  • Remove <file> from working copy and versioning completely:

    git rm <file>
    

Get File Path (ends with folder)

Have added ErrorHandler to this in case the user hits the cancel button instead of selecting a folder. So instead of getting a horrible error message you get a message that a folder must be selected and then the routine ends. Below code also stores the folder path in a range name (Which is just linked to cell A1 on a sheet).

Sub SelectFolder()

Dim diaFolder As FileDialog

'Open the file dialog
On Error GoTo ErrorHandler
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Title = "Select a folder then hit OK"
diaFolder.Show
Range("IC_Files_Path").Value = diaFolder.SelectedItems(1)
Set diaFolder = Nothing
Exit Sub

ErrorHandler:
Msg = "No folder selected, you must select a folder for program to run"
Style = vbError
Title = "Need to Select Folder"
Response = MsgBox(Msg, Style, Title)

End Sub

How do I script a "yes" response for installing programs?

If you want to just accept defaults you can use:

\n | ./shell_being_run

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I was getting the same exception, whenever a page was getting loaded,

NFO: Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
    at org.apache.coyote.http11.InternalInputBuffer.parseRequestLine(InternalInputBuffer.java:139)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1028)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

I found that one of my page URL was https instead of http, when I changed the same, error was gone.

How to add a WiX custom action that happens only on uninstall (via MSI)?

I used Custom Action separately coded in C++ DLL and used the DLL to call appropriate function on Uninstalling using this syntax :

<CustomAction Id="Uninstall" BinaryKey="Dll_Name" 
              DllEntry="Function_Name" Execute="deferred" />

Using the above code block, I was able to run any function defined in C++ DLL on uninstall. FYI, my uninstall function had code regarding Clearing current user data and registry entries.

Swift - How to detect orientation changes

Using NotificationCenter and UIDevice's beginGeneratingDeviceOrientationNotifications

Swift 4.2+

override func viewDidLoad() {
    super.viewDidLoad()        

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}

deinit {
   NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)         
}

func rotated() {
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

Swift 3

override func viewDidLoad() {
    super.viewDidLoad()        

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}

deinit {
     NotificationCenter.default.removeObserver(self)
}

func rotated() {
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

How do I remove accents from characters in a PHP string?

This answer I've got following tips here, so it is not really mine. It works for me using LATIN1 or UTF-8. If you use other charsets, you probably should add them to mb_detect_encoding function. Correct environment set is probably needed also.

function NoAccents($s){
        return iconv(mb_detect_encoding($s,'UTF-8, ASCII, ISO-8859-1'),'ASCII//TRANSLIT//INGORE',$s);
}

How to update Android Studio automatically?

I am having a similar problem while updating from 2.3.2 to 2.3.3.

Go to the bin folder of your Android Studio installation folder: e.g.

cd opt/android-studio/bin

Provide run permission for studio.sh file: chmod +x studio.sh

Run Android Studio from here: ./studio.sh

and try "update and restart" from android studio.

How to "EXPIRE" the "HSET" child key in redis?

You can use Sorted Set in redis to get a TTL container with timestamp as score. For example, whenever you insert a event string into the set you can set its score to the event time. Thus you can get data of any time window by calling zrangebyscore "your set name" min-time max-time

Moreover, we can do expire by using zremrangebyscore "your set name" min-time max-time to remove old events.

The only drawback here is you have to do housekeeping from an outsider process to maintain the size of the set.

Invalid application of sizeof to incomplete type with a struct

Your error is also shown when trying to access the sizeof() of an non-initialized extern array:

extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'

Note that you would get an array size missing error without the extern keyword.

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

Entity Framework select distinct name

In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT error, the best should be

var results = (
    from ta in DBContext.TestAddresses
    select ta.Name
)
.Distinct()
.OrderBy( x => 1);

C: printf a float value

printf("%0k.yf" float_variable_name)

Here k is the total number of characters you want to get printed. k = x + 1 + y (+ 1 for the dot) and float_variable_name is the float variable that you want to get printed.

Suppose you want to print x digits before the decimal point and y digits after it. Now, if the number of digits before float_variable_name is less than x, then it will automatically prepend that many zeroes before it.

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

How do I force Postgres to use a particular index?

Sometimes PostgreSQL fails to make the best choice of indexes for a particular condition. As an example, suppose there is a transactions table with several million rows, of which there are several hundred for any given day, and the table has four indexes: transaction_id, client_id, date, and description. You want to run the following query:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description = 'Refund'
GROUP BY client_id

PostgreSQL may choose to use the index transactions_description_idx instead of transactions_date_idx, which may lead to the query taking several minutes instead of less than one second. If this is the case, you can force using the index on date by fudging the condition like this:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description||'' = 'Refund'
GROUP BY client_id

Difference between RUN and CMD in a Dockerfile

RUN - command triggers while we build the docker image.

CMD - command triggers while we launch the created docker image.

How to check if a div is visible state or not?

You can use .css() to get the value of "visibility":

 if( ! ( $("#singlechatpanel-1").css('visibility') === "hidden")){
 }

http://api.jquery.com/css/

org.hibernate.MappingException: Unknown entity

In hibernate.cfg.xml , please put following code

<mapping class="class/bo name"/>

How can I specify a local gem in my Gemfile?

I believe you can do this:

gem "foo", path: "/path/to/foo"

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

How to put a Scanner input into an array... for example a couple of numbers

public static void main (String[] args)
{
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter size of an array");
    int n=s.nextInt();
    double arr[] = new double[n];
    System.out.println("Please enter elements of array:");
    for (int i=0; i<n; i++)
    {
        arr[i] = s.nextDouble();
    }
}

How to find the nearest parent of a Git branch?

Git comes with a couple of GUI clients that helps you visualize this. Open GitGUI and go to menu Repository > Visualize All Branch History

Use different Python version with virtualenv

Yes you just need to install the other version of python, and define the location of your other version of python in your command like :

virtualenv /home/payroll/Documents/env -p /usr/bin/python3

jQuery UI Sortable Position

As per the official documentation of the jquery sortable UI: http://api.jqueryui.com/sortable/#method-toArray

In update event. use:

var sortedIDs = $( ".selector" ).sortable( "toArray" );

and if you alert or console this var (sortedIDs). You'll get your sequence. Please choose as the "Right Answer" if it is a right one.

Get current time in milliseconds in Python?

If you want a simple method in your code that returns the milliseconds with datetime:

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

# returns the elapsed milliseconds since the start of the program
def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

dplyr mutate with conditional values

Try this:

myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

or this:

myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

Note

Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

Above used this input:

myfile <- 
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

Update 2 dplyr now has case_when which provides another solution:

myfile %>% 
       mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                             V2 == 4 & V3 != 1 ~ 2,
                             TRUE ~ 0))

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

You are converting cert into BKS Keystore, why aren't you using .cert directly, from https://developer.android.com/training/articles/security-ssl.html:

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.gtux_cert);
Certificate ca;
try {
    ca = cf.generateCertificate(instream);
} finally {
    caInput.close();
}

KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);

TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(););
tmf.init(kStore);

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

okHttpClient.setSslSocketFactory(context.getSocketFactory());

Absolute vs relative URLs

If it is for use within your website, it's better practice to use relative URL, like this if you need to move the website to another domain name or just debug locally, you can.

Take a look at what's stackoverflow is doing (ctrl+U in firefox):

<a href="/users/recent/90691"> // Link to an internal element

In some cases they use absolute urls :

<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=5934">

... but this is only it's a best practice to improve speed. In your case, it doesn't look like you're doing anything like that so I wouldn't worry about it.

How to create permanent PowerShell Aliases

This is a little bit fancy... but it works:

Step 1: Create a Powershell Profile:

FILE: install_profile.ps1
# THIS SCRIPT BLOWS AWAY YOUR DEFAULT POWERSHELL PROFILE SCRIPT
#   AND INSTALLS A POINTER TO A GLOBAL POWERSHELL PROFILE

$ErrorActionPreference = "Stop"

function print ([string]$msg)
{
    Write-Host -ForegroundColor Green $msg
}

print ""

# User's Powershell Profile
$psdir  = "$env:USERPROFILE\Documents\WindowsPowerShell"
$psfile = $psdir + "\Microsoft.PowerShell_profile.ps1"

print "Creating Directory: $psdir"
md $psdir -ErrorAction SilentlyContinue | out-null

# this is your auto-generated powershell profile to be installed
$content = @(
    "",
    ". ~/Documents/tools/profile.ps1",
    ""
)

print "Creating File: $psfile"
[System.IO.File]::WriteAllLines($psfile, $content)

print ""

# Make sure Powershell profile is readable
Set-ExecutionPolicy -Scope CurrentUser Unrestricted

Step 2: then in tools ~/Documents/tools/profile.ps1:

function Do-ActualThing {
    # do actual thing
}

Set-Alias MyAlias Do-ActualThing

Step 3:

$ Set-ExecutionPolicy -Scope CurrentUser Unrestricted $ . ./install_profile.ps1

React.js: Set innerHTML vs dangerouslySetInnerHTML

Yes there is a difference!

The immediate effect of using innerHTML versus dangerouslySetInnerHTML is identical -- the DOM node will update with the injected HTML.

However, behind the scenes when you use dangerouslySetInnerHTML it lets React know that the HTML inside of that component is not something it cares about.

Because React uses a virtual DOM, when it goes to compare the diff against the actual DOM, it can straight up bypass checking the children of that node because it knows the HTML is coming from another source. So there's performance gains.

More importantly, if you simply use innerHTML, React has no way to know the DOM node has been modified. The next time the render function is called, React will overwrite the content that was manually injected with what it thinks the correct state of that DOM node should be.

Your solution to use componentDidUpdate to always ensure the content is in sync I believe would work but there might be a flash during each render.

How to match hyphens with Regular Expression?

It’s less confusing to always use an escaped hyphen, so that it doesn't have to be positionally dependent. That’s a \- inside the bracketed character class.

But there’s something else to consider. Some of those enumerated characters should possibly be written differently. In some circumstances, they definitely should.

This comparison of regex flavors says that C? can use some of the simpler Unicode properties. If you’re dealing with Unicode, you should probably use the general category \p{L} for all possible letters, and maybe \p{Nd} for decimal numbers. Also, if you want to accomodate all that dash punctuation, not just HYPHEN-MINUS, you should use the \p{Pd} property. You might also want to write that sequence of whitespace characters simply as \s, assuming that’s not too general for you.

All together, that works out to apattern of [\p{L}\p{Nd}\p{Pd}!$*] to match any one character from that set.

I’d likely use that anyway, even if I didn’t plan on dealing with the full Unicode set, because it’s a good habit to get into, and because these things often grow beyond their original parameters. Now when you lift it to use in other code, it will still work correctly. If you hard-code all the characters, it won’t.

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

What is sr-only in Bootstrap 3?

Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".

<div class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only">Error:</span>
  Enter a valid email address
</div>

Glyphicon will be displayed on all other devices, word Error: on text readers.

How To: Execute command line in C#, get STD OUT results

You can launch any command line program using the Process class, and set the StandardOutput property of the Process instance with a stream reader you create (either based on a string or a memory location). After the process completes, you can then do whatever diff you need to on that stream.

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

How can I replace the deprecated set_magic_quotes_runtime in php?

In PHP 7 we can use:

ini_set('magic_quotes_runtime', 0);

instead of set_magic_quotes_runtime(0);

Finding all possible combinations of numbers to reach a given sum

Excel VBA version below. I needed to implement this in VBA (not my preference, don't judge me!), and used the answers on this page for the approach. I'm uploading in case others also need a VBA version.

Option Explicit

Public Sub SumTarget()
    Dim numbers(0 To 6)  As Long
    Dim target As Long

    target = 15
    numbers(0) = 3: numbers(1) = 9: numbers(2) = 8: numbers(3) = 4: numbers(4) = 5
    numbers(5) = 7: numbers(6) = 10

    Call SumUpTarget(numbers, target)
End Sub

Public Sub SumUpTarget(numbers() As Long, target As Long)
    Dim part() As Long
    Call SumUpRecursive(numbers, target, part)
End Sub

Private Sub SumUpRecursive(numbers() As Long, target As Long, part() As Long)

    Dim s As Long, i As Long, j As Long, num As Long
    Dim remaining() As Long, partRec() As Long
    s = SumArray(part)

    If s = target Then Debug.Print "SUM ( " & ArrayToString(part) & " ) = " & target
    If s >= target Then Exit Sub

    If (Not Not numbers) <> 0 Then
        For i = 0 To UBound(numbers)
            Erase remaining()
            num = numbers(i)
            For j = i + 1 To UBound(numbers)
                AddToArray remaining, numbers(j)
            Next j
            Erase partRec()
            CopyArray partRec, part
            AddToArray partRec, num
            SumUpRecursive remaining, target, partRec
        Next i
    End If

End Sub

Private Function ArrayToString(x() As Long) As String
    Dim n As Long, result As String
    result = "{" & x(n)
    For n = LBound(x) + 1 To UBound(x)
        result = result & "," & x(n)
    Next n
    result = result & "}"
    ArrayToString = result
End Function

Private Function SumArray(x() As Long) As Long
    Dim n As Long
    SumArray = 0
    If (Not Not x) <> 0 Then
        For n = LBound(x) To UBound(x)
            SumArray = SumArray + x(n)
        Next n
    End If
End Function

Private Sub AddToArray(arr() As Long, x As Long)
    If (Not Not arr) <> 0 Then
        ReDim Preserve arr(0 To UBound(arr) + 1)
    Else
        ReDim Preserve arr(0 To 0)
    End If
    arr(UBound(arr)) = x
End Sub

Private Sub CopyArray(destination() As Long, source() As Long)
    Dim n As Long
    If (Not Not source) <> 0 Then
        For n = 0 To UBound(source)
                AddToArray destination, source(n)
        Next n
    End If
End Sub

Output (written to the Immediate window) should be:

SUM ( {3,8,4} ) = 15
SUM ( {3,5,7} ) = 15
SUM ( {8,7} ) = 15
SUM ( {5,10} ) = 15 

What is the difference between Set and List?

The biggest different is the basic concept.

From the Set and List interface. Set is mathematics concept. Set method extends collection.however not add new method. size() means cardinality(more is BitSet.cardinality, Linear counter,Log Log,HyperLogLog). addAll() means union. retainAll() means intersection. removeAll() means difference.

However List lack of these concepts. List add a lot of method to support sequence concept which Collection interface not supply. core concept is INDEX. like add(index,element),get(index),search(indexOf()),remove(index) element. List also provide "Collection View" subList. Set do not have view. do not have positional access. List also provide a lot of algorithms in Collections class. sort(List),binarySearch(List),reverse(List),shuffle(List),fill(List). the method params is List interface. duplicate elements are just the result of concepts. not the essential difference.

So the essential difference is concept. Set is mathematics set concept.List is sequence concept.

How to test if a string is basically an integer in quotes using Ruby

You can do a one liner:

str = ...
int = Integer(str) rescue nil

if int
  int.times {|i| p i}
end

or even

int = Integer(str) rescue false

Depending on what you are trying to do you can also directly use a begin end block with rescue clause:

begin
  str = ...
  i = Integer(str)

  i.times do |j|
    puts j
  end
rescue ArgumentError
  puts "Not an int, doing something else"
end

How to clear all inputs, selects and also hidden fields in a form using jQuery?

for empty all input tags such as input,select,textatea etc. run this code

$('#message').val('').change();

Python memory usage of numpy arrays

In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

I use this code to get a listing of all of them and their size.

Not sure if locals() or globals() is better here.

import sys
import numpy
from humanize import naturalsize

for size, name in sorted(
    (value.nbytes, name)
    for name, value in locals().items()
    if isinstance(value, numpy.ndarray)):
  print("{:>30}: {:>8}".format(name, naturalsize(size)))

How large is a DWORD with 32- and 64-bit code?

Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.

In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.

You can find the official list here: http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx

All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

My error was solved after adding this dependency.

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.16.Final</version>
    </dependency>

Selenium WebDriver: Wait for complex page with JavaScript to load

If all you need to do is wait for the html on the page to become stable before trying to interact with elements, you can poll the DOM periodically and compare the results, if the DOMs are the same within the given poll time, you're golden. Something like this where you pass in the maximum wait time and the time between page polls before comparing. Simple and effective.

public void waitForJavascript(int maxWaitMillis, int pollDelimiter) {
    double startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < startTime + maxWaitMillis) {
        String prevState = webDriver.getPageSource();
        Thread.sleep(pollDelimiter); // <-- would need to wrap in a try catch
        if (prevState.equals(webDriver.getPageSource())) {
            return;
        }
    }
}

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

I use @Test annotiation of org.junit.Test package, but I had the same problem. After adding testImplementation("org.assertj:assertj-core:3.10.0") on build.gradle, it worked.

cannot find module "lodash"

For me, I update node and npm to the latest version and it works.

Best way to find the months between two dates

You can also use the arrow library. This is a simple example:

from datetime import datetime
import arrow

start = datetime(2014, 1, 17)
end = datetime(2014, 6, 20)

for d in arrow.Arrow.range('month', start, end):
    print d.month, d.format('MMMM')

This will print:

1 January
2 February
3 March
4 April
5 May
6 June

Hope this helps!

$apply already in progress error

You can $apply your changes only if $apply is not already in progress. You can update your code as

if(!$scope.$$phase) $scope.$apply();

Writing a pandas DataFrame to CSV file

To delimit by a tab you can use the sep argument of to_csv:

df.to_csv(file_name, sep='\t')

To use a specific encoding (e.g. 'utf-8') use the encoding argument:

df.to_csv(file_name, sep='\t', encoding='utf-8')

How to turn off gcc compiler optimization to enable buffer overflow

That's a good problem. In order to solve that problem you will also have to disable ASLR otherwise the address of g() will be unpredictable.

Disable ASLR:

sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'

Disable canaries:

gcc overflow.c -o overflow -fno-stack-protector

After canaries and ASLR are disabled it should be a straight forward attack like the ones described in Smashing the Stack for Fun and Profit

Here is a list of security features used in ubuntu: https://wiki.ubuntu.com/Security/Features You don't have to worry about NX bits, the address of g() will always be in a executable region of memory because it is within the TEXT memory segment. NX bits only come into play if you are trying to execute shellcode on the stack or heap, which is not required for this assignment.

Now go and clobber that EIP!

What is VanillaJS?

"Vanilla JS” is an expression that got popular after the publishing of a satire website in 2012 (http://vanilla-js.com/). There’s a section covering its story/meaning in this post.

So why the joke? It kind of came as a modern response to the old school knee-jerk reflex of relying on jQuery and additional JS libraries. With the ECMAScript spec and modern browsers capabilities, the need to bypass plain JS with external libraries to maintain consistency across browsers just isn’t there anymore. Here’s a site that shows you how true this is with concrete examples: http://youmightnotneedjquery.com/

How to set top position using jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

It checks whether the page has been called through POST (as opposed to GET, HEAD, etc). When you type a URL in the menu bar, the page is called through GET. However, when you submit a form with method="post" the action page is called with POST.

Python check if list items are integers?

Fast, simple, but maybe not always right:

>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']

More traditional if you need to get numbers:

new_list = []
for value in mylist:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:

try:
    new_list.append(str(int(value)))

How to recover deleted rows from SQL server table?

I think thats impossible, sorry.

Thats why whenever running a delete or update you should always use BEGIN TRANSACTION, then COMMIT if successful or ROLLBACK if not.

AngularJS toggle class using ng-class

I made this work in this way:

<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>

in your controller:

$scope.toggleClass = function (event) {
    $(event.target).toggleClass('active');
}

How to write "not in ()" sql query using join

SELECT d1.Short_Code 
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL

How to close activity and go back to previous activity in android

{ getApplicationContext.finish();   }

Try this method..

Reading and writing value from a textfile by using vbscript code

This script will read lines from large file and write to new small files. Will duplicate the header of the first line (Header) to all child files

Dim strLine
lCounter = 1
fCounter = 1
cPosition = 1
MaxLine = 1000
splitAt = MaxLine
Dim fHeader
sFile = "inputFile.txt"
dFile = LEFT(sFile, (LEN(sFile)-4))& "_0" & fCounter & ".txt"
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(sFile,1)
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
do while not objFileToRead.AtEndOfStream
        strLine = objFileToRead.ReadLine()
        objFileToWrite.WriteLine(strLine)
        If cPosition = 1 Then
            fHeader = strLine
        End If
        If cPosition = splitAt Then
            fCounter = fCounter + 1
            splitAt = splitAt + MaxLine
            objFileToWrite.Close
            Set objFileToWrite = Nothing
            If fCounter < 10 Then
                dFile=LEFT(dFile, (LEN(dFile)-5))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            ElseIf fCounter <100 Or fCounter = 100 Then
                dFile=LEFT(dFile, (LEN(dFile)-6))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            Else
                dFile=LEFT(dFile, (LEN(dFile)-7)) & fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            End If
        End If
        lCounter=lCounter + 1
        cPosition=cPosition + 1
Loop
objFileToWrite.Close
Set objFileToWrite = Nothing
objFileToRead.Close
Set objFileToRead = Nothing

Replace Div with another Div

HTML

<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>

JavaScript

jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));

Use superscripts in R axis labels

This is a quick example

plot(rnorm(30), xlab = expression(paste("4"^"th")))

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

Differences between Lodash and Underscore.js

They are pretty similar, with Lodash is taking over...

They both are a utility library which takes the world of utility in JavaScript...

It seems Lodash is getting updated more regularly now, so more used in the latest projects...

Also Lodash seems is lighter by a couple of KBs...

Both have a good API and documentation, but I think the Lodash one is better...

Here is a screenshot for each of the documentation items for getting the first value of an array...

Underscore.js:

Underscore.js

Lodash:

Lodash

As things may get updated time to time, just check their website also...

Lodash

Underscore.js

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Display special characters when using print statement

Use repr:

a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))

How can I add a table of contents to a Jupyter / JupyterLab notebook?

There is an ipython nbextension that constructs a table of contents for a notebook. It seems to only provide navigation, not section folding.

Convert java.util.date default format to Timestamp in Java

java.time

I am providing the modern answer. The Timestamp class was always poorly designed, a real hack on top of the already poorly designed Date class. Both those classes are now long outdated. Don’t use them.

When the question was asked, you would need a Timestamp for sending a point in time to the SQL database. Since JDBC 4.2 that is no longer the case. Assuming your database needs a timestamp with time zone (recommended for true timestamps), pass it an OffsetDateTime.

Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013: the time zone abbreviation. IST may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing.

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("EEE MMM dd HH:mm:ss ")
            .appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
            .appendPattern(" yyyy")
            .toFormatter(Locale.ROOT);
    String dateString = "Mon May 27 11:46:15 IST 2013";
    OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
            .atOffset(ZoneOffset.UTC);
    System.out.println(dateTime);

This snippet prints:

2013-05-27T06:16:15Z

This is the UTC equivalent of your string (assuming IST was for India Standard Time). Pass the OffsetDateTime to your database using one of the PreparedStatement.setObject methods (not setTimestamp).

How can I convert this into timestamp and calculate in seconds the difference between the same and current time?

Calculating the difference in seconds goes very naturally with java.time:

    long differenceInSeconds = ChronoUnit.SECONDS
            .between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
    System.out.println(differenceInSeconds);

When running just now I got:

202213260

Link: Oracle tutorial: Date Time explaining how to use java.time.

Sorting a Dictionary in place with respect to keys

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

How to change value of ArrayList element in java

The list is maintaining an object reference to the original value stored in the list. So when you execute this line:

Integer x = i.next();

Both x and the list are storing a reference to the same object. However, when you execute:

x = Integer.valueOf(9);

nothing has changed in the list, but x is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as

list.set(index, Integer.valueof(9))

Note: this has nothing to do with the immutability of Integer, as others are suggesting. This is just basic Java object reference behaviour.


Here's a complete example, to help explain the point. Note that this makes use of the ListIterator class, which supports removing/setting items mid-iteration:

import java.util.*;

public class ListExample {

  public static void main(String[] args) {

    List<Foo> fooList = new ArrayList<Foo>();
    for (int i = 0; i < 9; i++)
      fooList.add(new Foo(i, i));

    // Standard iterator sufficient for altering elements
    Iterator<Foo> iterator = fooList.iterator();

    if (iterator.hasNext()) {
      Foo foo = iterator.next();
      foo.x = 99;
      foo.y = 42;
    }

    printList(fooList);    

    // List iterator needed for replacing elements
    ListIterator<Foo> listIterator = fooList.listIterator();

    if (listIterator.hasNext()) {
      // Need to call next, before set.
      listIterator.next();
      // Replace item returned from next()
      listIterator.set(new Foo(99,99));
    }

    printList(fooList);
  }

  private static void printList(List<?> list) {
    Iterator<?> iterator = list.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next());
    }
    System.out.println();
  }

  private static class Foo {
    int x;
    int y;

    Foo(int x, int y) {
      this.x = x;
      this.y = y;
    }

    @Override
    public String toString() {
      return String.format("[%d, %d]", x, y);
    }
  }
}

This will print:

[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]

'True' and 'False' in Python

From 6.11. Boolean operations:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.

The expression '/bla/bla/bla' will be treated as true where a Boolean expression is expected (like in an if statement), but the expressions '/bla/bla/bla' is True and '/bla/bla/bla' == True will evaluate to False for the reasons in Ignacio's answer.

What is the difference between up-casting and down-casting with respect to class variable

Down-casting and up-casting was as follows:
enter image description here

Upcasting: When we want to cast a Sub class to Super class, we use Upcasting(or widening). It happens automatically, no need to do anything explicitly.

Downcasting : When we want to cast a Super class to Sub class, we use Downcasting(or narrowing), and Downcasting is not directly possible in Java, explicitly we have to do.

Dog d = new Dog();
Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting
d.callme();
a.callme(); // It calls Dog's method even though we use Animal reference.
((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly.
// Internally if it is not a Dog object it throws ClassCastException

Embedding DLLs in a compiled executable

Generally you would need some form of post build tool to perform an assembly merge like you are describing. There is a free tool called Eazfuscator (eazfuscator.blogspot.com/) which is designed for bytecode mangling that also handles assembly merging. You can add this into a post build command line with Visual Studio to merge your assemblies, but your mileage will vary due to issues that will arise in any non trival assembly merging scenarios.

You could also check to see if the build make untility NANT has the ability to merge assemblies after building, but I am not familiar enough with NANT myself to say whether the functionality is built in or not.

There are also many many Visual Studio plugins that will perform assembly merging as part of building the application.

Alternatively if you don't need this to be done automatically, there are a number of tools like ILMerge that will merge .net assemblies into a single file.

The biggest issue I've had with merging assemblies is if they use any similar namespaces. Or worse, reference different versions of the same dll (my problems were generally with the NUnit dll files).

How to take the first N items from a generator or list?

@Shaikovsky's answer is excellent (…and heavily edited since I posted this answer), but I wanted to clarify a couple of points.

[next(generator) for _ in range(n)]

This is the most simple approach, but throws StopIteration if the generator is prematurely exhausted.


On the other hand, the following approaches return up to n items which is preferable in many circumstances:

List: [x for _, x in zip(range(n), records)]

Generator: (x for _, x in zip(range(n), records))

How do you make div elements display inline?

Try writing it like this:

_x000D_
_x000D_
div { border: 1px solid #CCC; }
_x000D_
    <div style="display: inline">a</div>_x000D_
    <div style="display: inline">b</div>_x000D_
    <div style="display: inline">c</div>
_x000D_
_x000D_
_x000D_

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

How can I create a "Please Wait, Loading..." animation using jQuery?

SVG animations are probably a better solution to this problem. You won't need to worry about writing CSS and compared to GIFs, you'll get better resolution and alpha transparency. Some very good SVG loading animations that you can use are here: http://samherbert.net/svg-loaders/

You can also use those animations directly through a service I built: https://svgbox.net/iconset/loaders. It allows you to customize the fill and direct usage (hotlinking) is permitted.

To accomplish what you want to do with jQuery, you probably should have a loading info element hidden and use .show() when you want to show the loader. For eg, this code shows the loader after one second:

_x000D_
_x000D_
setTimeout(function() {
  $("#load").show();
}, 1000)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<div id="load" style="display:none">
    Please wait... 
    <img src="//s.svgbox.net/loaders.svg?fill=maroon&ic=tail-spin" 
         style="width:24px">
</div>
_x000D_
_x000D_
_x000D_

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

No connection could be made because the target machine actively refused it 127.0.0.1

Had the same problem, it turned out it was the WindowsFirewall blocking connections. Try to disable WindowsFirewall for a while to see if helps and if it is the problem open ports as needed.

Adding days to $Date in PHP

Here is the simplest solution to your query

$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days 
echo date_format($date,"Y-m-d"); //set date format of the result

remove empty lines from text file with PowerShell

If you actually want to filter blank lines from a file then you may try this:

(gc $source_file).Trim() | ? {$_.Length -gt 0}

CentOS 7 and Puppet unable to install nc

Nc is a link to nmap-ncat.

It would be nice to use nmap-ncat in your puppet, because NC is a virtual name of nmap-ncat.

Puppet cannot understand the links/virtualnames

your puppet should be:

package {
  'nmap-ncat':
    ensure => installed;
}

jQuery.active function

For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:

jQuery.ajaxPrefilter(function( options ) {
    options.global = true;
});

Keep in mind that you'll need a timeout on your JSONP request to catch failures.

How to nicely format floating numbers to string without unnecessary decimal 0's

If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:

public static String fmt(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
}

Produces:

232
0.18
1237875192
4.58
0
1.2345

And does not rely on string manipulation.

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

How to update array value javascript?

"But i want to know a better way to do this, if there is one ?"

Yes, since you seem to already have the original object, there's no reason to fetch it again from the Array.

  function Update(keyValue, newKey, newValue)
  {
    keyValue.Key = newKey;
    keyValue.Value = newValue; 
  }

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

You can use ax.figure.savefig(), as suggested in a comment on the question:

import pandas as pd

df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

Where is web.xml in Eclipse Dynamic Web Project

Follow below steps to generate web.xml in Eclipse with existing Dynamic Web Project

  1. Right Click on Created Dynamic Web Project
  2. Mouse Over Java EE Tools
  3. Click on Generate Deployment Descriptor Stub
  4. Now you are able to see web.xml file on WEB-INF folder

enter image description here

Commenting multiple lines in DOS batch file

Another option is to enclose the unwanted lines in an IF block that can never be true

if 1==0 (
...
)

Of course nothing within the if block will be executed, but it will be parsed. So you can't have any invalid syntax within. Also, the comment cannot contain ) unless it is escaped or quoted. For those reasons the accepted GOTO solution is more reliable. (The GOTO solution may also be faster)

Update 2017-09-19

Here is a cosmetic enhancement to pdub's GOTO solution. I define a simple environment variable "macro" that makes the GOTO comment syntax a bit better self documenting. Although it is generally recommended that :labels are unique within a batch script, it really is OK to embed multiple comments like this within the same batch script.

@echo off
setlocal

set "beginComment=goto :endComment"

%beginComment%
Multi-line comment 1
goes here
:endComment

echo This code executes

%beginComment%
Multi-line comment 2
goes here
:endComment

echo Done

Or you could use one of these variants of npocmaka's solution. The use of REM instead of BREAK makes the intent a bit clearer.

rem.||(
   remarks
   go here
)

rem^ ||(
   The space after the caret
   is critical
)

Using Laravel Homestead: 'no input file specified'

This is easy to fix, because you have changed the folder name to: exampleproject

So SSH to your vagrant:

ssh [email protected] -p 2222

Then change your nginx config:

sudo vi /etc/nginx/sites-enabled/homestead.app

Edit the correct URI to the root on line 3 to this with the new folder name:

root "/Users/MYUSERNAME/Code/exampleproject/public";

Restart Nginx

sudo service nginx reload

Reload the web browser, it should work now

How to suppress Pandas Future warning ?

Found this on github...

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

import pandas

Django: save() vs update() to update the database?

Using update directly is more efficient and could also prevent integrity problems.

From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:

e = Entry.objects.get(id=10)
e.comments_on = False
e.save()

…do this:

Entry.objects.filter(id=10).update(comments_on=False)

Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().

How to add a TextView to LinearLayout in Android

In Kotlin you can add Textview as follows.

 val textView = TextView(activity).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, 20, 0, 0)
                setPadding(10, 10, 0, 10)
            }
            text = "SOME TEXT"
            setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimary))
            setTextColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimaryDark))
            textSize = 16.0f
            typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        }
 linearLayoutContainer.addView(textView)

npm install from Git in a specific version

If by version you mean a tag or a release, then github provides download links for those. For example, if I want to install fetch version 0.3.2 (it is not available on npm), then I add to my package.json under dependencies:

"fetch": "https://github.com/github/fetch/archive/v0.3.2.tar.gz",

The only disadvantage when compared with the commit hash approach is that a hash is guaranteed not to represent changed code, whereas a tag could be replaced. Thankfully this rarely happens.

Update:

These days the approach I use is the compact notation for a GitHub served dependency:

"dependencies": {
  "package": "github:username/package#commit"
}

Where commit can be anything commitish, like a tag. In the case of GitHub you can even drop the initial github: since it's the default.

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

My problem was solved that way:

Your username is probably restricted, You must grant full access to the user.

  1. Right Click on Project and select Properties
  2. Click on Tab Security
  3. Click Edit button
  4. Found Current User and Permission for User Allow Full Control

how to start the tomcat server in linux?

Go to your Tomcat Directory with : cd/home/user/apache-tomcat6.0

  • sh bin/startup.sh.>> tail -f logs/catelina.out.>>

What is the difference between "is None" and "== None"

If you use numpy,

if np.zeros(3)==None: pass

will give you error when numpy does elementwise comparison

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

How to turn a vector into a matrix in R?

A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:

vec <- 1:49
dim(vec) <- c(7, 7)  ## (rows, cols)
vec

> vec <- 1:49
> dim(vec) <- c(7, 7)  ## (rows, cols)
> vec
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    8   15   22   29   36   43
[2,]    2    9   16   23   30   37   44
[3,]    3   10   17   24   31   38   45
[4,]    4   11   18   25   32   39   46
[5,]    5   12   19   26   33   40   47
[6,]    6   13   20   27   34   41   48
[7,]    7   14   21   28   35   42   49

Spring Boot JPA - configuring auto reconnect

Setting spring.datasource.tomcat.testOnBorrow=true in application.properties didn't work.

Programmatically setting like below worked without any issues.

import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;    

@Bean
public DataSource dataSource() {
    PoolProperties poolProperties = new PoolProperties();
    poolProperties.setUrl(this.properties.getDatabase().getUrl());         
    poolProperties.setUsername(this.properties.getDatabase().getUsername());            
    poolProperties.setPassword(this.properties.getDatabase().getPassword());

    //here it is
    poolProperties.setTestOnBorrow(true);
    poolProperties.setValidationQuery("SELECT 1");

    return new DataSource(poolProperties);
}

How to set image for bar button with swift?

Only two Lines of code required for this

Swift 3.0

let closeButtonImage = UIImage(named: "ic_close_white")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(ResetPasswordViewController.barButtonDidTap(_:)))

func barButtonDidTap(_ sender: UIBarButtonItem) 
{

}

How do I print an IFrame from javascript in Safari/Chrome

Use this:

window.onload = setTimeout("window.print()", 1000);

how to fire event on file select

<input id="fusk" type="file" name="upload" style="display: none;"
    onChange=" document.getElementById('myForm').submit();"
>

How to change the remote repository for a git submodule?

These commands will do the work on command prompt without altering any files on local repository

git config --file=.gitmodules submodule.Submod.url https://github.com/username/ABC.git
git config --file=.gitmodules submodule.Submod.branch Development
git submodule sync
git submodule update --init --recursive --remote

Please look at the blog for screenshots: Changing GIT submodules URL/Branch to other URL/branch of same repository

push object into array

The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.

var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
    for (var j=0; j<arr1.length; j++) {
        resultArray[j] = new makeArray(arr1[j], arr2[j]);
    }
function makeArray(first,second) {
    this.first = first;
    this.second = second;
}

Setting value of active workbook in Excel VBA

You're probably after Set wbOOR = ThisWorkbook

Just to clarify

ThisWorkbook will always refer to the workbook the code resides in

ActiveWorkbook will refer to the workbook that is active

Be careful how you use this when dealing with multiple workbooks. It really depends on what you want to achieve as to which is the best option.

OrderBy descending in Lambda expression?

This only works in situations where you have a numeric field, but you can put a minus sign in front of the field name like so:

reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);

However this works a little bit different than OrderByDescending when you have are running it on an int? or double? or decimal? fields.

What will happen is on OrderByDescending the nulls will be at the end, vs with this method the nulls will be at the beginning. Which is useful if you want to shuffle nulls around without splitting data into pieces and splicing it later.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

JQuery / JavaScript - trigger button click from another button click event

this works fine, but file name does not display anymore.

$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });

Valid characters in a Java class name

Identifiers are used for class names, method names, and variable names. An identifiermay be any descriptive sequence of uppercase and lowercase letters, numbers, or theunderscore and dollar-sign characters. They must not begin with a number, lest they beconfused with a numeric literal. Again, Java is case-sensitive, so VALUE is a differentidentifier than Value. Some examples of valid identifiers are:

AvgTemp ,count a4 ,$test ,this_is_ok

Invalid variable names include:

2count, high-temp, Not/ok

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

Background service with location listener in android

Background location service. It will be restarted even after killing the app.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    AlarmManager alarmManager;
    Button stop;
    PendingIntent pendingIntent;

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

        if (alarmManager == null) {
            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, AlarmReceive.class);
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000,
                    pendingIntent);
        }
    }
}

BookingTrackingService.java

public class BookingTrackingService extends Service implements LocationListener {

    private static final String TAG = "BookingTrackingService";
    private Context context;
    boolean isGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude, longitude;
    LocationManager locationManager;
    Location location;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    long notify_interval = 30000;

    public double track_lat = 0.0;
    public double track_lng = 0.0;
    public static String str_receiver = "servicetutorial.service.receiver";
    Intent intent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
        intent = new Intent(str_receiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        this.context = this;


        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy <<");
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    private void trackLocation() {
        Log.e(TAG, "trackLocation");
        String TAG_TRACK_LOCATION = "trackLocation";
        Map<String, String> params = new HashMap<>();
        params.put("latitude", "" + track_lat);
        params.put("longitude", "" + track_lng);

        Log.e(TAG, "param_track_location >> " + params.toString());

        stopSelf();
        mTimer.cancel();

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /******************************/

    private void fn_getlocation() {
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnable && !isNetworkEnable) {
            Log.e(TAG, "CAN'T GET LOCATION");
            stopSelf();
        } else {
            if (isNetworkEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {

                        Log.e(TAG, "isNetworkEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            if (isGPSEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        Log.e(TAG, "isGPSEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            Log.e(TAG, "START SERVICE");
            trackLocation();

        }
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    fn_getlocation();
                }
            });

        }
    }

//    private void fn_update(Location location) {
//
//        intent.putExtra("latutide", location.getLatitude() + "");
//        intent.putExtra("longitude", location.getLongitude() + "");
//        sendBroadcast(intent);
//    }
}

AlarmReceive.java (BroadcastReceiver)

public class AlarmReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("Service_call_"  , "You are in AlarmReceive class.");
        Intent background = new Intent(context, BookingTrackingService.class);
//        Intent background = new Intent(context, GoogleService.class);
        Log.e("AlarmReceive ","testing called broadcast called");
        context.startService(background);
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 <service
            android:name=".ServiceAndBroadcast.BookingTrackingService"
            android:enabled="true" />

        <receiver
            android:name=".ServiceAndBroadcast.AlarmReceive"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Alright, this is probably the easiest way to do it:

  1. First of all, you will have to install GAPPS.
  2. Next, open the virtual box and wait for the home screen to show up on Genymotion.
  3. Drag and drop the GAPPS folder that you had downloaded earlier on into Genymotion.
  4. You would get a prompt. Click OK. You would see a lot of errors, but just ignore them and wait for the successful prompt to come up. Click OK again and restart the virtual device.
  5. A Google account screen should show up. Open up the playstore app if it doesn't show up. Sign into your account. Again ignore the errors.
  6. The playstore should open now and should be fully functional.

Undefined index error PHP

Apparently the index 'productid' is missing from your html form. Inspect your html inputs first. eg <input type="text" name="productid" value=""> But this will handle the current error PHP is raising.

  $rowID = isset($_POST['rowID']) ? $_POST['rowID'] : '';
  $productid = isset($_POST['productid']) ? $_POST['productid'] : '';
  $name = isset($_POST['name']) ? $_POST['name'] : '';
  $price = isset($_POST['price']) ? $_POST['price'] : '';
  $description = isset($_POST['description']) ? $_POST['description'] : '';

Test for multiple cases in a switch, like an OR (||)

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}

BACKUP LOG cannot be performed because there is no current database backup

  1. Make sure there is a new database.
  2. Make sure you have access to your database (user, password etc).
  3. Make sure there is a backup file with no error in it.

Hope this can help you.

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

gpg decryption fails with no secret key error

I have solved this problem, try to use root privileges, such as sudo gpg ... I think that gpg elevated without permissions does not refer to file permissions, but system

How can I monitor the thread count of a process on linux?

jvmtop can show the current jvm thread count beside other metrics.

Uninstall Django completely

open the CMD and use this command :

**

pip uninstall django

**

it will easy uninstalled .

jQuery function after .append

For images and other sources you can use that:

$(el).one('load', function(){
    // completed
}).each(function() {
    if (this.complete)
        $(this).load();
});

Returning a boolean value in a JavaScript function

Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.

function  func(){
return true;
}

isBool = func();
console.log(typeof (isBool));   // output - string


let isBool = func();
console.log(typeof (isBool));   // output - boolean

Mercurial undo last commit

One way would be hg rollback (deprecated as of Hg2.7, August 2013)

Please use hg commit --amend instead of rollback to correct mistakes in the last commit.

Roll back the last transaction in a repository.

When committing or merging, Mercurial adds the changeset entry last.
Mercurial keeps a transaction log of the name of each file touched and its length prior to the transaction. On abort, it truncates each file to its prior length. This simplicity is one benefit of making revlogs append-only. The transaction journal also allows an undo operation.

See TortoiseHg Recovery section:

alt text

This thread also details the difference between hg rollback and hg strip:
(written by Martin Geisler who also contributes on SO)

  • 'hg rollback' will remove the last transaction. Transactions are a concept often found in databases. In Mercurial we start a transaction when certain operations are run, such as commit, push, pull...
    When the operation finishes succesfully, the transaction is marked as complete. If an error occurs, the transaction is "rolled back" and the repository is left in the same state as before.
    You can manually trigger a rollback with 'hg rollback'. This will undo the last transactional command. If a pull command brought 10 new changesets into the repository on different branches, then 'hg rollback' will remove them all. Please note: there is no backup when you rollback a transaction!

  • 'hg strip' will remove a changeset and all its descendants. The changesets are saved as a bundle, which you can apply again if you need them back.

ForeverWintr suggests in the comments (in 2016, 5 years later)

You can 'un-commit' files by first hg forgetting them, e.g.: hg forget filea; hg commit --amend, but that seems unintuitive.
hg strip --keep is probably a better solution for modern hg.

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

How to resize image automatically on browser width resize but keep same height?

It is an old question but i want to add that if you want to resize image according to viewport size only with css; you can use viewport units "vh (viewport height) or vw (viewport width)".

.img {
width: 100vw;
height: 100vh;
}

See browser supports

ASP.NET Web API session or something?

in Global.asax add

public override void Init()
{
    this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
    base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(
        SessionStateBehavior.Required);
}

give it a shot ;)

How can I force a long string without any blank to be wrapped?

If you're using PHP then the wordwrap function works well for this: http://php.net/manual/en/function.wordwrap.php

The CSS solution word-wrap: break-word; does not seem to be consistent across all browsers.

Other server-side languages have similar functions - or can be hand built.

Here's how the the PHP wordwrap function works:

$string = "ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTCGATGTAGCTAGTAGCATGTAGTGA";

$wrappedstring = wordwrap($string,50,"&lt;br&gt;",true);

This wraps the string at 50 characters with a <br> tag. The 'true' parameter forces the string to be cut.

How to convert jsonString to JSONObject in Java

There are various Java JSON serializers and deserializers linked from the JSON home page.

As of this writing, there are these 22:

...but of course the list can change.

How to test if a list contains another list?

Here a solution with less line of code and easily understandable (or at least I like to think so).

If you want to keep order (match only if the smaller list is found in the same order on the bigger list):

def is_ordered_subset(l1, l2):
    # First check to see if all element of l1 are in l2 (without checking order)
    if not set(l1).issubset(l2): 
        return False

    length = len(l1)
    # Make sublist of same size than l1
    list_of_sublist = [l2[i:i+length] for i, x in enumerate(l2)]
    #Check if one of this sublist is l1
    return l1 in list_of_sublist 

SpringMVC RequestMapping for GET parameters

This works in my case:

@RequestMapping(value = "/savedata",
            params = {"textArea", "localKey", "localFile"})
    @ResponseBody
    public void saveData(@RequestParam(value = "textArea") String textArea,
                         @RequestParam(value = "localKey") String localKey,
                         @RequestParam(value = "localFile") String localFile) {
}

Laravel requires the Mcrypt PHP extension

For those who still come here today:

Laravel does not need mcrypt extension anymore. mcrypt is obsolete, the last update to libmcrypt was in 2007. Laravel 4.2 is obsolete too and has no more support. The best (=secure) solution is to update to Laravel >5.1 (there is no LTS before Laravel 5.2).

Mcrypt was removed from Laravel in June 2015: https://github.com/laravel/framework/pull/9041

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

Ok, so this might not fix your issue but it definitely worked for me.

So you've created your Mysql user I take it? Go to user privileges on PhpMyAdmin and click edit next to the user your using for Symfony. Scroll down to near the bottom and where it says which host you want to use make sure you've selected LocalHost not % Any.

Then in your config file swap 127.0.0.1 for localhost. Hopefully that will work for you. Just worked for me as I was having the same issue.

Force table column widths to always be fixed regardless of contents

This works for me

td::after { 
content: ''; 
display: block; 
width: 30px;
}

Skip first couple of lines while reading lines in Python file

This solution helped me to skip the number of lines specified by the linetostart variable. You get the index (int) and the line (string) if you want to keep track of those too. In your case, you substitute linetostart with 18, or assign 18 to linetostart variable.

f = open("file.txt", 'r')
for i, line in enumerate(f, linetostart):
    #Your code

How to calculate growth with a positive and negative number?

Simplest solution is the following:

=(NEW/OLD-1)*SIGN(OLD)

The SIGN() function will result in -1 if the value is negative and 1 if the value is positive. So multiplying by that will conditionally invert the result if the previous value is negative.