Programs & Examples On #Popupcontrolextender

The PopupExtender is part of the AJAX Control Toolkit for ASP.net

Stop handler.postDelayed()

  Boolean condition=false;  //Instance variable declaration.

 //-----------------Inside oncreate--------------------------------------------------- 
  start =(Button)findViewById(R.id.id_start);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                starthandler();

                if(condition=true)
                {
                    condition=false;
                }


            }
        });

        stop=(Button) findViewById(R.id.id_stoplocatingsmartplug);

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stophandler();

            }
        });


    }

//-----------------Inside oncreate---------------------------------------------------

 public void starthandler()
    {

        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {


                if(!condition)
                {
                    //Do something after 100ms 


                }

            }
        }, 5000);

    }


    public void stophandler()
    {
        condition=true;
    }

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

I am using Windows 10 Home edition.

I tried various combination,

netsh wlan show drivers
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=allow ssid=happy key=12345678
netsh wlan start hostednetwork

and also,

Control Panel\Network and Internet\Network Connections\Ethernet Properties\Sharing\Internet Connection Sharing\Allow other network users to connect through this computer Internet connection...

But still cannot activate WiFi hotspot.

While I have given up, somehow I click on Network icon on the taskbar, suddenly I see the buttons:

[ Wi-Fi ] [ Airplane Mode ] [ Mobile hotspot ]

Just like how our mobile phone can enable Mobile hotspot, Windows 10 has Mobile hotspot build-in. Just click on [ Mobile hotspot ] button and it works.

How to check if X server is running?

I often need to run an X command on a server that is running many X servers, so the ps based answers do not work. Naturally, $DISPLAY has to be set appropriately. To check that that is valid, use xset q in some fragment like:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

EDIT

Some people find that xset can pause for a annoying amount of time before deciding that $DISPLAY is not pointing at a valid X server (often when tcp/ip is the transport). The fix of course is to use timeout to keep the pause amenable, 1 second say.

if ! timeout 1s xset q &>/dev/null; then
    ?

Android Fragment onAttach() deprecated

Activity is a context so if you can simply check the context is an Activity and cast it if necessary.

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

Update: Some are claiming that the new Context override is never called. I have done some tests and cannot find a scenario where this is true and according to the source code, it should never be true. In all cases I tested, both pre and post SDK23, both the Activity and the Context versions of onAttach were called. If you can find a scenario where this is not the case, I would suggest you create a sample project illustrating the issue and report it to the Android team.

Update 2: I only ever use the Android Support Library fragments as bugs get fixed faster there. It seems the above issue where the overrides do not get called correctly only comes to light if you use the framework fragments.

How to delete history of last 10 commands in shell?

With Bash 5 you can now do a range...Hooray!:

history -d 511-520

or counting backwards 10:

history -d -10--1

Excerpt from Bash 5 Man Page:

'history'

Options, if supplied, have the following meanings:

'-d OFFSET' Delete the history entry at position OFFSET. If OFFSET is positive, it should be specified as it appears when the history is displayed. If OFFSET is negative, it is interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of '-1' refers to the current 'history -d' command.

'-d START-END' Delete the history entries between positions START and END, inclusive. Positive and negative values for START and END are interpreted as described above.

Here is my solution for Bash 4. It iteratively deletes a single entry or a range of history starting with lowest index.

delHistory () {
    count=$(( ${2:-$1} - $1 ))
    while [[ $count -ge 0 ]]; do
        history -d "$1"
        ((count--))
    done
}

delHistory 511 520

Eclipse - Unable to install breakpoint due to missing line number attributes

I had this problem while attempting to start Tomcat in debugging mode from Eclipse. I had an ANT build file taking care of the compile and deploy. After setting the debug flag to true (as mentioned in other answers) and redeploying the application it worked fine:

<javac srcdir="./src/java" destdir="./bin" debug="true">

NOTE: if you've just added the debug flag and recompiled you still need to redeploy your application to the server since this is where Eclipse is debugging the class files. Very obvious but easy to spend an hour or so scratching your head and wondering why it's not working (trust me).

What's the difference between "app.render" and "res.render" in express.js?

along with these two variants, there is also jade.renderFile which generates html that need not be passed to the client.

usage-

var jade = require('jade');

exports.getJson = getJson;

function getJson(req, res) {
    var html = jade.renderFile('views/test.jade', {some:'json'});
    res.send({message: 'i sent json'});
}

getJson() is available as a route in app.js.

How do I calculate the normal vector of a line segment?

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

Another potential cause for this error: Attempting to get permission for a Facebook app in sandbox mode when the Facebook user is not listed in the app's admins, developers or testers.

Difference between checkout and export in SVN

As you stated, a checkout includes the .svn directories. Thus it is a working copy and will have the proper information to make commits back (if you have permission). If you do an export you are just taking a copy of the current state of the repository and will not have any way to commit back any changes.

fatal error LNK1104: cannot open file 'kernel32.lib'

I just met and solved this problem by myself. My problem is a little different. I'm using visual studio on Windows 10. When I create the project, the Target Platform Version was automatically set to 10.0.15063.0. But there is no kernel32.lib for this version of SDK, neither are other necessary header files and lib files. So I modified the Target Platform Version to 8.1. And it worked.

Environment:

  • Windows 10
  • Visual Studio 2015
  • Visual C++

Solution:

  1. Open the project's Property Page;
  2. Navigate to General page;
  3. Modify Target Platform Version to the desired target platform (e.g. 8.1).

Forms authentication timeout vs sessionState timeout

      <sessionState timeout="2" />
      <authentication mode="Forms">
          <forms name="userLogin" path="/" timeout="60" loginUrl="Login.aspx" slidingExpiration="true"/>
      </authentication>

This configuration sends me to the login page every two minutes, which seems to controvert the earlier answers

How do you serve a file for download with AngularJS or Javascript?

In our current project at work we had a invisible iFrame and I had to feed the url for the file to the iFrame to get a download dialog box. On the button click, the controller generates the dynamic url and triggers a $scope event where a custom directive I wrote, is listing. The directive will append a iFrame to the body if it does not exist already and sets the url attribute on it.

EDIT: Adding a directive

appModule.directive('fileDownload', function ($compile) {
    var fd = {
        restrict: 'A',
        link: function (scope, iElement, iAttrs) {

            scope.$on("downloadFile", function (e, url) {
                var iFrame = iElement.find("iframe");
                if (!(iFrame && iFrame.length > 0)) {
                    iFrame = $("<iframe style='position:fixed;display:none;top:-1px;left:-1px;'/>");
                    iElement.append(iFrame);
                }

                iFrame.attr("src", url);


            });
        }
    };

    return fd;
});

This directive responds to a controller event called downloadFile

so in your controller you do

$scope.$broadcast("downloadFile", url);

How do I run a batch file from my Java Application?

To expand on @Isha's anwser you could just do the following to get the returned output (post-facto not in rea-ltime) of the script that was run:

try {
    Process process = Runtime.getRuntime().exec("cmd /c start D:\\temp\\a.bat");
    System.out.println(process.getText());
} catch(IOException e) {
    e.printStackTrace();
}

Getting hold of the outer class object from the inner class object

The more general answer to this question involves shadowed variables and how they are accessed.

In the following example (from Oracle), the variable x in main() is shadowing Test.x:

class Test {
    static int x = 1;
    public static void main(String[] args) {
        InnerClass innerClassInstance = new InnerClass()
        {
            public void printX()
            {
                System.out.print("x=" + x);
                System.out.println(", Test.this.x=" + Test.this.x);
            }
        }
        innerClassInstance.printX();
    }

    public abstract static class InnerClass
    {
        int x = 0;

        public InnerClass() { }

        public abstract void printX();
    }
}

Running this program will print:

x=0, Test.this.x=1

More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

How do I remove my IntelliJ license in 2019.3?

I think there are more solutions!

You can start the app, and here are 3 things you can do:

  1. If the app shows for the first time the "import settings" dialog and then the "create/open a project" dialog, you can click on Settings > Manage License... > Remove License, and that removes for all Jetbrains products*.
  2. If you open products like IntelliJ IDEA and have projects currently active (like the app open automatically the all IDE without prompt), then click on File > Close Project, and follow the first step.
  3. Inside any app of IntelliJ, click on Help > Register... > Remove license.

*In case you have a license for a pack of products. If not, you have to remove the license per product individually. Check the 3rd step.

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

Bootstrap navbar Active State not working

If you don't use anchor links, you can use something like this:

$(document).ready(function () {
    $.each($('#navbar').find('li'), function() {
        $(this).toggleClass('active',
            '/' + $(this).find('a').attr('href') == window.location.pathname);
    });
});

Purge or recreate a Ruby on Rails database

Simply you can run

rake db:setup

It will drop database, create new database and populate db from seed if you created seed file with some data.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I cheated problem using transition by steps, not smoothly

transition-timing-function: steps(10, end);

It is not a solving, it is a cheating and can not be applied everywhere.

I can't explain it, but it works for me. None of another answers helps me (OSX, Chrome 63, Non-Retina display).

https://jsfiddle.net/tuzae6a9/6/

Define global variable with webpack

There are several way to approach globals:

  1. Put your variables in a module.

Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js. Then it will execute entry.js. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?

config.js

export default {
    FOO: 'bar'
}

somefile.js

import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)

Note: If you want the instance to be new each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

  1. Webpack's ProvidePlugin

Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo' again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).

Step 1) Create any module. For example, a global set of utilities would be handy:

utils.js

export function sayHello () {
  console.log('hello')
}

Step 2) Alias the module and add to ProvidePlugin:

webpack.config.js

var webpack = require("webpack");
var path = require("path");

// ...

module.exports = {

  // ...

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'utils': path.resolve(__dirname, './utils')  // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
    }
  },

  plugins: [

    // ...

    new webpack.ProvidePlugin({
      'utils': 'utils'
    })
  ]  

}

Now just call utils.sayHello() in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.

Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.

  1. Use Webpack's DefinePlugin

If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

Use it like:

console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
  1. Use the global window object (or Node's global)

window.foo = 'bar'  // For SPA's, browser environment.
global.foo = 'bar'  // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/

You'll see this commonly used for polyfills, for example: window.Promise = Bluebird

  1. Use a package like dotenv

(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.

// As early as possible in your application, require and configure dotenv.    
require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

That's it.

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Notes:

Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

IMHO, the best explanation about its meaning gave us Stroustrup + take into account examples of Dániel Sándor and Mohan:

Stroustrup:

Now I was seriously worried. Clearly we were headed for an impasse or a mess or both. I spent the lunchtime doing an analysis to see which of the properties (of values) were independent. There were only two independent properties:

  • has identity – i.e. and address, a pointer, the user can determine whether two copies are identical, etc.
  • can be moved from – i.e. we are allowed to leave to source of a "copy" in some indeterminate, but valid state

This led me to the conclusion that there are exactly three kinds of values (using the regex notational trick of using a capital letter to indicate a negative – I was in a hurry):

  • iM: has identity and cannot be moved from
  • im: has identity and can be moved from (e.g. the result of casting an lvalue to a rvalue reference)
  • Im: does not have identity and can be moved from.

    The fourth possibility, IM, (doesn’t have identity and cannot be moved) is not useful in C++ (or, I think) in any other language.

In addition to these three fundamental classifications of values, we have two obvious generalizations that correspond to the two independent properties:

  • i: has identity
  • m: can be moved from

This led me to put this diagram on the board: enter image description here

Naming

I observed that we had only limited freedom to name: The two points to the left (labeled iM and i) are what people with more or less formality have called lvalues and the two points on the right (labeled m and Im) are what people with more or less formality have called rvalues. This must be reflected in our naming. That is, the left "leg" of the W should have names related to lvalue and the right "leg" of the W should have names related to rvalue. I note that this whole discussion/problem arise from the introduction of rvalue references and move semantics. These notions simply don’t exist in Strachey’s world consisting of just rvalues and lvalues. Someone observed that the ideas that

  • Every value is either an lvalue or an rvalue
  • An lvalue is not an rvalue and an rvalue is not an lvalue

are deeply embedded in our consciousness, very useful properties, and traces of this dichotomy can be found all over the draft standard. We all agreed that we ought to preserve those properties (and make them precise). This further constrained our naming choices. I observed that the standard library wording uses rvalue to mean m (the generalization), so that to preserve the expectation and text of the standard library the right-hand bottom point of the W should be named rvalue.

This led to a focused discussion of naming. First, we needed to decide on lvalue. Should lvalue mean iM or the generalization i? Led by Doug Gregor, we listed the places in the core language wording where the word lvalue was qualified to mean the one or the other. A list was made and in most cases and in the most tricky/brittle text lvalue currently means iM. This is the classical meaning of lvalue because "in the old days" nothing was moved; move is a novel notion in C++0x. Also, naming the topleft point of the W lvalue gives us the property that every value is an lvalue or an rvalue, but not both.

So, the top left point of the W is lvalue and the bottom right point is rvalue. What does that make the bottom left and top right points? The bottom left point is a generalization of the classical lvalue, allowing for move. So it is a generalized lvalue. We named it glvalue. You can quibble about the abbreviation, but (I think) not with the logic. We assumed that in serious use generalized lvalue would somehow be abbreviated anyway, so we had better do it immediately (or risk confusion). The top right point of the W is less general than the bottom right (now, as ever, called rvalue). That point represent the original pure notion of an object you can move from because it cannot be referred to again (except by a destructor). I liked the phrase specialized rvalue in contrast to generalized lvalue but pure rvalue abbreviated to prvalue won out (and probably rightly so). So, the left leg of the W is lvalue and glvalue and the right leg is prvalue and rvalue. Incidentally, every value is either a glvalue or a prvalue, but not both.

This leaves the top middle of the W: im; that is, values that have identity and can be moved. We really don’t have anything that guides us to a good name for those esoteric beasts. They are important to people working with the (draft) standard text, but are unlikely to become a household name. We didn’t find any real constraints on the naming to guide us, so we picked ‘x’ for the center, the unknown, the strange, the xpert only, or even x-rated.

Steve showing off the final product

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

In case of lazy loading, you just need to import MatDialogModule in lazy loaded module. Then this module will be able to render entry component with its own imported MatDialogModule:

@NgModule({
  imports:[
    MatDialogModule
  ],
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    HomeComponent,
    DialogResultExampleDialog        
  ],
  entryComponents: [DialogResultExampleDialog]

When to use a View instead of a Table?

Views are acceptable when you need to ensure that complex logic is followed every time. For instance, we have a view that creates the raw data needed for all financial reporting. By having all reports use this view, everyone is working from the same data set, rather than one report using one set of joins and another forgetting to use one which gives different results.

Views are acceptable when you want to restrict users to a particular subset of data. For instance, if you do not delete records but only mark the current one as active and the older versions as inactive, you want a view to use to select only the active records. This prevents people from forgetting to put the where clause in the query and getting bad results.

Views can be used to ensure that users only have access to a set of records - for instance, a view of the tables for a particular client and no security rights on the tables can mean that the users for that client can only ever see the data for that client.

Views are very helpful when refactoring databases.

Views are not acceptable when you use views to call views which can result in horrible performance (at least in SQL Server). We almost lost a multimillion dollar client because someone chose to abstract the database that way and performance was horrendous and timeouts frequent. We had to pay for the fix too, not the client, as the performance issue was completely our fault. When views call views, they have to completely generate the underlying view. I have seen this where the view called a view which called a view and so many millions of records were generated in order to see the three the user ultimately needed. I remember one of these views took 8 minutes to do a simple count(*) of the records. Views calling views are an extremely poor idea.

Views are often a bad idea to use to update records as usually you can only update fields from the same table (again this is SQL Server, other databases may vary). If that's the case, it makes more sense to directly update the tables anyway so that you know which fields are available.

XPath: Get parent node from child node

Use the parent axes with the parent node's name.

//*[title="50"]/parent::store

This XPath will only select the parent node if it is a store.

But you can also use one of these

//*[title="50"]/parent::*
//*[title="50"]/..

These xpaths will select any parent node. So if the document changes you will always select a node, even if it is not the node you expect.

EDIT

What happens in the given example where the parent is a bicycle but the parent of the parent is a store?

Does it ascent?

No, it only selects the store if it is a parent of the node that matches //*[title="50"].

If not, is there a method to ascent in such cases and return None if there is no such parent?

Yes, you can use ancestor axes

//*[title="50"]/ancestor::store

This will select all ancestors of the node matching //*[title="50"] that are ` stores. E.g.

<data xmlns:d="defiant-namespace" d:mi="23">
    <store mi="1">
        <store mi="22">
            <book price="8.95" d:price="Number" d:mi="13">
                <title d:constr="String" d:mi="10">50</title>
                <category d:constr="String" d:mi="11">reference</category>
                <author d:constr="String" d:mi="12">Nigel Rees</author>
            </book>
        </store>
    </store>
</data>

XPath selection result

ASP.NET custom error page - Server.GetLastError() is null

Here is my solution..

In Global.aspx:

void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

        //direct user to error page 
        Server.Transfer("~/ErrorPages/Oops.aspx"); 
    }

In Oops.aspx:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadError(Server.GetLastError()); 
    }

    protected void LoadError(Exception objError)
    {
        if (objError != null)
        {
            StringBuilder lasterror = new StringBuilder();

            if (objError.Message != null)
            {
                lasterror.AppendLine("Message:");
                lasterror.AppendLine(objError.Message);
                lasterror.AppendLine();
            }

            if (objError.InnerException != null)
            {
                lasterror.AppendLine("InnerException:");
                lasterror.AppendLine(objError.InnerException.ToString());
                lasterror.AppendLine();
            }

            if (objError.Source != null)
            {
                lasterror.AppendLine("Source:");
                lasterror.AppendLine(objError.Source);
                lasterror.AppendLine();
            }

            if (objError.StackTrace != null)
            {
                lasterror.AppendLine("StackTrace:");
                lasterror.AppendLine(objError.StackTrace);
                lasterror.AppendLine();
            }

            ViewState.Add("LastError", lasterror.ToString());
        }
    }

   protected void btnReportError_Click(object sender, EventArgs e)
    {
        SendEmail();
    }

    public void SendEmail()
    {
        try
        {
            MailMessage msg = new MailMessage("webteam", "webteam");
            StringBuilder body = new StringBuilder();

            body.AppendLine("An unexcepted error has occurred.");
            body.AppendLine();

            body.AppendLine(ViewState["LastError"].ToString());

            msg.Subject = "Error";
            msg.Body = body.ToString();
            msg.IsBodyHtml = false;

            SmtpClient smtp = new SmtpClient("exchangeserver");
            smtp.Send(msg);
        }

        catch (Exception ex)
        {
            lblException.Text = ex.Message;
        }
    }

pandas: find percentile stats of a given column

I figured out below would work:

my_df.dropna().quantile([0.0, .9])

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

How to add a margin to a table row <tr>

For what is worth, I took advantage that I was already using bootstrap (4.3), because I needed to add margin, box-shadow and border-radius to my row, something I can't do with tables.

<div id="loop" class="table-responsive px-4">
<section>
    <div id="thead" class="row m-0">
        <div class="col"></div>
        <div class="col"></div>
        <div class="col"></div>
    </div>
    <div id="tbody" class="row m-0">
        <div class="col"></div>
        <div class="col"></div>
        <div class="col"></div>
    </div>
</section>
</div>

On css I added a few lines to mantain the table behavior of bootstrap

@media (max-width: 800px){
    #loop{
        section{
            min-width: 700px;
        }
    }
}

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

How to wait in a batch script?

You can ping an address that doesn't exist and specify the desired timeout:

ping 192.0.2.2 -n 1 -w 10000 > nul

And since the address does not exist, it'll wait 10,000 ms (10 seconds) and return.

  • The -w 10000 part specifies the desired timeout in milliseconds.
  • The -n 1 part tells ping that it should only try once (normally it'd try 4 times).
  • The > nul part is appended so the ping command doesn't output anything to screen.

You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and using the above technique:

rem SLEEP.BAT - sleeps by the supplied number of seconds

@ping 192.0.2.2 -n 1 -w %1000 > nul

NOTE (September 2002): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:

192.0.2.0/24 - This block is assigned as "TEST-NET" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Exclusions and provided dependencies will not work in child projects.

If you are using inheritance in Maven projects you must include this configuration on the parent pom.xml file. You will have a <parent>...</parent> section in your pom.xml if you are using inheritance. So you will have something like this in your parent pom.xml:

<groupId>some.groupId</groupId>
<version>1.0</version>
<artifactId>someArtifactId</artifactId>
<packaging>pom</packaging>
<modules>
    <module>child-module-1</module>
    <module>child-module-2</module>
</modules>
<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

How to check if a database exists in SQL Server?

From a Microsoft's script:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'db exists'

react-router - pass props to handler component

for the react-router 2.5.2,the solution is so easy:

    //someConponent
...
render:function(){
  return (
    <h1>This is the parent component who pass the prop to this.props.children</h1>
    {this.props.children && React.cloneElement(this.props.children,{myProp:'value'})}
  )
}
...

How to get highcharts dates in the x axis?

Check this sample out from the Highcharts API.

Replace this

return Highcharts.dateFormat('%a %d %b', this.value);

With this

return Highcharts.dateFormat('%a %d %b %H:%M:%S', this.value);

Look here about the dateFormat() function.

Also see - tickInterval and pointInterval

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

This approach is working, but I don't how, can anyone explain, how does it works..

String s = sc.next();
s += sc.nextLine();

Import PEM into Java Key Store

First, convert your certificate in a DER format :

openssl x509 -outform der -in certificate.pem -out certificate.der

And after, import it in the keystore :

keytool -import -alias your-alias -keystore cacerts -file certificate.der

How to return XML in ASP.NET?

XmlDocument xd = new XmlDocument();
xd.LoadXml(xmlContent);

context.Response.Clear();
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
xd.Save(context.Response.Output);
context.Response.Flush();
context.Response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();

FIFO based Queue implementations?

Here is example code for usage of java's built-in FIFO queue:

public static void main(String[] args) {
    Queue<Integer> myQ = new LinkedList<Integer>();
    myQ.add(1);
    myQ.add(6);
    myQ.add(3);
    System.out.println(myQ);   // 1 6 3
    int first = myQ.poll();    // retrieve and remove the first element
    System.out.println(first); // 1
    System.out.println(myQ);   // 6 3
}

How to easily import multiple sql files into a MySQL database?

Just type below command on your command prompt & it will bind all sql file into single sql file,

c:/xampp/mysql/bin/sql/ type *.sql > OneFile.sql;

Showing alert in angularjs when user leaves a page

Lets seperate your question, you are asking about two different things:

1.

I'm trying to write a validation which alerts the user when he tries to close the browser window.

2.

I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2.

For the first question, do it this way:

window.onbeforeunload = function (event) {
  var message = 'Sure you want to leave?';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}

And for the second question, do it this way:

You should handle the $locationChangeStart event in order to hook up to view transition event, so use this code to handle the transition validation in your controller/s:

function MyCtrl1($scope) {
    $scope.$on('$locationChangeStart', function(event) {
        var answer = confirm("Are you sure you want to leave this page?")
        if (!answer) {
            event.preventDefault();
        }
    });
}

When do items in HTML5 local storage expire?

If you’re familiar with the browsers locaStorage object, you know that there’s no provision for providing an expiry time. However, we can use Javascript to add a TTL (Time to live) to invalidate items in locaStorage after a certain period of time elapses.

function setLocalStorageItem(key, value, ttl) {
    // `item` is an object which contains the original value
    // as well as the time when it's supposed to expire
    let item = {
        value: value,
        expiry: ttl ? Date.now() + ttl : null
    };

    localStorage.setItem(key, JSON.stringify(item));
}

function getLocalStorageItem(key) {
    let item = localStorage.getItem(key);
    
    // if the item doesn't exist, return null
    if (!item) return null;

    item = JSON.parse(item);
    // compare the expiry time of the item with the current time
    if (item.expiry && Date.now() > item.expiry) {
        // If the item is expired, delete the item from storage and return null
        localStorage.removeItem(key);

        return null;
    }
    
    return item.value;
}

How to close a web page on a button click, a hyperlink or a link button click?

To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

How to get duplicate items from a list using LINQ?

Hope this wil help

int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };

var duplicates = listOfItems 
    .GroupBy(i => i)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key);

foreach (var d in duplicates)
    Console.WriteLine(d);

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

What is the target platform of your application? I think you should set the platform to x86, do not set it to Any CPU.

Best way to remove the last character from a string built with stringbuilder

The simplest and most efficient way is to perform this command:

data.Length--;

by doing this you move the pointer (i.e. last index) back one character but you don't change the mutability of the object. In fact, clearing a StringBuilder is best done with Length as well (but do actually use the Clear() method for clarity instead because that's what its implementation looks like):

data.Length = 0;

again, because it doesn't change the allocation table. Think of it like saying, I don't want to recognize these bytes anymore. Now, even when calling ToString(), it won't recognize anything past its Length, well, it can't. It's a mutable object that allocates more space than what you provide it, it's simply built this way.

Pandas - Compute z-score for all columns

To calculate a z-score for an entire column quickly, do as follows:

from scipy.stats import zscore
import pandas as pd

df = pd.DataFrame({'num_1': [1,2,3,4,5,6,7,8,9,3,4,6,5,7,3,2,9]})
df['num_1_zscore'] = zscore(df['num_1'])

display(df)

jQuery Event Keypress: Which key was pressed?

The event.keyCode and event.which are depracated. See @Gibolt answer above or check documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

event.key should be used instead

keypress event is depracated as well: https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

Add text at the end of each line

You could try using something like:

sed -n 's/$/:80/' ips.txt > new-ips.txt

Provided that your file format is just as you have described in your question.

The s/// substitution command matches (finds) the end of each line in your file (using the $ character) and then appends (replaces) the :80 to the end of each line. The ips.txt file is your input file... and new-ips.txt is your newly-created file (the final result of your changes.)


Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:

sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt

So, for example, if your input file looked something like this (note the :80):

127.0.0.1
128.0.0.0:80
121.121.33.111

The final result would look something like this:

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

Do the parentheses after the type name make a difference with new?

Assuming that Test is a class with a defined constructor, there's no difference. The latter form makes it a little clearer that Test's constructor is running, but that's about it.

TensorFlow: "Attempting to use uninitialized value" in variable initialization

Run this:

init = tf.global_variables_initializer()
sess.run(init)

Or (depending on the version of TF that you have):

init = tf.initialize_all_variables()
sess.run(init)

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Adding to this. If you use both INSERT IGNORE and ON DUPLICATE KEY UPDATE in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE clause itself causes a duplicate key error, that error will be ignored.

This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.

CREATE TABLE test 
 (id BIGINT (20) UNSIGNED AUTO_INCREMENT, 
  str VARCHAR(20), 
  PRIMARY KEY(id), 
  UNIQUE(str));

INSERT INTO test (str) VALUES('A'),('B');

/* duplicate key error caused not by the insert, 
but by the update: */
INSERT INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A'; 

/* duplicate key error is suppressed */
INSERT IGNORE INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A';

Conda environments not showing up in Jupyter Notebook

In my case, using Windows 10 and conda 4.6.11, by running the commands

conda install nb_conda

conda install -c conda-forge nb_conda_kernels

from the terminal while having the environment active didn't do the job after I opened Jupyter from the same command line using conda jupyter notebook.

The solution was apparently to opened Jupyter from the Anaconda Navigator by going to my environment in Environments: Open Anaconda Navigator, select the environment in Environments, press on the "play" button on the chosen environment, and select 'open with Jupyter Notebook'.

Environments in Anaconda Navigator to run Jupyter from the selected environment

Handling Enter Key in Vue.js

In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:

https://vuejs.org/v2/guide/events.html#Key-Modifiers

I leave a very simple example:

_x000D_
_x000D_
var vm = new Vue({_x000D_
  el: '#app',_x000D_
  data: {msg: ''},_x000D_
  methods: {_x000D_
    onEnter: function() {_x000D_
       this.msg = 'on enter event';_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/vue"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input v-on:keyup.enter="onEnter" />_x000D_
  <h1>{{ msg }}</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good luck

Powershell command to hide user from exchange address lists

"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."

This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.

Scroll part of content in fixed position container

Actually this is better way to do that. If height: 100% is used, the content goes off the border, but when it is 95% everything is in order:

div#scrollable {
    overflow-y: scroll;
    height: 95%;
}

Use jQuery to navigate away from page

Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!

If you're asking how to click a link via jQuery then assuming you have markup which looks like:

<a id="my-link" href="/relative/path.html">Click Me!</a>

You could click() it by executing:

$('#my-link').click();

How to create a css rule for all elements except one class?

The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.

How do you find what version of libstdc++ library is installed on your linux machine?

The mechanism I tend to use is a combination of readelf -V to dump the .gnu.version information from libstdc++, and then a lookup table that matches the largest GLIBCXX_ value extracted.

readelf -sV /usr/lib/libstdc++.so.6 | sed -n 's/.*@@GLIBCXX_//p' | sort -u -V | tail -1

if your version of sort is too old to have the -V option (which sorts by version number) then you can use:

tr '.' ' ' | sort -nu -t ' ' -k 1 -k 2 -k 3 -k 4 | tr ' ' '.'

instead of the sort -u -V, to sort by up to 4 version digits.

In general, matching the ABI version should be good enough.

If you're trying to track down the libstdc++.so.<VERSION>, though, you can use a little bash like:

file=/usr/lib/libstdc++.so.6
while [ -h $file ]; do file=$(ls -l $file | sed -n 's/.*-> //p'); done
echo ${file#*.so.}

so for my system this yielded 6.0.10.

If, however, you're trying to get a binary that was compiled on systemX to work on systemY, then these sorts of things will only get you so far. In those cases, carrying along a copy of the libstdc++.so that was used for the application, and then having a run script that does an:

export LD_LIBRARY_PATH=<directory of stashed libstdc++.so>
exec application.bin "$@"

generally works around the issue of the .so that is on the box being incompatible with the version from the application. For more extreme differences in environment, I tend to just add all the dependent libraries until the application works properly. This is the linux equivalent of working around what, for windows, would be considered dll hell.

How to prevent scanf causing a buffer overflow in C?

In their book The Practice of Programming (which is well worth reading), Kernighan and Pike discuss this problem, and they solve it by using snprintf() to create the string with the correct buffer size for passing to the scanf() family of functions. In effect:

int scanner(const char *data, char *buffer, size_t buflen)
{
    char format[32];
    if (buflen == 0)
        return 0;
    snprintf(format, sizeof(format), "%%%ds", (int)(buflen-1));
    return sscanf(data, format, buffer);
}

Note, this still limits the input to the size provided as 'buffer'. If you need more space, then you have to do memory allocation, or use a non-standard library function that does the memory allocation for you.


Note that the POSIX 2008 (2013) version of the scanf() family of functions supports a format modifier m (an assignment-allocation character) for string inputs (%s, %c, %[). Instead of taking a char * argument, it takes a char ** argument, and it allocates the necessary space for the value it reads:

char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
    printf("String is: <<%s>>\n", buffer);
    free(buffer);
}

If the sscanf() function fails to satisfy all the conversion specifications, then all the memory it allocated for %ms-like conversions is freed before the function returns.

Setting the selected attribute on a select list using jQuery

You can use pure DOM. See http://www.w3schools.com/htmldom/prop_select_selectedindex.asp

document.getElementById('dropdown').selectedIndex = 1;

but jQuery can help:

$('#dropdown').selectedIndex = 1;

Fastest way to compute entropy in Python

With the data as a pd.Series and scipy.stats, calculating the entropy of a given quantity is pretty straightforward:

import pandas as pd
import scipy.stats

def ent(data):
    """Calculates entropy of the passed `pd.Series`
    """
    p_data = data.value_counts()           # counts occurrence of each value
    entropy = scipy.stats.entropy(p_data)  # get entropy from counts
    return entropy

Note: scipy.stats will normalize the provided data, so this doesn't need to be done explicitly, i.e. passing an array of counts works fine.

Java SSLException: hostname in certificate didn't match

Updating the java version from 1.8.0_40 to 1.8.0_181 resolved the issue.

Select Specific Columns from Spark DataFrame

Problem was to select columns of on dataframe after joining with other dataframe.

I tried below and select the columns of salaryDf from the joined dataframe.

Hope this will help

        val empDf=spark.read.option("header","true").csv("/data/tech.txt")

        val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")

        val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and  empDf.col("last") === salaryDf.col("last"))

      //**below will select the colums of salaryDf only**

     val finalDF=joinData.select(salaryDf.columns map  salaryDf.col:_*)

//same way we can select the columns of empDf
joinData.select(empDf.columns map  empDf.col:_*)

How can you search Google Programmatically Java API

Some facts:

  1. Google offers a public search webservice API which returns JSON: http://ajax.googleapis.com/ajax/services/search/web. Documentation here

  2. Java offers java.net.URL and java.net.URLConnection to fire and handle HTTP requests.

  3. JSON can in Java be converted to a fullworthy Javabean object using an arbitrary Java JSON API. One of the best is Google Gson.

Now do the math:

public static void main(String[] args) throws Exception {
    String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    String search = "stackoverflow";
    String charset = "UTF-8";
    
    URL url = new URL(google + URLEncoder.encode(search, charset));
    Reader reader = new InputStreamReader(url.openStream(), charset);
    GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
    
    // Show title and URL of 1st result.
    System.out.println(results.getResponseData().getResults().get(0).getTitle());
    System.out.println(results.getResponseData().getResults().get(0).getUrl());
}

With this Javabean class representing the most important JSON data as returned by Google (it actually returns more data, but it's left up to you as an exercise to expand this Javabean code accordingly):

public class GoogleResults {

    private ResponseData responseData;
    public ResponseData getResponseData() { return responseData; }
    public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
    public String toString() { return "ResponseData[" + responseData + "]"; }

    static class ResponseData {
        private List<Result> results;
        public List<Result> getResults() { return results; }
        public void setResults(List<Result> results) { this.results = results; }
        public String toString() { return "Results[" + results + "]"; }
    }

    static class Result {
        private String url;
        private String title;
        public String getUrl() { return url; }
        public String getTitle() { return title; }
        public void setUrl(String url) { this.url = url; }
        public void setTitle(String title) { this.title = title; }
        public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
    }

}

###See also:


Update since November 2010 (2 months after the above answer), the public search webservice has become deprecated (and the last day on which the service was offered was September 29, 2014). Your best bet is now querying http://www.google.com/search directly along with a honest user agent and then parse the result using a HTML parser. If you omit the user agent, then you get a 403 back. If you're lying in the user agent and simulate a web browser (e.g. Chrome or Firefox), then you get a way much larger HTML response back which is a waste of bandwidth and performance.

Here's a kickoff example using Jsoup as HTML parser:

String google = "http://www.google.com/search?q=";
String search = "stackoverflow";
String charset = "UTF-8";
String userAgent = "ExampleBot 1.0 (+http://example.com/bot)"; // Change this to your company's name and bot homepage!

Elements links = Jsoup.connect(google + URLEncoder.encode(search, charset)).userAgent(userAgent).get().select(".g>.r>a");

for (Element link : links) {
    String title = link.text();
    String url = link.absUrl("href"); // Google returns URLs in format "http://www.google.com/url?q=<url>&sa=U&ei=<someKey>".
    url = URLDecoder.decode(url.substring(url.indexOf('=') + 1, url.indexOf('&')), "UTF-8");
    
    if (!url.startsWith("http")) {
        continue; // Ads/news/etc.
    }
    
    System.out.println("Title: " + title);
    System.out.println("URL: " + url);
}

PHP filesize MB/KB conversion

Here is a simple function to convert Bytes to KB, MB, GB, TB :

# Size in Bytes
$size = 14903511;
# Call this function to convert bytes to KB/MB/GB/TB
echo convertToReadableSize($size);
# Output => 14.2 MB

function convertToReadableSize($size){
  $base = log($size) / log(1024);
  $suffix = array("", "KB", "MB", "GB", "TB");
  $f_base = floor($base);
  return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}

PHP 7 RC3: How to install missing MySQL PDO

Since eggyal didn't provided his comment as answer after he gave right advice in a comment - i am posting it here: In my case I had to install module php-mysql. See comments under the question for details.

pg_config executable not found

You can install pre-compiled binaries on any platform with pip or conda:

python -m pip install psycopg2-binary

or

conda install psycopg2

Please be advised that the psycopg2-binary pypi page recommends building from source in production:

The binary package is a practical choice for development and testing but in production it is advised to use the package built from sources

To use the package built from sources, use python -m pip install psycopg2. That process will require several dependencies (documentation) (emphasis mine):

  • A C compiler.
  • The Python header files. They are usually installed in a package such as python-dev. A message such as error: Python.h: No such file or directory is an indication that the Python headers are missing.
  • The libpq header files. They are usually installed in a package such as libpq-dev. If you get an error: libpq-fe.h: No such file or directory you are missing them.
  • The pg_config program: it is usually installed by the libpq-dev package but sometimes it is not in a PATH directory. Having it in the PATH greatly streamlines the installation, so try running pg_config --version: if it returns an error or an unexpected version number then locate the directory containing the pg_config shipped with the right libpq version (usually /usr/lib/postgresql/X.Y/bin/) and add it to the PATH:
$ export PATH=/usr/lib/postgresql/X.Y/bin/:$PATH

You only need pg_config to compile psycopg2, not for its regular usage.

Once everything is in place it’s just a matter of running the standard:

$ pip install psycopg2

or, from the directory containing the source code:

$ python setup.py build
$ python setup.py install

How do I use StringUtils in Java?

StringUtils is a utility class from Apache commons-lang (many libraries have it but this is the most common library). You need to download the jar and add it to your applications classpath.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

In my case it was due to 'lower_case_table_names' parameter.

The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.

This is fixed by reverting back the lower case parameter changes to the previous state.

Subprocess changing directory

If you need to change directory, run a command and get the std output as well:

import os
import logging as log
from subprocess import check_output, CalledProcessError, STDOUT
log.basicConfig(level=log.DEBUG)

def cmd_std_output(cd_dir_path, cmd):
    cmd_to_list = cmd.split(" ")
    try:
        if cd_dir_path:
            os.chdir(os.path.abspath(cd_dir_path))
        output = check_output(cmd_to_list, stderr=STDOUT).decode()
        return output
    except CalledProcessError as e:
        log.error('e: {}'.format(e))
def get_last_commit_cc_cluster():
    cd_dir_path = "/repos/cc_manager/cc_cluster"
    cmd = "git log --name-status HEAD^..HEAD --date=iso"
    result = cmd_std_output(cd_dir_path, cmd)
    return result

log.debug("Output: {}".format(get_last_commit_cc_cluster()))

Output: "commit 3b3daaaaaaaa2bb0fc4f1953af149fa3921e\nAuthor: user1<[email protected]>\nDate:   2020-04-23 09:58:49 +0200\n\n

Disable browsers vertical and horizontal scrollbars

In modern versions of IE (IE10 and above), scrollbars can be hidden using the -ms-overflow-style property.

html {
     -ms-overflow-style: none;
}

In Chrome, scrollbars can be styled:

::-webkit-scrollbar {
    display: none;
}

This is very useful if you want to use the 'default' body scrolling in a web application, which is considerably faster than overflow-y: scroll.

Select arrow style change

Working with just one class:

select {
    width: 268px;
    padding: 5px;
    font-size: 16px;
    line-height: 1;
    border: 0;
    border-radius: 5px;
    height: 34px;
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
    -webkit-appearance: none;
    background-position-x: 244px;
}

http://jsfiddle.net/qhCsJ/4120/

HTML radio buttons allowing multiple selections

All radio buttons must have the same name attribute added.

How to set header and options in axios?

I have face this issue in post request. I have changed like this in axios header. It works fine.

axios.post('http://localhost/M-Experience/resources/GETrends.php',
      {
        firstName: this.name
      },
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

Find value in an array

This answer is for everyone that realizes the accepted answer does not address the question as it currently written.

The question asks how to find a value in an array. The accepted answer shows how to check whether a value exists in an array.

There is already an example using index, so I am providing an example using the select method.

1.9.3-p327 :012 > x = [1,2,3,4,5]
  => [1, 2, 3, 4, 5] 
1.9.3-p327 :013 > x.select {|y| y == 1}
  => [1]

How do you format code on save in VS Code

No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.

  1. Open Settings by pressing [Cmd+,] in Mac or using the below screenshot.

VS Code - Open Settings Command Image

  1. Type 'format' in the search box and enable the option 'Format On Save'.

enter image description here

You are done. Thank you.

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

function isEmpty(obj) {
    if (typeof obj == 'number') return false;
    else if (typeof obj == 'string') return obj.length == 0;
    else if (Array.isArray(obj)) return obj.length == 0;
    else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
    else if (typeof obj == 'boolean') return false;
    else return !obj;
}

In ES6 with trim to handle whitespace strings:

const isEmpty = value => {
    if (typeof value === 'number') return false
    else if (typeof value === 'string') return value.trim().length === 0
    else if (Array.isArray(value)) return value.length === 0
    else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
    else if (typeof value === 'boolean') return false
    else return !value
}

AES vs Blowfish for file encryption

Probably AES. Blowfish was the direct predecessor to Twofish. Twofish was Bruce Schneier's entry into the competition that produced AES. It was judged as inferior to an entry named Rijndael, which was what became AES.

Interesting aside: at one point in the competition, all the entrants were asked to give their opinion of how the ciphers ranked. It's probably no surprise that each team picked its own entry as the best -- but every other team picked Rijndael as the second best.

That said, there are some basic differences in the basic goals of Blowfish vs. AES that can (arguably) favor Blowfish in terms of absolute security. In particular, Blowfish attempts to make a brute-force (key-exhaustion) attack difficult by making the initial key setup a fairly slow operation. For a normal user, this is of little consequence (it's still less than a millisecond) but if you're trying out millions of keys per second to break it, the difference is quite substantial.

In the end, I don't see that as a major advantage, however. I'd generally recommend AES. My next choices would probably be Serpent, MARS and Twofish in that order. Blowfish would come somewhere after those (though there are a couple of others that I'd probably recommend ahead of Blowfish).

Html.EditorFor Set Default Value

Shove it in the ViewBag:

Controller:

ViewBag.ProductId = 1;

View:

@Html.TextBoxFor(c => c.Propertyname, new {@Value = ViewBag.ProductId})

Get cart item name, quantity all details woocommerce

Try this :

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id()); 
            echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
        } 
?>

To get Product Image and Regular & Sale Price:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            //product image
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )

            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
            /*Regular Price and Sale Price*/
            echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
            echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
        }
?>

Why doesn't Mockito mock static methods?

I seriously do think that it is code smell if you need to mock static methods, too.

  • Static methods to access common functionality? -> Use a singleton instance and inject that
  • Third party code? -> Wrap it into your own interface/delegate (and if necessary make it a singleton, too)

The only time this seems overkill to me, is libs like Guava, but you shouldn't need to mock this kind anyway cause it's part of the logic... (stuff like Iterables.transform(..))
That way your own code stays clean, you can mock out all your dependencies in a clean way, and you have an anti corruption layer against external dependencies. I've seen PowerMock in practice and all the classes we needed it for were poorly designed. Also the integration of PowerMock at times caused serious problems
(e.g. https://code.google.com/p/powermock/issues/detail?id=355)

PS: Same holds for private methods, too. I don't think tests should know about the details of private methods. If a class is so complex that it tempts to mock out private methods, it's probably a sign to split up that class...

ObjectiveC Parse Integer from String

NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];

_returnedArguments is an array of NSStrings which the UITextField text property is expecting. No need to convert.

Syntax error:

[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];

If your _appDelegate has a passwordField property, then you can set the text using the following

[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];

How to redirect to a 404 in Rails?

<%= render file: 'public/404', status: 404, formats: [:html] %>

just add this to the page you want to render to the 404 error page and you are done.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

Show/hide div if checkbox selected

<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox

<div id="div1" style="display:none;">NOTICE</div>

  <script type="text/javascript">
<!--
   function showMe (box) {
    var chboxs = document.getElementById("div1").style.display;
    var vis = "none";
        if(chboxs=="none"){
         vis = "block"; }
        if(chboxs=="block"){
         vis = "none"; }
    document.getElementById(box).style.display = vis;
}
  //-->
</script>

How to get the date 7 days earlier date from current date in Java

You can use this to continue using the type Date and a more legible code, if you preffer:

import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);

OpenSSL and error in reading openssl.conf file

On Windows you can also set the environment property OPENSSL_CONF. For example from the commandline you can type:

set OPENSSL_CONF=c:/libs/openssl-0.9.8k/openssl.cnf

to validate it you can type:

echo %OPENSSL_CONF%

You can also set it as part of the computer's environmental variables so all users and services have it available by default. See, for example, Environment variables in Windows NT and How To Manage Environment Variables in Windows XP.

Now you can run openssl commands without having to pass the config location parameter.

How to change the button text of <input type="file" />?

I did it like this for my project:

_x000D_
_x000D_
.btn-outlined.btn-primary {_x000D_
  color: #000;_x000D_
}_x000D_
.btn-outlined.btn-primary:active, .btn-outlined.btn-positive:active, .btn-outlined.btn-negative:active {_x000D_
  color:#000;_x000D_
}_x000D_
.btn-block {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  padding: 15px 0;_x000D_
  margin-bottom: 10px;_x000D_
  font-size: 18px;_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  text-align: center;_x000D_
}
_x000D_
<label for="fileUpload" class="btn btn-primary btn-block btn-outlined">Your text</label>_x000D_
<input type="file" id="fileUpload"style="display: none;">
_x000D_
_x000D_
_x000D_

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

The application may be doing too much work on its main thread

This is normal if you are using async/await functionalities in your application.

List names of all tables in a SQL Server 2012 schema

SELECT t1.name AS [Schema], t2.name AS [Table]
FROM sys.schemas t1
INNER JOIN sys.tables t2
ON t2.schema_id = t1.schema_id
ORDER BY t1.name,t2.name

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

SQL SELECT WHERE field contains words

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = ' '



CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL

        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END

SELECT ColumnName, ColumnValue FROM #Results

DROP TABLE #Results

Java: Finding the highest value in an array

void FindMax()
{
    int lessonNum;

    System.out.print("Enter your lesson numbers : ");
    lessonNum = input.nextInt();
    int[] numbers = new int[lessonNum];
    for (int i = 0; i < numbers.length; i++)
    {
        System.out.print("Please enter " + (i + 1) + " number : ");
        numbers[i] = input.nextInt();
    }
    double max = numbers[0];
    for (int i = 1; i < numbers.length; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
    }
    System.out.println("Maximum number is : " + max);
}

raw_input function in Python

The raw_input() function reads a line from input (i.e. the user) and returns a string

Python v3.x as raw_input() was renamed to input()

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

Ref: Docs Python 3

git: can't push (unpacker error) related to permission issues

A simpler way to do this is to add a post-receive script which runs the chmod command after every push to the 'hub' repo on the server. Add the following line to hooks/post-receive inside your git folder on the server:

chmod -Rf u+w /path/to/git/repo/objects

How to reset a form using jQuery with .reset() method

A reset button doesn't need any script at all (or name or id):

<input type="reset">

and you're done. But if you really must use script, note that every form control has a form property that references the form it's in, so you could do:

<input type="button" onclick="this.form.reset();">

But a reset button is a far better choice.

How to get only the last part of a path in Python?

str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

Slack URL to open a channel from browser

You can use

slack://

in order to open the Slack desktop application. For example, on mac, I've run:

open slack://

from the terminal and it opens the Mac desktop Slack application. Still, I didn't figure out the URL that should be used for opening a certain team, channel or message.

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

Make sure you're adding these dependencies in android/app/build.gradle, not android/build.gradle

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
  $validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
  if(!$validUser) $errorMsg = "Invalid username or password.";
  else $_SESSION["login"] = true;
}
if($validUser) {
   header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>Login</title>
</head>
<body>
  <form name="input" action="" method="post">
    <label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
    <label for="password">Password:</label><input type="password" value="" id="password" name="password" />
    <div class="error"><?= $errorMsg ?></div>
    <input type="submit" value="Home" name="sub" />
  </form>
</body>
</html>

Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well. Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.

Indent starting from the second line of a paragraph with CSS

Make left-margin: 2em or so will push the whole text including first line to right 2em. Than add text-indent (applicable to first line) as -2em or so.. This brings first line back to start without margin. I tried it for list tags

<style>
    ul li{
      margin-left: 2em;
      text-indent: -2em;
    }
</style>

How is "mvn clean install" different from "mvn install"?

clean is its own build lifecycle phase (which can be thought of as an action or task) in Maven. mvn clean install tells Maven to do the clean phase in each module before running the install phase for each module.

What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.

Fixed positioned div within a relative parent div

A simple thing you can do is position your fixed DIV relative to the rest of your page with % values.

Check out this jsfiddle here where the fixed DIV is a sidebar.

div#wrapper {
    margin: auto;
    width: 80%;
}

div#main {
    width: 60%;
}

div#sidebar {
    position: fixed;
    width: 30%;
    left: 60%;
}

And a brief picture below describing the layout above:

example layout

Get timezone from users browser using moment(timezone).js

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true

Bootstrap select dropdown list placeholder

Here's another way to do it

<select name="GROUPINGS[xxxxxx]" style="width: 60%;" required>
    <option value="">Choose Platform</option>
<option value="iOS">iOS</option>
    <option value="Android">Android</option>
    <option value="Windows">Windows</option>
</select>

"Choose Platform" becomes the placeholder and the 'required' property ensures that the user has to select one of the options.

Very useful, when you don't want to user field names or Labels.

Creating SolidColorBrush from hex color value

I've been using:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));

jQuery - Getting the text value of a table cell in the same row as a clicked element

You want .children() instead (documentation here):

$(this).closest('tr').children('td.two').text();

How can I escape square brackets in a LIKE clause?

Let's say you want to match the literal its[brac]et.

You don't need to escape the ] as it has special meaning only when it is paired with [.

Therefore escaping [ suffices to solve the problem. You can escape [ by replacing it with [[].

Why do I get "'property cannot be assigned" when sending an SMTP email?

If you want to have your email and password not appear in your code and want your company email client server to use your windows credentials use below.

client.Credentials = CredentialCache.DefaultNetworkCredentials;

Source

Accessing a Dictionary.Keys Key through a numeric index

I don't know if this would work because I'm pretty sure that the keys aren't stored in the order they are added, but you could cast the KeysCollection to a List and then get the last key in the list... but it would be worth having a look.

The only other thing I can think of is to store the keys in a lookup list and add the keys to the list before you add them to the dictionary... it's not pretty tho.

Oracle SQL, concatenate multiple columns + add text

Below query works for me @Oracle 10G ----

select PHONE, CONTACT, (ADDR1 ||  '-' || ADDR2 || '-' || ADDR3) as Address
from CUSTOMER_DETAILS
where Code='341'; 

O/P -

1111 [email protected] 4th street-capetown-sa

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

Converting JSON to XLS/CSV in Java

A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.

Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

You can wrap the inputs in col-* classes

<form name="registration_form" id="registration_form" class="form-horizontal">
     <div class="form-group">
           <div class="col-sm-6">
             <label for="firstname" class="sr-only"></label>
             <input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">
           </div>       
           <div class="col-sm-6">
             <label for="lastname" class="sr-only"></label>
             <input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">
           </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
          <label for="username" class="sr-only"></label>
          <input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">
        </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
        <label for="password" class="sr-only"></label>
        <input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">
        </div>
    </div><!--/form-group-->
 </form>

http://bootply.com/127825

Objects inside objects in javascript

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};

then:

pause_menu.pause_button.someProperty //evaluates to "prop1"

etc etc.

Is the size of C "int" 2 bytes or 4 bytes?

Is the size of C “int” 2 bytes or 4 bytes?

Does an Integer variable in C occupy 2 bytes or 4 bytes?

C allows "bytes" to be something other than 8 bits per "byte".

CHAR_BIT number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1

A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT rather than 8. The size of an int in bits in C is sizeof(int) * CHAR_BIT.

#include <limits.h>
printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);

What are the factors that it depends on?

The int bit size is commonly 32 or 16 bits. C specified minimum ranges:

minimum value for an object of type int INT_MIN -32767
maximum value for an object of type int INT_MAX +32767
C11dr §5.2.4.2.1 1

The minimum range for int forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int bit sizes.

The computer's processor and architecture drive the int bit size selection.

Yet even with 64-bit processors, the compiler's int size may be 32-bit for compatibility reasons as large code bases depend on int being 32-bit (or 32/16).

How to write JUnit test with Spring Autowire?

I've done it with two annotations for test class: @RunWith(SpringRunner.class) and @SpringBootTest. Example:

@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {

    @Autowired
    private ProtocolTransactionService protocolTransactionService;
}

@SpringBootTest loads the whole context, which was OK in my case.

Importing a CSV file into a sqlite3 database table using Python

With this you can do joins on CSVs as well:

import sqlite3
import os
import pandas as pd
from typing import List

class CSVDriver:
    def __init__(self, table_dir_path: str):
        self.table_dir_path = table_dir_path  # where tables (ie. csv files) are located
        self._con = None

    @property
    def con(self) -> sqlite3.Connection:
        """Make a singleton connection to an in-memory SQLite database"""
        if not self._con:
            self._con = sqlite3.connect(":memory:")
        return self._con
    
    def _exists(self, table: str) -> bool:
        query = """
        SELECT name
        FROM sqlite_master 
        WHERE type ='table'
        AND name NOT LIKE 'sqlite_%';
        """
        tables = self.con.execute(query).fetchall()
        return table in tables

    def _load_table_to_mem(self, table: str, sep: str = None) -> None:
        """
        Load a CSV into an in-memory SQLite database
        sep is set to None in order to force pandas to auto-detect the delimiter
        """
        if self._exists(table):
            return
        file_name = table + ".csv"
        path = os.path.join(self.table_dir_path, file_name)
        if not os.path.exists(path):
            raise ValueError(f"CSV table {table} does not exist in {self.table_dir_path}")
        df = pd.read_csv(path, sep=sep, engine="python")  # set engine to python to skip pandas' warning
        df.to_sql(table, self.con, if_exists='replace', index=False, chunksize=10000)

    def query(self, query: str) -> List[tuple]:
        """
        Run an SQL query on CSV file(s). 
        Tables are loaded from table_dir_path
        """
        tables = extract_tables(query)
        for table in tables:
            self._load_table_to_mem(table)
        cursor = self.con.cursor()
        cursor.execute(query)
        records = cursor.fetchall()
        return records

extract_tables():

import sqlparse
from sqlparse.sql import IdentifierList, Identifier,  Function
from sqlparse.tokens import Keyword, DML
from collections import namedtuple
import itertools

class Reference(namedtuple('Reference', ['schema', 'name', 'alias', 'is_function'])):
    __slots__ = ()

    def has_alias(self):
        return self.alias is not None

    @property
    def is_query_alias(self):
        return self.name is None and self.alias is not None

    @property
    def is_table_alias(self):
        return self.name is not None and self.alias is not None and not self.is_function

    @property
    def full_name(self):
        if self.schema is None:
            return self.name
        else:
            return self.schema + '.' + self.name

def _is_subselect(parsed):
    if not parsed.is_group:
        return False
    for item in parsed.tokens:
        if item.ttype is DML and item.value.upper() in ('SELECT', 'INSERT',
                                                        'UPDATE', 'CREATE', 'DELETE'):
            return True
    return False


def _identifier_is_function(identifier):
    return any(isinstance(t, Function) for t in identifier.tokens)


def _extract_from_part(parsed):
    tbl_prefix_seen = False
    for item in parsed.tokens:
        if item.is_group:
            for x in _extract_from_part(item):
                yield x
        if tbl_prefix_seen:
            if _is_subselect(item):
                for x in _extract_from_part(item):
                    yield x
            # An incomplete nested select won't be recognized correctly as a
            # sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes
            # the second FROM to trigger this elif condition resulting in a
            # StopIteration. So we need to ignore the keyword if the keyword
            # FROM.
            # Also 'SELECT * FROM abc JOIN def' will trigger this elif
            # condition. So we need to ignore the keyword JOIN and its variants
            # INNER JOIN, FULL OUTER JOIN, etc.
            elif item.ttype is Keyword and (
                    not item.value.upper() == 'FROM') and (
                    not item.value.upper().endswith('JOIN')):
                tbl_prefix_seen = False
            else:
                yield item
        elif item.ttype is Keyword or item.ttype is Keyword.DML:
            item_val = item.value.upper()
            if (item_val in ('COPY', 'FROM', 'INTO', 'UPDATE', 'TABLE') or
                    item_val.endswith('JOIN')):
                tbl_prefix_seen = True
        # 'SELECT a, FROM abc' will detect FROM as part of the column list.
        # So this check here is necessary.
        elif isinstance(item, IdentifierList):
            for identifier in item.get_identifiers():
                if (identifier.ttype is Keyword and
                        identifier.value.upper() == 'FROM'):
                    tbl_prefix_seen = True
                    break


def _extract_table_identifiers(token_stream):
    for item in token_stream:
        if isinstance(item, IdentifierList):
            for ident in item.get_identifiers():
                try:
                    alias = ident.get_alias()
                    schema_name = ident.get_parent_name()
                    real_name = ident.get_real_name()
                except AttributeError:
                    continue
                if real_name:
                    yield Reference(schema_name, real_name,
                                    alias, _identifier_is_function(ident))
        elif isinstance(item, Identifier):
            yield Reference(item.get_parent_name(), item.get_real_name(),
                            item.get_alias(), _identifier_is_function(item))
        elif isinstance(item, Function):
            yield Reference(item.get_parent_name(), item.get_real_name(),
                            item.get_alias(), _identifier_is_function(item))


def extract_tables(sql):
    # let's handle multiple statements in one sql string
    extracted_tables = []
    statements = list(sqlparse.parse(sql))
    for statement in statements:
        stream = _extract_from_part(statement)
        extracted_tables.append([ref.name for ref in _extract_table_identifiers(stream)])
    return list(itertools.chain(*extracted_tables))

Example (assuming account.csv and tojoin.csv exist in /path/to/files):

db_path = r"/path/to/files"
driver = CSVDriver(db_path)
query = """
SELECT tojoin.col_to_join 
FROM account
LEFT JOIN tojoin
ON account.a = tojoin.a
"""
driver.query(query)

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Execute a file with arguments in Python shell

If you want to run the scripts in parallel and give them different arguments you can do like below.

import os
os.system("python script.py arg1 arg2 & python script.py arg11 arg22")

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

HTTP error 403 in Python 3 Web Scraping

Definitely it's blocking because of your use of urllib based on the user agent. This same thing is happening to me with OfferUp. You can create a new class called AppURLopener which overrides the user-agent with Mozilla.

import urllib.request

class AppURLopener(urllib.request.FancyURLopener):
    version = "Mozilla/5.0"

opener = AppURLopener()
response = opener.open('http://httpbin.org/user-agent')

Source

.htaccess redirect all pages to new domain

This is a bug in older versions of apache (and thus mod_rewrite) where the path prefix was appended to the rewritten path if it got changed. See here

I think it was fixed in apache2 V2.2.12, there is a special flag you need to use which i will add here when i find it, (i think it was NP for No Path)

RewriteRule ^(.*)$ http://newdomain.com/ [??]

How to create a sticky left sidebar menu using bootstrap 3?

Bootstrap 3

Here is a working left sidebar example:

http://bootply.com/90936 (similar to the Bootstrap docs)

The trick is using the affix component along with some CSS to position it:

  #sidebar.affix-top {
    position: static;
    margin-top:30px;
    width:228px;
  }

  #sidebar.affix {
    position: fixed;
    top:70px;
    width:228px;
  }

EDIT- Another example with footer and affix-bottom


Bootstrap 4

The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top class is explained in this answer.

Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Following is the MySQL syntax:

UPDATE table1 
INNER JOIN table2 ON table1.field1 = table2.field2
SET table1.field3 = table2.field4 
WHERE ...... ;

http://geekswithblogs.net/faizanahmad/archive/2009/01/05/join-in-sql-update--statement.aspx

'str' object does not support item assignment in Python

The other answers are correct, but you can, of course, do something like:

>>> str1 = "mystring"
>>> list1 = list(str1)
>>> list1[5] = 'u'
>>> str1 = ''.join(list1)
>>> print(str1)
mystrung
>>> type(str1)
<type 'str'>

if you really want to.

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: Date.now() / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2:

db.foo.updateMany( {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2:

db.foo.update( {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2:

db.foo.update( {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

How to access parent Iframe from JavaScript

Also you can set name and ID to equal values

<iframe id="frame1" name="frame1" src="any.html"></iframe>

so you will be able to use next code inside child page

parent.document.getElementById(window.name);

Make Adobe fonts work with CSS3 @font-face in IE9

I wasted a lot of time because of this issue. Finally I found great solution myself. Before I was using .ttf font only. But I added one extra font format .eot that started to work in IE.

I used following code and it worked like charm in all browsers.

@font-face {
font-family: OpenSans;
src: url(assets/fonts/OpenSans/OpenSans-Regular.ttf), 
url(assets/fonts/OpenSans/OpenSans-Regular.eot);
}

@font-face {
font-family: OpenSans Bold;
src: url(assets/fonts/OpenSans/OpenSans-Bold.ttf),
url(assets/fonts/OpenSans/OpenSans-Bold.eot);
}

I hope this will help someone.

How to delete from a text file, all lines that contain a specific string?

There are many other ways to delete lines with specific string besides sed:

AWK

awk '!/pattern/' file > temp && mv temp file

Ruby (1.9+)

ruby -i.bak -ne 'print if not /test/' file

Perl

perl -ni.bak -e "print unless /pattern/" file

Shell (bash 3.2 and later)

while read -r line
do
  [[ ! $line =~ pattern ]] && echo "$line"
done <file > o
mv o file

GNU grep

grep -v "pattern" file > temp && mv temp file

And of course sed (printing the inverse is faster than actual deletion):

sed -n '/pattern/!p' file

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

If you package it as a single jar and it's non web app try to load app context as below.

@SpringBootApplication

ApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class);

Or use below plugin to package as a single jar

             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

you can specify the external configs by using below command to run

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

/http://docs.spring.io/spring-boot/docs/current/reference/htmlboot-features-external-config.html#boot-features-external-config-application-property-files

Note that if you are passing the properties as arguments then don't include @PropertySource("classpath:test.properties") it will override the parameters

How to export table data in MySql Workbench to csv?

MySQL Workbench 6.3.6

Export the SELECT result

  • After you run a SELECT: Query > Export Results...

    Query Export Results

Export table data

  • In the Navigator, right click on the table > Table Data Export Wizard

    Table Data Export

  • All columns and rows are included by default, so click on Next.

  • Select File Path, type, Field Separator (by default it is ;, not ,!!!) and click on Next.

    CSV

  • Click Next > Next > Finish and the file is created in the specified location

What does "collect2: error: ld returned 1 exit status" mean?

The ld returned 1 exit status error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0 means success, and exit status > 0 means errors.

When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld, which first reports the error it found (clrscr reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.

In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.

Adding an onclicklistener to listview (android)

If your Activity extends ListActivity, you can simply override the OnListItemClick() method like so:

/** {@inheritDoc} */
@Override  
protected void onListItemClick(ListView l, View v, int pos, long id) {  
    super.onListItemClick(l, v, pos, id);

    // TODO : Logic
}  

With Spring can I make an optional path variable?

Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.

What is a callback function?

I believe this "callback" jargon has been mistakenly used in a lot of places. My definition would be something like:

A callback function is a function that you pass to someone and let them call it at some point of time.

I think people just read the first sentence of the wiki definition:

a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code.

I've been working with lots of APIs, see various of bad examples. Many people tend to name a function pointer (a reference to executable code) or anonymous functions(a piece of executable code) "callback", if they are just functions why do you need another name for this?

Actually only the second sentence in wiki definition reveals the differences between a callback function and a normal function:

This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

so the difference is who you are going to pass the function and how your passed in function is going to be called. If you just define a function and pass it to another function and called it directly in that function body, don't call it a callback. The definition says your passed in function is gonna be called by "lower-level" function.

I hope people can stop using this word in ambiguous context, it can't help people to understand better only worse.

Splitting dataframe into multiple dataframes

In [28]: df = DataFrame(np.random.randn(1000000,10))

In [29]: df
Out[29]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000000 entries, 0 to 999999
Data columns (total 10 columns):
0    1000000  non-null values
1    1000000  non-null values
2    1000000  non-null values
3    1000000  non-null values
4    1000000  non-null values
5    1000000  non-null values
6    1000000  non-null values
7    1000000  non-null values
8    1000000  non-null values
9    1000000  non-null values
dtypes: float64(10)

In [30]: frames = [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]

In [31]: %timeit [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]
1 loops, best of 3: 849 ms per loop

In [32]: len(frames)
Out[32]: 16667

Here's a groupby way (and you could do an arbitrary apply rather than sum)

In [9]: g = df.groupby(lambda x: x/60)

In [8]: g.sum()    

Out[8]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 16667 entries, 0 to 16666
Data columns (total 10 columns):
0    16667  non-null values
1    16667  non-null values
2    16667  non-null values
3    16667  non-null values
4    16667  non-null values
5    16667  non-null values
6    16667  non-null values
7    16667  non-null values
8    16667  non-null values
9    16667  non-null values
dtypes: float64(10)

Sum is cythonized that's why this is so fast

In [10]: %timeit g.sum()
10 loops, best of 3: 27.5 ms per loop

In [11]: %timeit df.groupby(lambda x: x/60)
1 loops, best of 3: 231 ms per loop

CSS3 transition events

Just for fun, don't do this!

$.fn.transitiondone = function () {
  return this.each(function () {
    var $this = $(this);
    setTimeout(function () {
      $this.trigger('transitiondone');
    }, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
  });
};


$('div').on('mousedown', function (e) {
  $(this).addClass('bounce').transitiondone();
});

$('div').on('transitiondone', function () {
  $(this).removeClass('bounce');
});

Couldn't load memtrack module Logcat Error

This error, as you can read on the question linked in comments above, results to be:

"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."

The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:

  • package="com.example.hive" in <manifest> tag,
  • android:name="com.sit.gems.app.GemsApplication" for <application>
  • and android:name="com.sit.gems.activity" in <activity>

As you know, these things do not prevent your app to be displayed. But I think:

the Couldn't load memtrack module error could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.

For better using and with few things, this can be resolved by following these tips:


1. Try an other emulator...

And even a real device! The memtrack module error seems related to your emulator. So change it into Run configuration, don't forget to change the API too.


2. OpenGL error logs

For OpenGl errors, as called unimplemented OpenGL ES API, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java, it might help you):

<uses-feature android:glEsVersion="0x00020000"></uses-feature>  
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />

3. Use the same package

Don't declare different package names to all the tags in Manifest. You should have the same for Manifest, Activities, etc. Something like this looks right:

<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sit.gems.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- don't set a package name in <application> -->
    <application ... >

        <!-- then, declare the activities -->
        <activity
            android:name="com.sit.gems.activity.SplashActivity" ... >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- same package here -->
        <activity
            android:name="com.sit.gems.activity.HomeActivity" ... >
        </activity>
    </application>
</manifest>  

4. Don't get lost with layouts:

You should set another layout for SplashScreenActivity.java because you're not using the TabHost for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:

// inside SplashScreen class
setContentView(R.layout.splash_screen);

// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" 
     android:gravity="center"
     android:text="@string/appname" />  

Avoid using a layout in activities which don't use it.


5. Splash Screen?

Finally, I don't understand clearly the purpose of your SplashScreenActivity. It sets a content view and directly finish. This is useless.

As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity. Therefore, you should do this and don't use the TabHost layout ;):

// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set your splash_screen layout
        setContentView(R.layout.splash_screen);

        // create a new Thread
        new Thread(new Runnable() {
            public void run() {
                try {
                    // sleep during 800ms
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // start HomeActivity
                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                SplashActivity.this.finish();
            }
        }).start();
    }
}  

I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

From ND to 1D arrays

I wanted to see a benchmark result of functions mentioned in answers including unutbu's.

Also want to point out that numpy doc recommend to use arr.reshape(-1) in case view is preferable. (even though ravel is tad faster in the following result)


TL;DR: np.ravel is the most performant (by very small amount).

Benchmark

Functions:

numpy version: '1.18.0'

Execution times on different ndarray sizes

+-------------+----------+-----------+-----------+-------------+
|  function   |   10x10  |  100x100  | 1000x1000 | 10000x10000 |
+-------------+----------+-----------+-----------+-------------+
| ravel       | 0.002073 |  0.002123 |  0.002153 |    0.002077 |
| reshape(-1) | 0.002612 |  0.002635 |  0.002674 |    0.002701 |
| flatten     | 0.000810 |  0.007467 |  0.587538 |  107.321913 |
| flat        | 0.000337 |  0.000255 |  0.000227 |    0.000216 |
+-------------+----------+-----------+-----------+-------------+

Conclusion

ravel and reshape(-1)'s execution time was consistent and independent from ndarray size. However, ravel is tad faster, but reshape provides flexibility in reshaping size. (maybe that's why numpy doc recommend to use it instead. Or there could be some cases where reshape returns view and ravel doesn't).
If you are dealing with large size ndarray, using flatten can cause a performance issue. Recommend not to use it. Unless you need a copy of the data to do something else.

Used code

import timeit
setup = '''
import numpy as np
nd = np.random.randint(10, size=(10, 10))
'''

timeit.timeit('nd = np.reshape(nd, -1)', setup=setup, number=1000)
timeit.timeit('nd = np.ravel(nd)', setup=setup, number=1000)
timeit.timeit('nd = nd.flatten()', setup=setup, number=1000)
timeit.timeit('nd.flat', setup=setup, number=1000)

Rubymine: How to make Git ignore .idea files created by Rubymine

You may use gitignore for advanced gitignore file generation. It's fast, easy and cutting edge tags are automatically generated for you.

Use this link for most of jetbrains softwares (intelij, phpstorm...) jetbrains .gitignore file

[edit]

Below is the generated gitignore file for Jetbrains Softwares, this will prevent you from sharing sensitive informations (passwords, keystores, db passwords...) used by any of Jetbrains software to manage projects.

# Created by https://www.gitignore.io

### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm

*.iml

## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:

# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries

# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml

# Gradle:
# .idea/gradle.xml
# .idea/libraries

# Mongo Explorer plugin:
# .idea/mongoSettings.xml

## File-based project format:
*.ipr
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties

Generated code is also well commented. hope it helps :)

Why aren't python nested functions called closures?

I'd like to offer another simple comparison between python and JS example, if this helps make things clearer.

JS:

function make () {
  var cl = 1;
  function gett () {
    console.log(cl);
  }
  function sett (val) {
    cl = val;
  }
  return [gett, sett]
}

and executing:

a = make(); g = a[0]; s = a[1];
s(2); g(); // 2
s(3); g(); // 3

Python:

def make (): 
  cl = 1
  def gett ():
    print(cl);
  def sett (val):
    cl = val
  return gett, sett

and executing:

g, s = make()
g() #1
s(2); g() #1
s(3); g() #1

Reason: As many others said above, in python, if there is an assignment in the inner scope to a variable with the same name, a new reference in the inner scope is created. Not so with JS, unless you explicitly declare one with the var keyword.

Set System.Drawing.Color values

You could do:

Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components

Parsing string as JSON with single quotes?

var str =  "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);

This solved the problem for me.

Finding the last index of an array

Is this worth mentioning?

var item = new Stack(arr).Pop();

How should I remove all the leading spaces from a string? - swift

Swift 3

You can simply use this method to remove all normal spaces in a string (doesn't consider all types of whitespace):

let myString = " Hello World ! "
let formattedString = myString.replacingOccurrences(of: " ", with: "")

The result will be:

HelloWorld!

Could not install packages due to an EnvironmentError: [Errno 13]

try this command line below for MacOS to check user's permission.

$ sudo python -m pip install --user --upgrade pip

Excel compare two columns and highlight duplicates

I was trying to compare A-B columns and highlight equal text, but usinng the obove fomrulas some text did not match at all. So I used form (VBA macro to compare two columns and color highlight cell differences) codes and I modified few things to adapt it to my application and find any desired column (just by clicking it). In my case, I use large and different numbers of rows on each column. Hope this helps:

Sub ABTextCompare()

Dim Report As Worksheet
Dim i, j, colNum, vMatch As Integer
Dim lastRowA, lastRowB, lastRow, lastColumn As Integer
Dim ColumnUsage As String
Dim colA, colB, colC As String
Dim A, B, C As Variant

Set Report = Excel.ActiveSheet
vMatch = 1

'Select A and B Columns to compare
On Error Resume Next
 Set A = Application.InputBox(Prompt:="Select column to compare", Title:="Column A", Type:=8)
  If A Is Nothing Then Exit Sub
colA = Split(A(1).Address(1, 0), "$")(0)
 Set B = Application.InputBox(Prompt:="Select column being searched", Title:="Column B", Type:=8)
   If A Is Nothing Then Exit Sub
  colB = Split(B(1).Address(1, 0), "$")(0)
 'Select Column to show results
 Set C = Application.InputBox("Select column  to show results", "Results", Type:=8)
    If C Is Nothing Then Exit Sub
  colC = Split(C(1).Address(1, 0), "$")(0)

'Get Last Row
lastRowA = Report.Cells.Find("", Range(colA & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column A
lastRowB = Report.Cells.Find("", Range(colB & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column B

 Application.ScreenUpdating = False
'***************************************************
For i = 2 To lastRowA
      For j = 2 To lastRowB
          If Report.Cells(i, A.Column).Value <> "" Then
              If InStr(1, Report.Cells(j, B.Column).Value, Report.Cells(i, A.Column).Value, vbTextCompare) > 0 Then
                  vMatch = vMatch + 1
                  Report.Cells(i, A.Column).Interior.ColorIndex = 35 'Light green background
                  Range(colC & 1).Value = "Items Found"
                  Report.Cells(i, A.Column).Copy Destination:=Range(colC & vMatch)
                  Exit For
              Else
                  'Do Nothing
              End If
          End If
      Next j
  Next i
If vMatch = 1 Then
    MsgBox Prompt:="No Itmes Found", Buttons:=vbInformation
End If
'***************************************************
Application.ScreenUpdating = True

End Sub

Android emulator not able to access the internet

I had this also and I solved it by creating new android emulator virtual device and chosen Nexus 4 api 27. Before I was creating Pixel device api 28, and it was not working even after recreating device. So I tried totally different configuration and Android Emulator has internet connection as is expected. Other solutions did not work for me but I did no try it all.

How can I align text directly beneath an image?

I am not an expert in HTML but here is what worked for me:

<div class="img-with-text-below">
    <img src="your-image.jpg" alt="alt-text" />
    <p><center>Your text</center></p>
</div>

When to use window.opener / window.parent / window.top

I think you need to add some context to your question. However, basic information about these things can be found here:

window.opener https://developer.mozilla.org/en-US/docs/Web/API/Window.opener

I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.

window.parent https://developer.mozilla.org/en-US/docs/Web/API/Window.parent

I've used this mostly when working with IFrames that need to communicate with the window object that contains them.

window.top https://developer.mozilla.org/en-US/docs/Web/API/Window.top

This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.

If you add some more detail to your question, I can supply other more relevant examples.

UPDATE: There are a few ways you can handle your situation.
You have the following structure:

  • Main Window
    • Dialog 1
      • Dialog 2 Opened By Dialog 1

When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.

So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:

childwindow.appMainWindow = window.opener

After making the assignment above, close dialog 1. Then from the code running inside dialog2, you should be able to use window.appMainWindow to reference the main window, window object.

Hope this helps.

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

Vue.js redirection to another page

<div id="app">
   <a :href="path" />Link</a>
</div>

<script>
      new Vue({
        el: '#app',
        data: {
          path: 'https://www.google.com/'
        }
      });
</script> enter code here

How do I get the path of the assembly the code is in?

This should work:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
Assembly asm = Assembly.GetCallingAssembly();
String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);

string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");

I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).

Automatically run %matplotlib inline in IPython Notebook

The setting was disabled in Jupyter 5.X and higher by adding below code

pylab = Unicode('disabled', config=True,
    help=_("""
    DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
    """)
)

@observe('pylab')
def _update_pylab(self, change):
    """when --pylab is specified, display a warning and exit"""
    if change['new'] != 'warn':
        backend = ' %s' % change['new']
    else:
        backend = ''
    self.log.error(_("Support for specifying --pylab on the command line has been removed."))
    self.log.error(
        _("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
    )
    self.exit(1)

And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels and you can find kernel for your project by running below command

$ jupyter kernelspec list
Available kernels:
  python3    /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3

This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json file, I see something like below

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
 ],
 "display_name": "Python 3",
 "language": "python"
}

So you can see what command is executed to launch the kernel. So if you run the below command

$ python -m ipykernel_launcher --help
IPython: an enhanced interactive Python shell.

Subcommands
-----------

Subcommands are launched as `ipython-kernel cmd [args]`. For information on
using subcommand 'cmd', do: `ipython-kernel cmd -h`.

install
    Install the IPython kernel

Options
-------

Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.

....
--pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Pre-load matplotlib and numpy for interactive use, selecting a particular
    matplotlib backend and loop integration.
--matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Configure matplotlib for interactive use with the default matplotlib
    backend.
...    
To see all available configurables, use `--help-all`

So now if we update our kernel.json file to

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
  "--pylab",
  "inline"
 ],
 "display_name": "Python 3",
 "language": "python"
}

And if I run jupyter notebook the graphs are automatically inline

Auto Inline

Note the below approach also still works, where you create a file on below path

~/.ipython/profile_default/ipython_kernel_config.py

c = get_config()
c.IPKernelApp.matplotlib = 'inline'

But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.

So choose which approach you would like to use based on your requirement

What are the differences between ArrayList and Vector?

As the documentation says, a Vector and an ArrayList are almost equivalent. The difference is that access to a Vector is synchronized, whereas access to an ArrayList is not. What this means is that only one thread can call methods on a Vector at a time, and there's a slight overhead in acquiring the lock; if you use an ArrayList, this isn't the case. Generally, you'll want to use an ArrayList; in the single-threaded case it's a better choice, and in the multi-threaded case, you get better control over locking. Want to allow concurrent reads? Fine. Want to perform one synchronization for a batch of ten writes? Also fine. It does require a little more care on your end, but it's likely what you want. Also note that if you have an ArrayList, you can use the Collections.synchronizedList function to create a synchronized list, thus getting you the equivalent of a Vector.

How to set thymeleaf th:field value from other variable

It has 2 possible solutions:

1) You can set it in the view by javascript... (not recomended)

<input class="form-control"
       type="text"
       id="tbFormControll"
       th:field="*{clientName}"/>

<script type="text/javascript">
        document.getElementById("tbFormControll").value = "default";
</script>

2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.

public class FormControllModel {
    ...
    private String clientName = "default";
    public String getClientName () {
        return clientName;
    }
    public void setClientName (String value) {
        clientName = value;
    }
    ...
}

I hope it helps.

Percentage Height HTML 5/CSS

Sometimes, you may want to conditionally set the height of a div, such as when the entire content is less than the height of the screen. Setting all parent elements to 100% will cut off content when it is longer than the screen size.

So, the way to get around this is to set the min-height:

Continue to let the parent elements automatically adjust their height Then in your main div, subtract the pixel sizes of the header and footer div from 100vh (viewport units). In css, something like:

min-height: calc(100vh - 246px);

100vh is full length of the screen, minus the surrounding divs. By setting min-height and not height, content longer than screen will continue to flow, instead of getting cut off.

Form inside a form, is that alright?

No. HTML explicitly forbids nested forms.

From the HTML 5 draft:

Content model: Flow content, but with no form element descendants.

From the HTML 4.01 Recommendation:

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->

(Note the -(FORM) section).

Prevent a webpage from navigating away using JavaScript

That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.

In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).

A more appropriate error message might be:

window.onbeforeunload = function() {
    return "If you leave this page, you will lose any unsaved changes.";
}

Or stackoverflow style: "You have started writing or editing a post."

How to make an autocomplete address field with google maps api?

Below I split all the details of formatted address like City, State, Country and Zip code. 
So when you start typing your street name and select any option then street name write over street field, city name write over city field and all other fields like state, country and zip code will fill automatically. 
Using Google APIs.
------------------------------------------------
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function() {
    var places = new google.maps.places.Autocomplete(document
            .getElementById('txtPlaces'));
    google.maps.event.addListener(places, 'place_changed', function() {
        var place = places.getPlace();
        var address = place.formatted_address;
        var  value = address.split(",");
        count=value.length;
        country=value[count-1];
        state=value[count-2];
        city=value[count-3];
        var z=state.split(" ");
        document.getElementById("selCountry").text = country;
        var i =z.length;
        document.getElementById("pstate").value = z[1];
        if(i>2)
        document.getElementById("pzcode").value = z[2];
        document.getElementById("pCity").value = city;
        var latitude = place.geometry.location.lat();
        var longitude = place.geometry.location.lng();
        var mesg = address;
        document.getElementById("txtPlaces").value = mesg;
        var lati = latitude;
        document.getElementById("plati").value = lati;
        var longi = longitude;
        document.getElementById("plongi").value = longi;            
    });
});

Python Selenium accessing HTML source

To answer your question about getting the URL to use for urllib, just execute this JavaScript code:

url = browser.execute_script("return window.location;")

Create a asmx web service in C# using visual studio 2013

  1. Create Empty ASP.NET Project enter image description here
  2. Add Web Service(asmx) to your project
    enter image description here

Add hover text without javascript like we hover on a user's reputation

This can also be done in CSS, for more customisability:

_x000D_
_x000D_
.hoverable {
  position: relative;
}

.hoverable>.hoverable__tooltip {
  display: none;
}

.hoverable:hover>.hoverable__tooltip {
  display: inline;
  position: absolute;
  top: 1em;
  left: 1em;
  background: #888;
  border: 1px solid black;
}
_x000D_
<div class="hoverable">
  <span class="hoverable__main">Main text</span>
  <span class="hoverable__tooltip">Hover text</span>
</div>
_x000D_
_x000D_
_x000D_

(Obviously, styling can be improved)

Rails 4: how to use $(document).ready() with turbo-links

You have to use:

document.addEventListener("turbolinks:load", function() {
  // your code here
})

from turbolinks doc.

How to monitor network calls made from iOS Simulator

FLEX is a great tool to monitor network traffic from your iOS app.

FLEX iOS Screenshot 1

On clicking on any of the requests listed in the above screenshot, I will be redirected to another screen where I can see more details about that request. FLEX iOS Screenshot 2

However, I had a use case where the app which I was working on would redirect the user to Safari. I wanted to monitor the network traffic in Safari as well, but FLEX could only monitor the traffic from your iOS app, not from any other app ( at the time of writing this answer ).

Then I switched to Proxyman to monitor network traffic from the iOS simulator.

  • It has a clear set of instructions on how to set it up with both iOS simulators and Android emulators.
  • It has a simple, intuitive UI, which makes it easy to work with.

enter image description here

How to disable logging on the standard error stream in Python?

There are some really nice answers here, but apparently the simplest is not taken too much in consideration (only from infinito).

root_logger = logging.getLogger()
root_logger.disabled = True

This disables the root logger, and thus all the other loggers. I haven't really tested but it should be also the fastest.

From the logging code in python 2.7 I see this

def handle(self, record):
    """
    Call the handlers for the specified record.

    This method is used for unpickled records received from a socket, as
    well as those created locally. Logger-level filtering is applied.
    """
    if (not self.disabled) and self.filter(record):
        self.callHandlers(record)

Which means that when it's disabled no handler is called, and it should be more efficient that filtering to a very high value or setting a no-op handler for example.

What does ||= (or-equals) mean in Ruby?

a ||= b

is equivalent to

a || a = b

and not

a = a || b

because of the situation where you define a hash with a default (the hash will return the default for any undefined keys)

a = Hash.new(true) #Which is: {}

if you use:

a[10] ||= 10 #same as a[10] || a[10] = 10

a is still:

{}

but when you write it like so:

a[10] = a[10] || 10

a becomes:

{10 => true}

because you've assigned the value of itself at key 10, which defaults to true, so now the hash is defined for the key 10, rather than never performing the assignment in the first place.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

 TimeZone tz = TimeZone.getDefault();  
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;

add commas to a number in jQuery

Here is my coffeescript version of @baacke's fiddle provided in a comment to @Timothy Perez

class Helpers
    @intComma: (number) ->
        # remove any existing commas
        comma = /,/g
        val = number.toString().replace comma, ''

        # separate the decimals
        valSplit = val.split '.'

        integer = valSplit[0].toString()
        expression = /(\d+)(\d{3})/
        while expression.test(integer)
            withComma = "$1,$2"
            integer = integer.toString().replace expression, withComma

        # recombine with decimals if any
        val = integer
        if valSplit.length == 2
            val = "#{val}.#{valSplit[1]}"

        return val

"Rate This App"-link in Google Play store app on the phone

This is if you publish your app in both Google Play Store and Amazon Appstore. I also handle the case that users (especially in China) don't have both app store and browser.

public void goToMyApp(boolean googlePlay) {//true if Google Play, false if Amazone Store
    try {
       startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse((googlePlay ? "market://details?id=" : "amzn://apps/android?p=") +getPackageName())));
    } catch (ActivityNotFoundException e1) {
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse((googlePlay ? "http://play.google.com/store/apps/details?id=" : "http://www.amazon.com/gp/mas/dl/android?p=") +getPackageName())));
        } catch (ActivityNotFoundException e2) {
            Toast.makeText(this, "You don't have any app that can open this link", Toast.LENGTH_SHORT).show();
        }
    }
}

Update data on a page without refreshing

You can read about jQuery Ajax from official jQuery Site: https://api.jquery.com/jQuery.ajax/

If you don't want to use any click event then you can set timer for periodically update.

Below code may be help you just example.

function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

Above function will call after every 10 seconds and get content from response.php and update in #some_div.

Python division

You're casting to float after the division has already happened in your second example. Try this:

float(20-10) / float(100-10)

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

jdk7 32 bit windows version to download

Go to the download page and download the Windows x86 version with filename jdk-7-windows-i586.exe.

Send message to specific client with socket.io and node.js

You can do this

On server.

global.io=require("socket.io")(server);

io.on("connection",function(client){
    console.log("client is ",client.id);
    //This is handle by current connected client 
    client.emit('messages',{hello:'world'})
    //This is handle by every client
    io.sockets.emit("data",{data:"This is handle by every client"})
    app1.saveSession(client.id)

    client.on("disconnect",function(){
        app1.deleteSession(client.id)
        console.log("client disconnected",client.id);
    })

})

    //And this is handle by particular client 
    var socketId=req.query.id
    if(io.sockets.connected[socketId]!=null) {
        io.sockets.connected[socketId].emit('particular User', {data: "Event response by particular user "});
    }

And on client, it is very easy to handle.

var socket=io.connect("http://localhost:8080/")
    socket.on("messages",function(data){
        console.log("message is ",data);
        //alert(data)
    })
    socket.on("data",function(data){
        console.log("data is ",data);
        //alert(data)
    })

    socket.on("particular User",function(data){
        console.log("data from server ",data);
        //alert(data)
    })

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

In my case I just ignored the following in application.properties file:

# Hibernate

#spring.jpa.hibernate.ddl-auto=update

It works for me....

Delete all data in SQL Server database

Below a script that I used to remove all data from an SQL Server database

------------------------------------------------------------
/* Use database */ 
-------------------------------------------------------------

use somedatabase;

GO

------------------------------------------------------------------
/* Script to delete an repopulate the base [init database] */
------------------------------------------------------------------

-------------------------------------------------------------
/* Procedure delete all constraints */ 
-------------------------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_DeleteAllConstraints' AND type = 'P')
    DROP PROCEDURE dbo.sp_DeleteAllConstraints
GO

CREATE PROCEDURE sp_DeleteAllConstraints
AS
    EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
    EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
GO

-----------------------------------------------------
/* Procedure delete all data from the database */ 
-----------------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_DeleteAllData' AND type = 'P')
    DROP PROCEDURE dbo.sp_DeleteAllData
GO

CREATE PROCEDURE sp_DeleteAllData
AS
    EXEC sp_MSForEachTable 'DELETE FROM ?'
GO

-----------------------------------------------
/* Procedure enable all constraints */ 
-----------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_EnableAllConstraints' AND type = 'P')
    DROP PROCEDURE dbo.sp_EnableAllConstraints
GO
-- ....
-- ....
-- ....

Updating state on props change in React Form

It's quite clearly from their docs:

If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.

Use: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

The question has been answered above, Just to make you feel comfortable using all four string at the same time in a connection

<?php
  define("DB_HOST", "localhost");
  define("DB_USER", "root");
  define("DB_PASSWORD", "");
  define("DB_DATABASE", "databasename");

  $db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
  // you could test connection eventually using a if and else conditional statement, 
  // feel free to take out the code below once you see Connected!
  if ($db) {
    echo "Connected!";
  } else {
    echo "Connection Failed";
  }
?>

How do I pause my shell script for a second before continuing?

You can make it wait using $RANDOM, a default random number generator. In the below I am using 240 seconds. Hope that helps @

> WAIT_FOR_SECONDS=`/usr/bin/expr $RANDOM % 240` /bin/sleep
> $WAIT_FOR_SECONDS

How do I delete from multiple tables using INNER JOIN in SQL server

Example for delete some records from master table and corresponding records from two detail tables:

BEGIN TRAN

  -- create temporary table for deleted IDs
  CREATE TABLE #DeleteIds (
    Id INT NOT NULL PRIMARY KEY
  )

  -- save IDs of master table records (you want to delete) to temporary table    
  INSERT INTO #DeleteIds(Id)
  SELECT DISTINCT mt.MasterTableId
  FROM MasterTable mt 
  INNER JOIN ... 
  WHERE ...  

  -- delete from first detail table using join syntax
  DELETE d
  FROM DetailTable_1 D
  INNER JOIN #DeleteIds X
    ON D.MasterTableId = X.Id


  -- delete from second detail table using IN clause  
  DELETE FROM DetailTable_2
  WHERE MasterTableId IN (
    SELECT X.Id
    FROM #DeleteIds X
  )


  -- and finally delete from master table
  DELETE d
  FROM MasterTable D
  INNER JOIN #DeleteIds X
    ON D.MasterTableId = X.Id

  -- do not forget to drop the temp table
  DROP TABLE #DeleteIds

COMMIT

document.getElementById(id).focus() is not working for firefox or chrome

Make sure you use "id" and "getElementById" as shown here:

<FORM id="my_form" name="my_form" action="">
<INPUT TYPE="text" NAME="somefield" ID="somefield" onChange="document.getElementById('my_form').submit();">
</FORM>

How do I select the "last child" with a specific class name in CSS?

I suggest that you take advantage of the fact that you can assign multiple classes to an element like so:

<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list last">test3</li>
    <li>test4</li>
</ul>

The last element has the list class like its siblings but also has the last class which you can use to set any CSS property you want, like so:

ul li.list {
    color: #FF0000;
}

ul li.list.last {
    background-color: #000;
}

C++: Where to initialize variables in constructor

There are many other reasons. You should always initialize all member variables in the initialization list if possible.

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6