Programs & Examples On #Time wait

Difference between webdriver.get() and webdriver.navigate()

navigate().to() and get() will work same when you use for the first time. When you use it more than once then using navigate().to() you can come to the previous page at any time whereas you can do the same using get().

Conclusion: navigate().to() holds the entire history of the current window and get() just reload the page and hold any history.

How to get a string between two characters?

This is a simple use \D+ regex and job done.
This select all chars except digits, no need to complicate

/\D+/

How to install OpenSSL in windows 10?

I also wanted to create OPEN SSL for Windows 10. An easy way of getting it done without running into a risk of installing unknown software from 3rd party websites and risking entries of viruses, is by using the openssl.exe that comes inside your Git for Windows installation. In my case, I found the open SSL in the following location of Git for Windows Installation.

C:\Program Files\Git\usr\bin\openssl.exe

If you also want instructions on how to use OPENSSL to generate and use Certificates. Here is a write-up on my blog. The step by step instructions first explains how to use Microsoft Windows Default Tool and also OPEN SSL and explains the difference between them.

http://kaushikghosh12.blogspot.com/2016/08/self-signed-certificates-with-microsoft.html

Adding minutes to date time in PHP

I thought this would help some when dealing with time zones too. My modified solution is based off of @Tim Cooper's solution, the correct answer above.

$minutes_to_add = 10;
$time = new DateTime();
**$time->setTimezone(new DateTimeZone('America/Toronto'));**
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$timestamp = $time->format("Y/m/d G:i:s");

The bold line, line 3, is the addition. I hope this helps some folks as well.

How can I sort a std::map first by value, then by key?

EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.

"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"

The most obvious approach is to loop through twice. On the first pass, order the values:

if(current_value > examined_value)
{
    current_value = examined_value
    (and then swap them, however you like)
}

Then on the second pass, alphabetize the words, but only if their values match.

if(current_value == examined_value)
{
    (alphabetize the two)
}

Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.

There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.

Loaded nib but the 'view' outlet was not set

To anyone that is using an xib method to create a UIView and having this problem, you will notice that you won't have the "view" outlet under the connections inspector menu. But if you set the File's Owners custom class to a UIViewController and then you will see the "view" outlet, which you can just CMND connect an outlet to the CustomView.

Creating a simple configuration file and parser in C++

SimpleConfigFile is a library that does exactly what you require and it is very simple to use.

# File file.cfg
url = http://example.com
file = main.exe
true = 0 

The following program reads the previous configuration file:

#include<iostream>
#include<string>
#include<vector>
#include "config_file.h"

int main(void)
{
    // Variables that we want to read from the config file
    std::string url, file;
    bool true_false;

    // Names for the variables in the config file. They can be different from the actual variable names.
    std::vector<std::string> ln = {"url","file","true"};

    // Open the config file for reading
    std::ifstream f_in("file.cfg");

    CFG::ReadFile(f_in, ln, url, file, true_false);
    f_in.close();

    std::cout << "url: " << url << std::endl;
    std::cout << "file: " << file << std::endl;
    std::cout << "true: " << true_false << std::endl;

    return 0;
}

The function CFG::ReadFile uses variadic templates. This way, you can pass the variables you want to read and the corresponding type is used for reading the data in the appropriate way.

Possible reasons for timeout when trying to access EC2 instance

For me it was the apache server hosted on a t2.micro linux EC2 instance, not the EC2 instance itself.

I fixed it by doing:

sudo su

service httpd restart

pow (x,y) in Java

Additionally for what was said, if you want integer powers of two, then 1 << x (or 1L << x) is a faster way to calculate 2x than Math.pow(2,x) or a multiplication loop, and is guaranteed to give you an int (or long) result.

It only uses the lowest 5 (or 6) bits of x (i.e. x & 31 (or x & 63)), though, shifting between 0 and 31 (or 63) bits.

How to use Boost in Visual Studio 2010

I could recommend the following trick: Create a special boost.props file

  1. Open the property manager
  2. Right click on your project node, and select 'Add new project property sheet'.
  3. Select a location and name your property sheet (e.g. c:\mystuff\boost.props)
  4. Modify the additional Include and Lib folders to the search path.

This procedure has the value that boost is included only in projects where you want to explicitly include it. When you have a new project that uses boost, do:

  1. Open the property manager.
  2. Right click on the project node, and select 'Add existing property sheet'.
  3. Select the boost property sheet.

EDIT (following edit from @jim-fred):

The resulting boost.props file looks something like this...

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros">
    <BOOST_DIR>D:\boost_1_53_0\</BOOST_DIR>
  </PropertyGroup>
  <PropertyGroup>
    <IncludePath>$(BOOST_DIR);$(IncludePath)</IncludePath>
    <LibraryPath>$(BOOST_DIR)stage\lib\;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
</Project>

It contains a user macro for the location of the boost directory (in this case, D:\boost_1_53_0) and two other parameters: IncludePath and LibraryPath. A statement #include <boost/thread.hpp> would find thread.hpp in the appropriate directory (in this case, D:\boost_1_53_0\boost\thread.hpp). The 'stage\lib\' directory may change depending on the directory installed to.

This boost.props file could be located in the D:\boost_1_53_0\ directory.

Java: recommended solution for deep cloning/copying an instance

For deep cloning (clones the entire object hierarchy):

  • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable.

  • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable.

For shallow cloning (clones only the first level properties):

I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

ASP.Net MVC: Calling a method from a view

You should create custom helper for just changing string format except using controller call.

iterrows pandas get next rows value

This can be solved also by izipping the dataframe (iterator) with an offset version of itself.

Of course the indexing error cannot be reproduced this way.

Check this out

import pandas as pd
from itertools import izip

df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])   

for id1, id2 in izip(df.iterrows(),df.ix[1:].iterrows()):
    print id1[1]['value']
    print id2[1]['value']

which gives

AA
BB
BB
CC

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

Get latitude and longitude based on location name with Google Autocomplete API

I hope this will be more useful for future scope contain auto complete Google API feature with latitude and longitude

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();  

Complete View

<!DOCTYPE html>
<html>
    <head>
    <title>Place Autocomplete With Latitude & Longitude </title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
#pac-input {
    background-color: #fff;
    padding: 0 11px 0 13px;
    width: 400px;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    text-overflow: ellipsis;
}
#pac-input:focus {
    border-color: #4d90fe;
    margin-left: -1px;
    padding-left: 14px;  /* Regular padding-left + 1. */
    width: 401px;
}
}
</style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
    <script>


  function initialize() {
        var address = (document.getElementById('pac-input'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
        /*********************************************************************/
        /* var address contain your autocomplete address *********************/
        /* place.geometry.location.lat() && place.geometry.location.lat() ****/
        /* will be used for current address latitude and longitude************/
        /*********************************************************************/
        document.getElementById('lat').innerHTML = place.geometry.location.lat();
        document.getElementById('long').innerHTML = place.geometry.location.lng();
        });
  }

   google.maps.event.addDomListener(window, 'load', initialize);

    </script>
    </head>
    <body>
<input id="pac-input" class="controls" type="text"
        placeholder="Enter a location">
<div id="lat"></div>
<div id="long"></div>
</body>
</html>

Get full path of a file with FileUpload Control

Check this:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="FileUp.aspx.vb" Inherits="FileUp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server"></asp:Label><br />
       <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <asp:Button ID="Button1" runat="server" Text="Upload" />
    </div>
    </form>
</body>
</html>

Code:

Partial Class FileUp
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim path As String
        Dim path1 As String
        path = Server.MapPath("~/")
        FileUpload1.SaveAs(path + FileUpload1.FileName)
        path1 = path + FileUpload1.FileName
        Label1.Text = path1
        Response.Write("File Uploaded successfully")
    End Sub
End Class

Installing Java 7 on Ubuntu

Oracle as well as modern versions of Ubuntu have moved to newer versions of Java. The default for Ubuntu 20.04 is OpenJDK 11 which is good enough for most purposes.

If you really need it for running legacy programs, OpenJDK 8 is also available for Ubuntu 20.04 from the official repositories.

If you really need exactly Java 7, the best bet as of 2020 is to download a Zulu distribution. The easiest to install if you have root privileges is the .DEB version, otherwise download the .ZIP one.

https://www.azul.com/downloads/zulu-community/?version=java-7-lts&os=ubuntu&architecture=x86-64-bit&package=jdk

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

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

            httpCon.disconnect();
}
}

What's the best way to trim std::string?

I'm not sure if your environment is the same, but in mine, the empty string case will cause the program to abort. I would either wrap that erase call with an if(!s.empty()) or use Boost as already mentioned.

How to show "Done" button on iPhone number pad

All those implementation about finding the keyboard view and adding the done button at the 3rd row (that is why button.y = 163 b/c keyboard's height is 216) are fragile because iOS keeps change the view hierarchy. For example none of above codes work for iOS9.

I think it is more safe to just find the topmost view, by [[[UIApplication sharedApplication] windows] lastObject], and just add the button at bottom left corner of it, doneButton.frame = CGRectMake(0, SCREEN_HEIGHT-53, 106, 53);// portrait mode

Set font-weight using Bootstrap classes

EDIT 2 (final) : According to the bootstrap 4 documentation, class="font-weight-bold" is what you are looking for.


EDIT : You can use class="font-weight-bold" as shown here (Bootstrap 4 alpha).

I kept the original answer below for clarity purposes.


I am posting this answer because this thread seems to have a lot of visitors, yet it had no proper solution to solve this issue. But there will be soon now a way with Bootstrap 4 :

As this GitHub pull request shows, you will just have to use the text-weight-normal, text-weight-bold and text-weight-italic classes.

This can maybe change until the official stable release. At this date of writing, this pull request is not merged yet in the alpha branch.

I will update this post once Bootstrap v4 has been released.

How to move Docker containers between different hosts?

Use this script: https://github.com/ricardobranco777/docker-volumes.sh

This does preserve data in volumes.

Example usage:

# Stop the container   
docker stop $CONTAINER

# Create a new image   
docker commit $CONTAINER $CONTAINER

# Save image
docker save -o $CONTAINER.tar $CONTAINER

# Save the volumes (use ".tar.gz" if you want compression)
docker-volumes.sh $CONTAINER save $CONTAINER-volumes.tar

# Copy image and volumes to another host
scp $CONTAINER.tar $CONTAINER-volumes.tar $USER@$HOST:

# On the other host:
docker load -i $CONTAINER.tar
docker create --name $CONTAINER [<PREVIOUS CONTAINER OPTIONS>] $CONTAINER

# Load the volumes
docker-volumes.sh $CONTAINER load $CONTAINER-volumes.tar

# Start container
docker start $CONTAINER

send mail from linux terminal in one line

You can install the mail package in Ubuntu with below command.

For Ubuntu -:

$ sudo apt-get install -y mailutils

For CentOs-:

$ sudo yum install -y mailx

Test Mail command-:

$ echo "Mail test" | mail -s "Subject" [email protected]

What does iterator->second mean?

I'm sure you know that a std::vector<X> stores a whole bunch of X objects, right? But if you have a std::map<X, Y>, what it actually stores is a whole bunch of std::pair<const X, Y>s. That's exactly what a map is - it pairs together the keys and the associated values.

When you iterate over a std::map, you're iterating over all of these std::pairs. When you dereference one of these iterators, you get a std::pair containing the key and its associated value.

std::map<std::string, int> m = /* fill it */;
auto it = m.begin();

Here, if you now do *it, you will get the the std::pair for the first element in the map.

Now the type std::pair gives you access to its elements through two members: first and second. So if you have a std::pair<X, Y> called p, p.first is an X object and p.second is a Y object.

So now you know that dereferencing a std::map iterator gives you a std::pair, you can then access its elements with first and second. For example, (*it).first will give you the key and (*it).second will give you the value. These are equivalent to it->first and it->second.

How to change background color in android app

You can try this in xml sheet:

android:background="@color/background_color"

Why can't I see the "Report Data" window when creating reports?

I had the same problem, but in c# 2012 I closed the "report data" and I couldn't find it and I finally found a solution to this issue.

This is my method:

VIEW >> TOOLBARS >> CUSTOMIZE >> COMMANDS ... select from the "Menu bar" .. VIEW.

OK now in the "Controls" find the "REPORT DATA", select it and MOVE it UP, close the menu. After that select a file.rdlc and click on the "View" ... OK Finally will be appeared "REPORT DATA"...

Javascript Date: next month

I was looking for a simple one-line solution to get the next month via math so I wouldn't have to look up the javascript date functions (mental laziness on my part). Quite strangely, I didn't find one here.

I overcame my brief bout of laziness, wrote one, and decided to share!

Solution:

(new Date().getMonth()+1)%12 + 1

Just to be clear why this works, let me break down the magic!

It gets the current month (which is in 0..11 format), increments by 1 for the next month, and wraps it to a boundary of 12 via modulus (11%12==11; 12%12==0). This returns the next month in the same 0..11 format, so converting to a format Date() will recognize (1..12) is easy: simply add 1 again.

Proof of concept:

> for(var m=0;m<=11;m++) { console.info( "next month for %i: %i", m+1, (m+1)%12 + 1 ) }
next month for 1: 2
next month for 2: 3
next month for 3: 4
next month for 4: 5
next month for 5: 6
next month for 6: 7
next month for 7: 8
next month for 8: 9
next month for 9: 10
next month for 10: 11
next month for 11: 12
next month for 12: 1

So there you have it.

Remove non-numeric characters (except periods and commas) from a string

If letters are always in the beginning or at the end, you can simply just use trim...no regex needed

$string = trim($string, "a..zA..Z"); // this also take care of lowercase

"AR3,373.31" --> "3,373.31"
"12.322,11T" --> "12.322,11"
"12.322,11"  --> "12.322,11"

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

I had this problem when using RubyMine (6.3.3). One day I tried to run my code, but it didn't work and complained about no JavaScript runtime found. I was able to run rails s though. The fix for me was creating a new Run configuration. Seems really bizarre that the Run configuration would become corrupt.

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

Try

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

or even

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

if input is not very large.

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

How to find path of active app.config file?

I tried one of the previous answers in a web app (actually an Azure web role running locally) and it didn't quite work. However, this similar approach did work:

var map = new ExeConfigurationFileMap { ExeConfigFilename = "MyComponent.dll.config" };
var path = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).FilePath;

The config file turned out to be in C:\Program Files\IIS Express\MyComponent.dll.config. Interesting place for it.

How can I make an image transparent on Android?

On newer versions of Android (post Android 4.2 (Jelly Bean) at least), the setAlpha(int value) method is depreciated. Instead, use the setAlpha(float value) method that takes a float between 0 and 1 where 0 is complete transparency and 1 is no transparency.

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

How can I unstage my files again after making a local commit?

For unstaging all the files in your last commit -

git reset HEAD~

How do I include negative decimal numbers in this regular expression?

You should add an optional hyphen at the beginning by adding -? (? is a quantifier meaning one or zero occurrences):

^-?[0-9]\d*(\.\d+)?$

I verified it in Rubular with these values:

10.00
-10.00

and both matched as expected.

Amazon S3 direct file upload from client browser - private key disclosure

If you are willing to use a 3rd party service, auth0.com supports this integration. The auth0 service exchanges a 3rd party SSO service authentication for an AWS temporary session token will limited permissions.

See: https://github.com/auth0-samples/auth0-s3-sample/
and the auth0 documentation.

Delete all data in SQL Server database

  1. First you'll have to disable all the triggers :

    sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER all';
    
  2. Run this script : (Taken from this post Thank you @SQLMenace)

    SET NOCOUNT ON
    GO
    
    SELECT 'USE [' + db_name() +']';
    ;WITH a AS 
    (
         SELECT 0 AS lvl, 
                t.object_id AS tblID 
         FROM sys.TABLES t
         WHERE t.is_ms_shipped = 0
           AND t.object_id NOT IN (SELECT f.referenced_object_id 
                                   FROM sys.foreign_keys f)
    
         UNION ALL
    
         SELECT a.lvl + 1 AS lvl, 
                f.referenced_object_id AS tblId
         FROM a
         INNER JOIN sys.foreign_keys f ON a.tblId = f.parent_object_id 
                                       AND a.tblID <> f.referenced_object_id
    )
    SELECT 
        'Delete from ['+ object_schema_name(tblID) + '].[' + object_name(tblId) + ']' 
    FROM a
    GROUP BY tblId 
    ORDER BY MAX(lvl),1
    

This script will produce DELETE statements in proper order. starting from referenced tables then referencing ones

  1. Copy the DELETE FROM statements and run them once

  2. enable triggers

    sp_msforeachtable 'ALTER TABLE ? ENABLE TRIGGER all'
    
  3. Commit the changes :

    begin transaction
    commit;
    

How can I open a website in my web browser using Python?

If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website. e.g.

 import webbrowser

 webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)

Check if inputs are empty using jQuery

Please use this code for input text

$('#search').on("input",function (e) {

});

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

Get properties and values from unknown object

I haven't found this to work on, say Application objects. I have however had success with

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

string rval = serializer.Serialize(myAppObj);

How to register multiple implementations of the same interface in Asp.Net Core?

You're correct, the built in ASP.NET Core container does not have the concept of registering multiple services and then retrieving a specific one, as you suggest, a factory is the only real solution in that case.

Alternatively, you could switch to a third party container like Unity or StructureMap that does provide the solution you need (documented here: https://docs.asp.net/en/latest/fundamentals/dependency-injection.html?#replacing-the-default-services-container).

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

In case anyone stumbles with this problem again, the accepted solution did work for older versions of ionic and app scripts, I had used it many times in the past, but last week, after I updated some stuff, it got broken again, and this fix wasn't working anymore as this was already solved on the current version of app-scripts, most of the info is referred on this post https://forum.ionicframework.com/t/ionic-cordova-run-android-livereload-cordova-not-available/116790/18 but I'll make it short here:

First make sure you have this versions on your system

cli packages: (xxxx\npm\node_modules)

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : not installed

local packages:

@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0
Ionic Framework    : ionic-angular 3.9.2

System:

Node : v10.1.0
npm  : 5.6.0

An this on your package.json

"@angular/cli": "^6.0.3", "@ionic/app-scripts": "^3.1.9", "typescript": "~2.4.2"

Now remove your platform with ionic cordova platform rm what-ever Then DELETE the node_modules and plugins folder and MAKE SURE the platform was deleted inside the platforms folder.

Finally, run

npm install ionic cordova platform add what-ever ionic cordova run

And everything should be working again

Matplotlib legends in subplot

This does what you want and overcomes some of the problems in other answers:

import matplotlib.pyplot as plt

labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]

f,axs = plt.subplots(3, sharex=True, sharey=True)

# ---- loop over axes ----
for i,ax in enumerate(axs):
  axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
  axs[i].legend(loc="upper right")

plt.show()

... produces ... subplots

Virtual member call in a constructor

There are well-written answers above for why you wouldn't want to do that. Here's a counter-example where perhaps you would want to do that (translated into C# from Practical Object-Oriented Design in Ruby by Sandi Metz, p. 126).

Note that GetDependency() isn't touching any instance variables. It would be static if static methods could be virtual.

(To be fair, there are probably smarter ways of doing this via dependency injection containers or object initializers...)

public class MyClass
{
    private IDependency _myDependency;

    public MyClass(IDependency someValue = null)
    {
        _myDependency = someValue ?? GetDependency();
    }

    // If this were static, it could not be overridden
    // as static methods cannot be virtual in C#.
    protected virtual IDependency GetDependency() 
    {
        return new SomeDependency();
    }
}

public class MySubClass : MyClass
{
    protected override IDependency GetDependency()
    {
        return new SomeOtherDependency();
    }
}

public interface IDependency  { }
public class SomeDependency : IDependency { }
public class SomeOtherDependency : IDependency { }

100% Min Height CSS layout

I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.

Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.

I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.

Why does a base64 encoded string have an = sign at the end

From Wikipedia:

The final '==' sequence indicates that the last group contained only one byte, and '=' indicates that it contained two bytes.

Thus, this is some sort of padding.

How do I set a program to launch at startup

I found adding a shortcut to the startup folder to be the easiest way for me. I had to add a reference to "Windows Script Host Object Model" and "Microsoft.CSharp" and then used this code:

IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
string shortcutAddress = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\MyAppName.lnk";
System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();

IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "My App Name";
shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
shortcut.TargetPath = curAssembly.Location;
shortcut.IconLocation = AppDomain.CurrentDomain.BaseDirectory + @"MyIconName.ico";
shortcut.Save();

How to change the status bar color in Android?

One more solution:

final View decorView = w.getDecorView();
View view = new View(BaseControllerActivity.this);
final int statusBarHeight = UiUtil.getStatusBarHeight(ContextHolder.get());
view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight));
view.setBackgroundColor(colorValue);
((ViewGroup)decorView).addView(view);

How to prevent "The play() request was interrupted by a call to pause()" error?

here is a solution from googler blog:

var video = document.getElementById('#video')
var promise = video.play()
//chrome version 53+
if(promise){
    promise.then(_=>{
        video.pause()
    })
}else{
    video.addEventListener('canplaythrough', _=>{
        video.pause()
    }, false)
}

Java Enum Methods - return opposite direction enum

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    public Direction getOppositeDirection(){
        return Direction.values()[(this.ordinal() + 2) % 4];
    }
}

Enums have a static values method that returns an array containing all of the values of the enum in the order they are declared. source

since NORTH gets 1, EAST gets 2, SOUTH gets 3, WEST gets 4; you can create a simple equation to get the opposite one:

(value + 2) % 4

Expand div to max width when float:left is set

And based on merkuro's solution, if you would like maximize the one on the left, you should use:

<!DOCTYPE html>   
<html lang="en">     
    <head>              
        <meta "charset="UTF-8" />   
        <title>Content with Menu</title>                 
        <style>
            .content .left {
                margin-right: 100px;
                background-color: green;
            }
            .content .right {
                float: right;
                width: 100px;
                background-color: red;
            }
        </style>              
    </head>
    <body>        
        <div class="content">
            <div class="right">  
                <p>is</p>
                <p>this</p>
                <p>what</p>
                <p>you are looking for?</p>
            </div>
            <div class="left">
                <p>Hi, Flo!</p>
            </div>
        </div>
    </body>
</html>

Has not been tested on IE, so it may look broken on IE.

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

How can I make text appear on next line instead of overflowing?

Well, you can stick one or more "soft hyphens" (&#173;) in your long unbroken strings. I doubt that old IE versions deal with that correctly, but what it's supposed to do is tell the browser about allowable word breaks that it can use if it has to.

Now, how exactly would you pick where to stuff those characters? That depends on the actual string and what it means, I guess.

How do I pass command line arguments to a Node.js program?

Here's my 0-dep solution for named arguments:

const args = process.argv
    .slice(2)
    .map(arg => arg.split('='))
    .reduce((args, [value, key]) => {
        args[value] = key;
        return args;
    }, {});

console.log(args.foo)
console.log(args.fizz)

Example:

$ node test.js foo=bar fizz=buzz
bar
buzz

Note: Naturally this will fail when the argument contains a =. This is only for very simple usage.

Draggable div without jQuery UI

Here's my contribution:

http://jsfiddle.net/g6m5t8co/1/

<!doctype html>
<html>
    <head>
        <style>
            #container {
                position:absolute;
                background-color: blue;
                }
            #elem{
                position: absolute;
                background-color: green;
                -webkit-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                -ms-user-select: none;
                -khtml-user-select: none;     
                user-select: none;
            }
        </style>
        <script>
            var mydragg = function(){
                return {
                    move : function(divid,xpos,ypos){
                        divid.style.left = xpos + 'px';
                        divid.style.top = ypos + 'px';
                    },
                    startMoving : function(divid,container,evt){
                        evt = evt || window.event;
                        var posX = evt.clientX,
                            posY = evt.clientY,
                        divTop = divid.style.top,
                        divLeft = divid.style.left,
                        eWi = parseInt(divid.style.width),
                        eHe = parseInt(divid.style.height),
                        cWi = parseInt(document.getElementById(container).style.width),
                        cHe = parseInt(document.getElementById(container).style.height);
                        document.getElementById(container).style.cursor='move';
                        divTop = divTop.replace('px','');
                        divLeft = divLeft.replace('px','');
                        var diffX = posX - divLeft,
                            diffY = posY - divTop;
                        document.onmousemove = function(evt){
                            evt = evt || window.event;
                            var posX = evt.clientX,
                                posY = evt.clientY,
                                aX = posX - diffX,
                                aY = posY - diffY;
                                if (aX < 0) aX = 0;
                                if (aY < 0) aY = 0;
                                if (aX + eWi > cWi) aX = cWi - eWi;
                                if (aY + eHe > cHe) aY = cHe -eHe;
                            mydragg.move(divid,aX,aY);
                        }
                    },
                    stopMoving : function(container){
                        var a = document.createElement('script');
                        document.getElementById(container).style.cursor='default';
                        document.onmousemove = function(){}
                    },
                }
            }();

        </script>
    </head>
    <body>
        <div id='container' style="width: 600px;height: 400px;top:50px;left:50px;">     
            <div id="elem" onmousedown='mydragg.startMoving(this,"container",event);' onmouseup='mydragg.stopMoving("container");' style="width: 200px;height: 100px;">
                <div style='width:100%;height:100%;padding:10px'>
                <select id=test>
                    <option value=1>first
                    <option value=2>second
                </select>
                <INPUT TYPE=text value="123">
                </div>
            </div>
        </div>  
    </body>
</html>

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

Enabling WiFi on Android Emulator

Wifi is not available on the emulator if you are using below of API level 25.

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

More Information: https://developer.android.com/studio/run/emulator.html#wifi

Run a shell script with an html button

As stated by Luke you need to use a server side language, like php. This is a really simple php example:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("/path/to/name.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

Pycharm and sys.argv arguments

In addition to Jim's answer (sorry not enough rep points to make a comment), just wanted to point out that the arguments specified in PyCharm do not have special characters escaped, unlike what you would do on the command line. So, whereas on the command line you'd do:

python mediadb.py  /media/paul/New\ Volume/Users/paul/Documents/spinmaster/\*.png

the PyCharm parameter would be:

"/media/paul/New Volume/Users/paul/Documents/spinmaster/*.png"

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I recently got this message, too, after I switched the data center location of a web application sending through Google SMTP.

The URL that apparently Google means is: https://support.google.com/mail/answer/78754. At that link, one of the steps is to reset your password. Not coincidentally, I also received an email from google with a subject of "Suspicious sign in prevented" that instructed me to change my password.

After resetting my password, I was back to using Google SMTP as usual.

Things possible in IntelliJ that aren't possible in Eclipse?

Data flow analysis : inter-procedural backward flow analysis and forward flow analysis, as described here. My experiences are based on Community Edition, which does data flow analysis fairly well. It has failed (refused to do anything) in few cases when code is very complex.

How do I find out what is hammering my SQL Server?

I assume due diligence here that you confirmed the CPU is actually consumed by SQL process (perfmon Process category counters would confirm this). Normally for such cases you take a sample of the relevant performance counters and you compare them with a baseline that you established in normal load operating conditions. Once you resolve this problem I recommend you do establish such a baseline for future comparisons.

You can find exactly where is SQL spending every single CPU cycle. But knowing where to look takes a lot of know how and experience. Is is SQL 2005/2008 or 2000 ? Fortunately for 2005 and newer there are a couple of off the shelf solutions. You already got a couple good pointer here with John Samson's answer. I'd like to add a recommendation to download and install the SQL Server Performance Dashboard Reports. Some of those reports include top queries by time or by I/O, most used data files and so on and you can quickly get a feel where the problem is. The output is both numerical and graphical so it is more usefull for a beginner.

I would also recommend using Adam's Who is Active script, although that is a bit more advanced.

And last but not least I recommend you download and read the MS SQL Customer Advisory Team white paper on performance analysis: SQL 2005 Waits and Queues.

My recommendation is also to look at I/O. If you added a load to the server that trashes the buffer pool (ie. it needs so much data that it evicts the cached data pages from memory) the result would be a significant increase in CPU (sounds surprising, but is true). The culprit is usually a new query that scans a big table end-to-end.

Get an object's class name at runtime

I know I'm late to the party, but I find that this works too.

var constructorString: string = this.constructor.toString();
var className: string = constructorString.match(/\w+/g)[1]; 

Alternatively...

var className: string = this.constructor.toString().match(/\w+/g)[1];

The above code gets the entire constructor code as a string and applies a regex to get all 'words'. The first word should be 'function' and the second word should be the name of the class.

Hope this helps.

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.

How do I find the date a video (.AVI .MP4) was actually recorded?

There doesn't seem to be a well defined standard for video metadata (compared to photos and audio files, which have EXIF and ID3/etc. respectively)

Some tags exists like e.g. Title, Composer etc. You can see those if you select a movie file in Windows 7 (perhaps earlier versions also) explorer or right click and view properties. I have not found a tag for recording date unfortunately - the closest thing available is Year (integer) :-(

Programatically, you can read and write most of these tags in .NET using Taglib Sharp from the mono project. Source and binaries are available on the banshee FTP server. It has a pretty impressive list of formats it supports (but still, make sure you catch exceptions when trying to read or write tags - it will throw whenever it finds a file it cannot understand, something which happened to me several times for my modest collection of home recordings.)

To read tags:

using (var f = TagLib.File.Create(@"c:\Path\To\MyVideo.mp4"))
{
    if (f.Tag != null)
    {
        string title = f.Tag.Title;
        Size resolution = new Size(f.Properties.VideoWidth, f.Properties.VideoHeight);
        int year = f.Tag.Year;
        // etc.
    }
}

And similarly, to write metadata back to the file:

using (var f = TagLib.File.Create(@"c:\Path\To\MyVideo.mp4"))
{
    f.Tag.Title = "My Awesome Movie";
    f.Tag.Year = (uint)2011;
    f.Save();
}

Determine what attributes were changed in Rails after_save callback?

Rails 5.1+

Use saved_change_to_published?:

class SomeModel < ActiveRecord::Base
  after_update :send_notification_after_change

  def send_notification_after_change
    Notification.send(…) if (saved_change_to_published? && self.published == true)
  end

end

Or if you prefer, saved_change_to_attribute?(:published).

Rails 3–5.1

Warning

This approach works through Rails 5.1 (but is deprecated in 5.1 and has breaking changes in 5.2). You can read about the change in this pull request.

In your after_update filter on the model you can use _changed? accessor. So for example:

class SomeModel < ActiveRecord::Base
  after_update :send_notification_after_change

  def send_notification_after_change
    Notification.send(...) if (self.published_changed? && self.published == true)
  end

end

It just works.

mysql: get record count between two date-time

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

How to measure height, width and distance of object using camera?

If you know the viewport angle of the camera, you can use the height in pixels to determine the angle from the top to bottom of the object. Then, using the distance and arctangent calculate the height:

height = arctan(angle) * distance

To find the viewport angle, point the camera at something which is of known height, and make it exactly fill the screen. For example, point it at a ruler, and make it just far enough away that you can only barely see the ends of the ruler. Measure the distance from the camera, and then your total viewport angle is

viewportAngle = tan(ruler_length / distance)

Then, suppose your camera is 480px tall (cheap webcam), and the view angle is 20°. If you have an object onscreen which is 240px tall, then its angle is 10°. If you know it's 2 feet away, you would say 2 feet * arctan(10°) = ~4.1 inches tall. (I think... it's 2am so this may be a little off)

PHP JSON String, escape Double Quotes for JS output

I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around

$products = array($ofDirtyArray);
if($products !=null) {
    header("Content-type: application/json");
    header('Content-Type: charset=utf-8');
    array_walk_recursive($products, function(&$val) {
        $val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
    });
    echo json_encode($products,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

I hope it helps someone/someone improves it.

Static Vs. Dynamic Binding in Java

Well in order to understand how static and dynamic binding actually works? or how they are identified by compiler and JVM?

Let's take below example where Mammal is a parent class which has a method speak() and Human class extends Mammal, overrides the speak() method and then again overloads it with speak(String language).

public class OverridingInternalExample {

    private static class Mammal {
        public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
    }

    private static class Human extends Mammal {

        @Override
        public void speak() { System.out.println("Hello"); }

        // Valid overload of speak
        public void speak(String language) {
            if (language.equals("Hindi")) System.out.println("Namaste");
            else System.out.println("Hello");
        }

        @Override
        public String toString() { return "Human Class"; }

    }

    //  Code below contains the output and bytecode of the method calls
    public static void main(String[] args) {
        Mammal anyMammal = new Mammal();
        anyMammal.speak();  // Output - ohlllalalalalalaoaoaoa
        // 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

        Mammal humanMammal = new Human();
        humanMammal.speak(); // Output - Hello
        // 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

        Human human = new Human();
        human.speak(); // Output - Hello
        // 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V

        human.speak("Hindi"); // Output - Namaste
        // 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V
    }
}

When we compile the above code and try to look at the bytecode using javap -verbose OverridingInternalExample, we can see that compiler generates a constant table where it assigns integer codes to every method call and byte code for the program which I have extracted and included in the program itself (see the comments below every method call)

Program Bytecode

By looking at above code we can see that the bytecodes of humanMammal.speak(), human.speak() and human.speak("Hindi") are totally different (invokevirtual #4, invokevirtual #7, invokevirtual #9) because the compiler is able to differentiate between them based on the argument list and class reference. Because all of this get resolved at compile time statically that is why Method Overloading is known as Static Polymorphism or Static Binding.

But bytecode for anyMammal.speak() and humanMammal.speak() is same (invokevirtual #4) because according to compiler both methods are called on Mammal reference.

So now the question comes if both method calls have same bytecode then how does JVM know which method to call?

Well, the answer is hidden in the bytecode itself and it is invokevirtual instruction set. JVM uses the invokevirtual instruction to invoke Java equivalent of the C++ virtual methods. In C++ if we want to override one method in another class we need to declare it as virtual, But in Java, all methods are virtual by default because we can override every method in the child class (except private, final and static methods).

In Java, every reference variable holds two hidden pointers

  1. A pointer to a table which again holds methods of the object and a pointer to the Class object. e.g. [speak(), speak(String) Class object]
  2. A pointer to the memory allocated on the heap for that object’s data e.g. values of instance variables.

So all object references indirectly hold a reference to a table which holds all the method references of that object. Java has borrowed this concept from C++ and this table is known as virtual table (vtable).

A vtable is an array like structure which holds virtual method names and their references on array indices. JVM creates only one vtable per class when it loads the class into memory.

So whenever JVM encounter with a invokevirtual instruction set, it checks the vtable of that class for the method reference and invokes the specific method which in our case is the method from a object not the reference.

Because all of this get resolved at runtime only and at runtime JVM gets to know which method to invoke, that is why Method Overriding is known as Dynamic Polymorphism or simply Polymorphism or Dynamic Binding.

You can read it more details on my article How Does JVM Handle Method Overloading and Overriding Internally.

What are invalid characters in XML

The predeclared characters are:

& < > " '

See "What are the special characters in XML?" for more information.

How to select top n rows from a datatable/dataview in ASP.NET

You could modify the query. If you are using SQL Server at the back, you can use Select top n query for such need. The current implements fetch the whole data from database. Selecting only the required number of rows will give you a performance boost as well.

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is Linux specific and is an environment variable pointing to directories where the dynamic loader should look for shared libraries.

Try to add the directory where your .dll is in the PATH variable. Windows will automatically look in the directories listet in this environment variable. LD_LIBRARY_PATH probably won't solve the problem (unless the JVM uses it - I do not know about that).

How to schedule a task to run when shutting down windows

One workaround might be to write a simple batch file to run the program then shutdown the computer.

You can shut down from the command line -- so your script could be fairly simple:

c:\directory\myProgram.exe
C:\WINDOWS\system32\shutdown.exe -s -f -t 0

how to convert a string date into datetime format in python?

You should use datetime.datetime.strptime:

import datetime

dt = datetime.datetime.strptime(string_date, fmt)

fmt will need to be the appropriate format for your string. You'll find the reference on how to build your format here.

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

Capture keyboardinterrupt in Python without try-except

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal
import sys
import time
import threading

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

One of the way to browse your database is to use questoid sqlite manager.

# 1. Download questoid manager from this link .

# 2. Drop this file into your eclipse --> dropins.

# 3. Restart your eclipse.

# 4. Now go to your file explorer and click your database. you can find a blue database icon enabled in the top right corner.

# 5. Double click the icon and you can see ur inserted fields/tables/ in the database

What's the difference between console.dir and console.log?

Well, the Console Standard (as of commit ef88ec7a39fdfe79481d7d8f2159e4a323e89648) currently calls for console.dir to apply generic JavaScript object formatting before passing it to Printer (a spec-level operation), but for a single-argument console.log call, the spec ends up passing the JavaScript object directly to Printer.

Since the spec actually leaves almost everything about the Printer operation to the implementation, it's left to their discretion what type of formatting to use for console.log().

Find Java classes implementing an interface

The code you are talking about sounds like ServiceLoader, which was introduced in Java 6 to support a feature that has been defined since Java 1.3 or earlier. For performance reasons, this is the recommended approach to find interface implementations at runtime; if you need support for this in an older version of Java, I hope that you'll find my implementation helpful.

There are a couple of implementations of this in earlier versions of Java, but in the Sun packages, not in the core API (I think there are some classes internal to ImageIO that do this). As the code is simple, I'd recommend providing your own implementation rather than relying on non-standard Sun code which is subject to change.

How to extract filename.tar.gz file

It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

select count(*) from table of mysql in php

You need to alias the aggregate using the as keyword in order to call it from mysqli_fetch_assoc

$result=mysqli_query($conn,"SELECT count(*) as total from Students");
$data=mysqli_fetch_assoc($result);
echo $data['total'];

What is the easiest way to get the current day of the week in Android?

If you do not want to use Calendar class at all you can use this

String weekday_name = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(System.currentTimeMillis());

i.e., result is,

"Sunday"

String to HtmlDocument

You could try with OpenNew and then with Write but that's a bit strange use of that class. More info on MSDN.

How to set background color of a View

Several choices to do this...

Set background to green:

v.setBackgroundColor(0x00FF00);

Set background to green with Alpha:

v.setBackgroundColor(0xFF00FF00);

Set background to green with Color.GREEN constant:

v.setBackgroundColor(Color.GREEN);

Set background to green defining in Colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>     
    <color name="myGreen">#00FF00</color> 
    <color name="myGreenWithAlpha">#FF00FF00</color> 
</resources>

and using:

v.setBackgroundResource(R.color.myGreen);

and:

v.setBackgroundResource(R.color.myGreenWithAlpha);

or the longer winded:

v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreen));

and:

v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreenWithAlpha));

Git fatal: protocol 'https' is not supported

This issue persisted even after the fix from most upvoted answer.

More specific, I pasted in the link without "Ctrl + v", but it still gave fatal: protocol 'https' is not supported.

But if you copy that message in Windows or in Google search bar you will that the actual message is fatal: protocol '##https' is not supported, where '#' stands for this character. As you can see, those 2 characters have not been removed.

I was working on IntelliJ IDEA Community Edition 2019.2.3 and the following fix refers to this tool, but the answer is that those 2 characters are still there and need to be removed from the link.

IntelliJ fix

Go to top bar, select VCS -> Git -> Remotes... and click.

Now it will open something link this

enter image description here

You can see those 2 unrecognised characters. We have to remove them. Either click edit icon and delete those 2 characters or you can delete the link and add a new one.

Make sure you have ".git" folder in your project folder.

enter image description here

And now it should like this. Click "Ok" and now you can push files to your git repository.

enter image description here

Redirect From Action Filter Attribute

Alternatively to a redirect, if it is calling your own code, you could use this:

actionContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(new { controller = "Home", action = "Error" })
);

actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);

It is not a pure redirect but gives a similar result without unnecessary overhead.

How to convert a string into double and vice versa?

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.

Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.

Python safe method to get value of nested dictionary

For nested dictionary/JSON lookups, you can use dictor

pip install dictor

dict object

{
    "characters": {
        "Lonestar": {
            "id": 55923,
            "role": "renegade",
            "items": [
                "space winnebago",
                "leather jacket"
            ]
        },
        "Barfolomew": {
            "id": 55924,
            "role": "mawg",
            "items": [
                "peanut butter jar",
                "waggy tail"
            ]
        },
        "Dark Helmet": {
            "id": 99999,
            "role": "Good is dumb",
            "items": [
                "Shwartz",
                "helmet"
            ]
        },
        "Skroob": {
            "id": 12345,
            "role": "Spaceballs CEO",
            "items": [
                "luggage"
            ]
        }
    }
}

to get Lonestar's items, simply provide a dot-separated path, ie

import json
from dictor import dictor

with open('test.json') as data: 
    data = json.load(data)

print dictor(data, 'characters.Lonestar.items')

>> [u'space winnebago', u'leather jacket']

you can provide fallback value in case the key isnt in path

theres tons more options you can do, like ignore letter casing and using other characters besides '.' as a path separator,

https://github.com/perfecto25/dictor

Laravel migration: unique key is too long, even if specified

In 24 october 2016 Taylor Otwell the Author of Laravel announced on is Twitter

"utf8mb4" will be the default MySQL character set in Laravel 5.4 for better emoji support. Taylor Otwell Twitter Post

which before version 5.4 the character set was utf8

During this century many web app, include chat or some kind platform to allow their users to converses, and many people like to use emoji or smiley. and this are some kind of super characters that require more spaces to be store and that is only possible using utf8mb4 as the charset. That is the reason why they migrate to utf8mb4 just for space purpose.

if you look up in the Illuminate\Database\Schema\Builder class you will see that the $defaultStringLength is set to 255, and to modify that you can procede through the Schema Facade and call the defaultStringLength method and pass the new length.

to perform that change call that method within your AppServiceProvider class which is under the app\providers subdirectory like this

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // all other code ...

        Schema::defaultStringLength(191); 
    }
    // and all other code goes here
}

I will suggest to use 191 as the value just because MySQL support 767 bytes, and because 767 / 4 which is the number of byte take by each multibyte character you will get 191.

You can learn more here The utf8mb4 Character Set (4-Byte UTF-8 Unicode Encoding) Limits on Table Column Count and Row Size

When do I use path params vs. query params in a RESTful API?

Best practice for RESTful API design is that path params are used to identify a specific resource or resources, while query parameters are used to sort/filter those resources.

Here's an example. Suppose you are implementing RESTful API endpoints for an entity called Car. You would structure your endpoints like this:

GET /cars
GET /cars/:id
POST /cars
PUT /cars/:id
DELETE /cars/:id

This way you are only using path parameters when you are specifying which resource to fetch, but this does not sort/filter the resources in any way.

Now suppose you wanted to add the capability to filter the cars by color in your GET requests. Because color is not a resource (it is a property of a resource), you could add a query parameter that does this. You would add that query parameter to your GET /cars request like this:

GET /cars?color=blue

This endpoint would be implemented so that only blue cars would be returned.

As far as syntax is concerned, your URL names should be all lowercase. If you have an entity name that is generally two words in English, you would use a hyphen to separate the words, not camel case.

Ex. /two-words

Open file in a relative location in Python

With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.

If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.

So you can fiddle with something like this:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

How to limit file upload type file size in PHP?

Hope This useful...

form:

<form action="check.php" method="post" enctype="multipart/form-data">
<label>Upload An Image</label>
<input type="file" name="file_upload" />
<input type="submit" name="upload"/>
</form>

check.php:

<?php 
    if(isset($_POST['upload'])){
        $maxsize=2097152;
        $format=array('image/jpeg');
    if($_FILES['file_upload']['size']>=$maxsize){
        $error_1='File Size too large';
        echo '<script>alert("'.$error_1.'")</script>';
    }
    elseif($_FILES['file_upload']['size']==0){
        $error_2='Invalid File';
        echo '<script>alert("'.$error_2.'")</script>';
    }
    elseif(!in_array($_FILES['file_upload']['type'],$format)){
        $error_3='Format Not Supported.Only .jpeg files are accepted';
        echo '<script>alert("'.$error_3.'")</script>';
        }

        else{
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
            if(move_uploaded_file($_FILES["file_upload"]["tmp_name"], $target_file)){ 
            echo "The file ". basename($_FILES["file_upload"]["name"]). " has been uploaded.";
            }
            else{
                echo "sorry";
                }
            }
    }
?>

Set variable in jinja

{{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

Result:

it worked

Simple and fast method to compare images for similarity

I face the same issues recently, to solve this problem(simple and fast algorithm to compare two images) once and for all, I contribute an img_hash module to opencv_contrib, you can find the details from this link.

img_hash module provide six image hash algorithms, quite easy to use.

Codes example

origin lenaorigin lena

blur lenablur lena

resize lenaresize lena

shift lenashift lena

#include <opencv2/core.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/img_hash.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

void compute(cv::Ptr<cv::img_hash::ImgHashBase> algo)
{
    auto input = cv::imread("lena.png");
    cv::Mat similar_img;

    //detect similiar image after blur attack
    cv::GaussianBlur(input, similar_img, {7,7}, 2, 2);
    cv::imwrite("lena_blur.png", similar_img);
    cv::Mat hash_input, hash_similar;
    algo->compute(input, hash_input);
    algo->compute(similar_img, hash_similar);
    std::cout<<"gaussian blur attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after shift attack
    similar_img.setTo(0);
    input(cv::Rect(0,10, input.cols,input.rows-10)).
            copyTo(similar_img(cv::Rect(0,0,input.cols,input.rows-10)));
    cv::imwrite("lena_shift.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"shift attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after resize
    cv::resize(input, similar_img, {120, 40});
    cv::imwrite("lena_resize.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"resize attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;
}

int main()
{
    using namespace cv::img_hash;

    //disable opencl acceleration may(or may not) boost up speed of img_hash
    cv::ocl::setUseOpenCL(false);

    //if the value after compare <= 8, that means the images
    //very similar to each other
    compute(ColorMomentHash::create());

    //there are other algorithms you can try out
    //every algorithms have their pros and cons
    compute(AverageHash::create());
    compute(PHash::create());
    compute(MarrHildrethHash::create());
    compute(RadialVarianceHash::create());
    //BlockMeanHash support mode 0 and mode 1, they associate to
    //mode 1 and mode 2 of PHash library
    compute(BlockMeanHash::create(0));
    compute(BlockMeanHash::create(1));
}

In this case, ColorMomentHash give us best result

  • gaussian blur attack : 0.567521
  • shift attack : 0.229728
  • resize attack : 0.229358

Pros and cons of each algorithm

Performance under different attacks

The performance of img_hash is good too

Speed comparison with PHash library(100 images from ukbench) compute performance comparison performance

If you want to know the recommend thresholds for these algorithms, please check this post(http://qtandopencv.blogspot.my/2016/06/introduction-to-image-hash-module-of.html). If you are interesting about how do I measure the performance of img_hash modules(include speed and different attacks), please check this link(http://qtandopencv.blogspot.my/2016/06/speed-up-image-hashing-of-opencvimghash.html).

Loading existing .html file with android WebView

You could read the html file manually and then use loadData or loadDataWithBaseUrl methods of WebView to show it.

Xcode 5 and iOS 7: Architecture and Valid architectures

My understanding from Apple Docs.

  • What is Architectures (ARCHS) into Xcode build-settings?
    • Specifies architecture/s to which the binary is TARGETED. When specified more that one architecture, the generated binary may contain object code for each of the specified architecture.
  • What is Valid Architectures (VALID_ARCHS) into Xcode build-settings?

    • Specifies architecture/s for which the binary may be BUILT.
    • During build process, this list is intersected with ARCHS and the resulting list specifies the architectures the binary can run on.
  • Example :- One iOS project has following build-settings into Xcode.

    • ARCHS = armv7 armv7s
    • VALID_ARCHS = armv7 armv7s arm64
    • In this case, binary will be built for armv7 armv7s arm64 architectures. But the same binary will run on ONLY ARCHS = armv7 armv7s.

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

How do I clone a single branch in Git?

There are primarily 2 solutions for this:

  1. You need to specify the branch name with -b command switch. Here is the syntax of the command to clone the specific git branch.

    git clone -b <BRANCH_NAME> <GIT_REMOTE_URL>
    

    Example:

    git clone -b tahir https://github.com/Repository/Project.git
    

    The following command will clone the branch tahir from the git repository.The above command clones only the specific branch but fetches the details of other branches. You can view all branches details with command.

    git branch -a
    
  2. You can use --single-branch flag to prevent fetching details of other branches like below:

    git clone -b <BRANCH_NAME> --single-branch <GIT_REMOTE_URL>
    

    Example:

    git clone -b tahir --single-branch \ 
    https://github.com/Repository/Project.git
    

    Now if you do a git branch -a, it will only show your current single branch that you have cloned and not all the branches. So it depends on you how you want it.

How to escape a while loop in C#

Use break; to escape the first loop:

if (s.Contains("mp4:production/CATCHUP/"))
{
   RemoveEXELog();
   Process p = new Process();
   p.StartInfo.WorkingDirectory = "dump";
   p.StartInfo.FileName = "test.exe"; 
   p.StartInfo.Arguments = s; 
   p.Start();
   break;
}

If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:

        boolean breakFlag = false;
        while (!breakFlag)
        {
            Thread.Sleep(5000);
            if (!System.IO.File.Exists("Command.bat")) continue;
            using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("mp4:production/CATCHUP/"))
                    {

                        RemoveEXELog();

                        Process p = new Process();
                        p.StartInfo.WorkingDirectory = "dump";
                        p.StartInfo.FileName = "test.exe"; 
                        p.StartInfo.Arguments = s; 
                        p.Start();

                        breakFlag = true;
                        break;
                    }
                }
            }

Or, if you want to just exit the function completely from within the nested loop, put in a return; instead of a break;.

But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while guards.

How to run a stored procedure in oracle sql developer?

-- If no parameters need to be passed to a procedure, simply:

BEGIN
   MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;

Twitter Bootstrap 3: how to use media queries?

Bootstrap 3

Here are the selectors used in BS3, if you want to stay consistent:

@media(max-width:767px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Note: FYI, this may be useful for debugging:

<span class="visible-xs">SIZE XS</span>
<span class="visible-sm">SIZE SM</span>
<span class="visible-md">SIZE MD</span>
<span class="visible-lg">SIZE LG</span>

Bootstrap 4

Here are the selectors used in BS4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.

@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Update 2019-02-11: BS3 info is still accurate as of version 3.4.0, updated BS4 for new grid, accurate as of 4.3.0.

Get a list of all functions and procedures in an Oracle database

SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')

The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.

Java Program to test if a character is uppercase/lowercase/number/vowel

If it weren't a homework, you could use existing methods such as Character.isDigit(char), Character.isUpperCase(char) and Character.isLowerCase(char) which are a bit "smarter", because they don't operate only in ASCII, but also in various charsets.

static final char[] VOWELS = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };

static boolean isVowel(char ch) {
    for (char vowel : VOWELS) {
        if (vowel == ch) {
            return true;
        }
    }
    return false;
}

static boolean isDigit(char ch) {
    return ch >= '0' && ch <= '9';
}

static boolean isLowerCase(char ch) {
    return ch >= 'a' && ch <= 'z';
}

static boolean isUpperCase(char ch) {
    return ch >= 'A' && ch <= 'Z';
}

android: how to align image in the horizontal center of an imageview?

You can center the ImageView itself by using:

android:layout_centerVertical="true" or android:layout_centerHorizontal="true" For vertical or horizontal. Or to center inside the parent:

android:layout_centerInParent="true"

But it sounds like you are trying to center the actual source image inside the imageview itself, which I am not sure on.

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

How to set corner radius of imageView?

Swift 3, Xcode 8, iOS 10

DispatchQueue.main.async {
  self.mainImageView.layer.cornerRadius = self.mainImageView.bounds.size.width / 2.0
  self.mainImageView.clipsToBounds = true
}

HTML list-style-type dash

In my case adding this code to CSS

ul {
    list-style-type: '- ';
}

was enough. Simple as it is.

Why is 2 * (i * i) faster than 2 * i * i in Java?

I tried a JMH using the default archetype: I also added an optimized version based on Runemoro's explanation.

@State(Scope.Benchmark)
@Warmup(iterations = 2)
@Fork(1)
@Measurement(iterations = 10)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
//@BenchmarkMode({ Mode.All })
@BenchmarkMode(Mode.AverageTime)
public class MyBenchmark {
  @Param({ "100", "1000", "1000000000" })
  private int size;

  @Benchmark
  public int two_square_i() {
    int n = 0;
    for (int i = 0; i < size; i++) {
      n += 2 * (i * i);
    }
    return n;
  }

  @Benchmark
  public int square_i_two() {
    int n = 0;
    for (int i = 0; i < size; i++) {
      n += i * i;
    }
    return 2*n;
  }

  @Benchmark
  public int two_i_() {
    int n = 0;
    for (int i = 0; i < size; i++) {
      n += 2 * i * i;
    }
    return n;
  }
}

The result are here:

Benchmark                           (size)  Mode  Samples          Score   Score error  Units
o.s.MyBenchmark.square_i_two           100  avgt       10         58,062         1,410  ns/op
o.s.MyBenchmark.square_i_two          1000  avgt       10        547,393        12,851  ns/op
o.s.MyBenchmark.square_i_two    1000000000  avgt       10  540343681,267  16795210,324  ns/op
o.s.MyBenchmark.two_i_                 100  avgt       10         87,491         2,004  ns/op
o.s.MyBenchmark.two_i_                1000  avgt       10       1015,388        30,313  ns/op
o.s.MyBenchmark.two_i_          1000000000  avgt       10  967100076,600  24929570,556  ns/op
o.s.MyBenchmark.two_square_i           100  avgt       10         70,715         2,107  ns/op
o.s.MyBenchmark.two_square_i          1000  avgt       10        686,977        24,613  ns/op
o.s.MyBenchmark.two_square_i    1000000000  avgt       10  652736811,450  27015580,488  ns/op

On my PC (Core i7 860 - it is doing nothing much apart from reading on my smartphone):

  • n += i*i then n*2 is first
  • 2 * (i * i) is second.

The JVM is clearly not optimizing the same way than a human does (based on Runemoro's answer).

Now then, reading bytecode: javap -c -v ./target/classes/org/sample/MyBenchmark.class

I am not expert on bytecode, but we iload_2 before we imul: that's probably where you get the difference: I can suppose that the JVM optimize reading i twice (i is already here, and there is no need to load it again) whilst in the 2*i*i it can't.

How to tell if a JavaScript function is defined

Try this:

callback instanceof Function

Git workflow and rebase vs merge questions

I have one question after reading your explanation: Could it be that you never did a

git checkout master
git pull origin
git checkout my_new_feature

before doing the 'git rebase/merge master' in your feature branch?

Because your master branch won't update automatically from your friend's repository. You have to do that with the git pull origin. I.e. maybe you would always rebase from a never-changing local master branch? And then come push time, you are pushing in a repository which has (local) commits you never saw and thus the push fails.

How to loop and render elements in React.js without an array of objects to map?

I'm using Object.keys(chars).map(...) to loop in render

// chars = {a:true, b:false, ..., z:false}

render() {
    return (
       <div>
        {chars && Object.keys(chars).map(function(char, idx) {
            return <span key={idx}>{char}</span>;
        }.bind(this))}
        "Some text value"
       </div>
    );
}

Not Equal to This OR That in Lua

Your problem stems from a misunderstanding of the or operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1, but I'll go into a little more detail about why your attempted solution doesn't work.

When you read x ~=(0 or 1) or x ~= 0 or 1 it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.

However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or has a lower precedence than ~=, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.

As a result, when evaluating x ~=(0 or 1), the interpreter will first compute 0 or 1 (because of the parentheses) and then x ~= the result of the first computation, and in the second example, it will compute x ~= 0 and then apply the result of that computation to or 1.

The logical operator or "returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~= is the inverse of the equality operator ==; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.

Using these rules, x ~=(0 or 1) will decompose to x ~= 0 (after applying the or operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1 will first evaluate x ~= 0 (which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1 or true or 1. In the first case, the statement will return 1, and in the second case, the statement will return true. Because control structures in Lua only consider nil and false to be false, and anything else to be true, this will always enter the if statement, which is not what you want either.

There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:

if x ~= 1 and x ~= 0 then
    print( "X must be equal to 1 or 0" )
    return
end

Alternatively, you can use a loop to check these values:

local x_is_ok = false
for i = 0,1 do 
    if x == i then
        x_is_ok = true
    end
end
if not x_is_ok then
    print( "X must be equal to 1 or 0" )
    return
end

Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)

if not (x >= 0 and x <= 1 and math.floor(x) == x) then
    print( "X must be equal to 1 or 0" )
    return
end

Note that I wrote x >= 0 and x <= 1. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1, and what this erroneous expression would return!

Excel Reference To Current Cell

A2 is already a relative reference and will change when you move the cell or copy the formula.

Display UIViewController as Popup in iPhone

NOTE : This solution is broken in iOS 8. I will post new solution ASAP.

I am going to answer here using storyboard but it is also possible without storyboard.

  1. Init: Create two UIViewController in storyboard.

    • lets say FirstViewController which is normal and SecondViewController which will be the popup.

  2. Modal Segue: Put UIButton in FirstViewController and create a segue on this UIButton to SecondViewController as modal segue.

  3. Make Transparent: Now select UIView (UIView Which is created by default with UIViewController) of SecondViewController and change its background color to clear color.

  4. Make background Dim: Add an UIImageView in SecondViewController which covers whole screen and sets its image to some dimmed semi transparent image. You can get a sample from here : UIAlertView Background Image

  5. Display Design: Now add an UIView and make any kind of design you want to show. Here is a screenshot of my storyboard storyboard

    • Here I have add segue on login button which open SecondViewController as popup to ask username and password
  6. Important: Now that main step. We want that SecondViewController doesn't hide FirstViewController completely. We have set clear color but this is not enough. By default it adds black behind model presentation so we have to add one line of code in viewDidLoad of FirstViewController. You can add it at another place also but it should run before segue.

    [self setModalPresentationStyle:UIModalPresentationCurrentContext];

  7. Dismiss: When to dismiss depends on your use case. This is a modal presentation so to dismiss we do what we do for modal presentation:

    [self dismissViewControllerAnimated:YES completion:Nil];

Thats all.....

Any kind of suggestion and comment are welcome.

Demo : You can get demo source project from Here : Popup Demo

NEW : Someone have done very nice job on this concept : MZFormSheetController
New : I found one more code to get this kind of function : KLCPopup


iOS 8 Update : I made this method to work with both iOS 7 and iOS 8

+ (void)setPresentationStyleForSelfController:(UIViewController *)selfController presentingController:(UIViewController *)presentingController
{
    if (iOSVersion >= 8.0)
    {
        presentingController.providesPresentationContextTransitionStyle = YES;
        presentingController.definesPresentationContext = YES;

        [presentingController setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    }
    else
    {
        [selfController setModalPresentationStyle:UIModalPresentationCurrentContext];
        [selfController.navigationController setModalPresentationStyle:UIModalPresentationCurrentContext];
    }
}

Can use this method inside prepareForSegue deligate like this

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    PopUpViewController *popup = segue.destinationViewController;
    [self setPresentationStyleForSelfController:self presentingController:popup]
}

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

Java JTable setting Column Width

With JTable.AUTO_RESIZE_OFF, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth() instead of TableColumn.setPreferredWidth() for all but the last column.

Once you are satisfied that AUTO_RESIZE_LAST_COLUMN does in fact work, you can experiment with a combination of TableColumn.setMaxWidth() and TableColumn.setMinWidth()

INNER JOIN same table

I don't know how the table is created but try this...

SELECT users1.user_id, users2.user_parent_id
FROM users AS users1
INNER JOIN users AS users2
ON users1.id = users2.id
WHERE users1.user_id = users2.user_parent_id

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

The problem is also identified in your status bar at the bottom:

overwrite label in status bar

You are in overwrite mode instead of insert mode.

The “Insert” key toggles between insert and overwrite modes.

Server.Mappath in C# classlibrary

You can get the base path by using the following code and append your needed path with that.

string  path = System.AppDomain.CurrentDomain.BaseDirectory;

What to use now Google News API is deprecated?

Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431

Also, it sounds like they are building a replacement... but it's going to cost you.

I'd say, go to a different service. I think bing has a news API.

You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625

Printing the last column of a line in a file

You can do this without awk with just some pipes.

tac file | grep -m1 A1 | rev | cut -d' ' -f1 | rev

How to check for an undefined or null variable in JavaScript?

You can just check if the variable has a value or not. Meaning,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}

How to list files inside a folder with SQL Server

If you want you can achieve this using a CLR Function/Assembly.

  1. Create a SQL Server CLR Assembly Project.
  2. Go to properties and ensure the permission level on the Connection is setup to external
  3. Add A Sql Function to the Assembly.

Here's an example which will allow you to select form your result set like a table.

public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read,
        FillRowMethodName = "GetFiles_FillRow", TableDefinition = "FilePath nvarchar(4000)")]
    public static IEnumerable GetFiles(SqlString path)
    {
        return System.IO.Directory.GetFiles(path.ToString()).Select(s => new SqlString(s));
    }

    public static void GetFiles_FillRow(object obj,out SqlString filePath)
    {
        filePath = (SqlString)obj;
    }
};

And your SQL query.

use MyDb

select * From GetFiles('C:\Temp\');

Be aware though, your database needs to have CLR Assembly functionaliy enabled using the following SQL Command.

sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

CLR Assemblies (like XP_CMDShell) are disabled by default so if the reason for not using XP Cmd Shell is because you don't have permission, then you may be stuck with this option as well... just FYI.

How to connect to SQL Server from another computer?

I'll edit my previous answer based on further info supplied. You can clearely ping the remote computer as you can use terminal services.

I've a feeling that port 1433 is being blocked by a firewall, hence your trouble. See TCP Ports Needed for Communication to SQL Server Through a Firewall by Microsoft.

Try using this application to ping your servers ip address and port 1433.

tcping your.server.ip.address 1433

And see if you get a "Port is open" response from tcping.

Ok, next to try is to check SQL Server. RDP onto the SQL Server computer. Start SSMS. Connect to the database. In object explorer (usually docked on the left) right click on the server and click properties.

alt text http://www.hicrest.net/server_prop_menu.jpg

Goto the Connections settings and make sure "Allow remote connections to this server" is ticket.

alt text http://www.hicrest.net/server_properties.jpg

BehaviorSubject vs Observable?

Observable: Different result for each Observer

One very very important difference. Since Observable is just a function, it does not have any state, so for every new Observer, it executes the observable create code again and again. This results in:

The code is run for each observer . If its a HTTP call, it gets called for each observer

This causes major bugs and inefficiencies

BehaviorSubject (or Subject ) stores observer details, runs the code only once and gives the result to all observers .

Ex:

JSBin: http://jsbin.com/qowulet/edit?js,console

_x000D_
_x000D_
// --- Observable ---_x000D_
let randomNumGenerator1 = Rx.Observable.create(observer => {_x000D_
   observer.next(Math.random());_x000D_
});_x000D_
_x000D_
let observer1 = randomNumGenerator1_x000D_
      .subscribe(num => console.log('observer 1: '+ num));_x000D_
_x000D_
let observer2 = randomNumGenerator1_x000D_
      .subscribe(num => console.log('observer 2: '+ num));_x000D_
_x000D_
_x000D_
// ------ BehaviorSubject/ Subject_x000D_
_x000D_
let randomNumGenerator2 = new Rx.BehaviorSubject(0);_x000D_
randomNumGenerator2.next(Math.random());_x000D_
_x000D_
let observer1Subject = randomNumGenerator2_x000D_
      .subscribe(num=> console.log('observer subject 1: '+ num));_x000D_
      _x000D_
let observer2Subject = randomNumGenerator2_x000D_
      .subscribe(num=> console.log('observer subject 2: '+ num));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.3/Rx.min.js"></script>
_x000D_
_x000D_
_x000D_

Output :

"observer 1: 0.7184075243594013"
"observer 2: 0.41271850211336103"
"observer subject 1: 0.8034263165479893"
"observer subject 2: 0.8034263165479893"

Observe how using Observable.create created different output for each observer, but BehaviorSubject gave the same output for all observers. This is important.


Other differences summarized.

?????????????????????????????????????????????????????????????????????????????
?         Observable                  ?     BehaviorSubject/Subject         ?      
????????????????????????????????????????????????????????????????????????????? 
? Is just a function, no state        ? Has state. Stores data in memory    ?
?????????????????????????????????????????????????????????????????????????????
? Code run for each observer          ? Same code run                       ?
?                                     ? only once for all observers         ?
?????????????????????????????????????????????????????????????????????????????
? Creates only Observable             ?Can create and also listen Observable?
? ( data producer alone )             ? ( data producer and consumer )      ?
?????????????????????????????????????????????????????????????????????????????
? Usage: Simple Observable with only  ? Usage:                              ?
? one Obeserver.                      ? * Store data and modify frequently  ?
?                                     ? * Multiple observers listen to data ?
?                                     ? * Proxy between Observable  and     ?
?                                     ?   Observer                          ?
?????????????????????????????????????????????????????????????????????????????

How to reset sequence in postgres and fill id column with new data?

To retain order of the rows:

UPDATE thetable SET rowid=col_serial FROM 
(SELECT rowid, row_number() OVER ( ORDER BY lngid) AS col_serial FROM thetable ORDER BY lngid) AS t1 
WHERE thetable.rowid=t1.rowid;

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

Paste multiple columns together

In my opinion the sprintf-function deserves a place among these answers as well. You can use sprintf as follows:

do.call(sprintf, c(d[cols], '%s-%s-%s'))

which gives:

 [1] "a-d-g" "b-e-h" "c-f-i"

And to create the required dataframe:

data.frame(a = d$a, x = do.call(sprintf, c(d[cols], '%s-%s-%s')))

giving:

  a     x
1 1 a-d-g
2 2 b-e-h
3 3 c-f-i

Although sprintf doesn't have a clear advantage over the do.call/paste combination of @BrianDiggs, it is especially usefull when you also want to pad certain parts of desired string or when you want to specify the number of digit. See ?sprintf for the several options.

Another variant would be to use pmap from :

pmap(d[2:4], paste, sep = '-')

Note: this pmap solution only works when the columns aren't factors.


A benchmark on a larger dataset:

# create a larger dataset
d2 <- d[sample(1:3,1e6,TRUE),]
# benchmark
library(microbenchmark)
microbenchmark(
  docp = do.call(paste, c(d2[cols], sep="-")),
  appl = apply( d2[, cols ] , 1 , paste , collapse = "-" ),
  tidr = tidyr::unite_(d2, "x", cols, sep="-")$x,
  docs = do.call(sprintf, c(d2[cols], '%s-%s-%s')),
  times=10)

results in:

Unit: milliseconds
 expr       min        lq      mean    median        uq       max neval cld
 docp  214.1786  226.2835  297.1487  241.6150  409.2495  493.5036    10 a  
 appl 3832.3252 4048.9320 4131.6906 4072.4235 4255.1347 4486.9787    10   c
 tidr  206.9326  216.8619  275.4556  252.1381  318.4249  407.9816    10 a  
 docs  413.9073  443.1550  490.6520  453.1635  530.1318  659.8400    10  b 

Used data:

d <- data.frame(a = 1:3, b = c('a','b','c'), c = c('d','e','f'), d = c('g','h','i')) 

Java: Why is the Date constructor deprecated, and what do I use instead?

One reason that the constructor is deprecated is that the meaning of the year parameter is not what you would expect. The javadoc says:

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date).

Notice that the year field is the number of years since 1900, so your sample code most likely won't do what you expect it to do. And that's the point.

In general, the Date API only supports the modern western calendar, has idiosyncratically specified components, and behaves inconsistently if you set fields.

The Calendar and GregorianCalendar APIs are better than Date, and the 3rd-party Joda-time APIs were generally thought to be the best. In Java 8, they introduced the java.time packages, and these are now the recommended alternative.

AngularJS : Why ng-bind is better than {{}} in angular?

According to Angular Doc:
Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading... it's the main difference...

Basically until every dom elements not loaded, we can not see them and because ngBind is attribute on the element, it waits until the doms come into play... more info below

ngBind
- directive in module ng

The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

Typically, you don't use ngBind directly, but instead you use the double curly markup like {{ expression }} which is similar but less verbose.

It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before AngularJS compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

An alternative solution to this problem would be using the ngCloak directive. visit here

for more info about the ngbind visit this page: https://docs.angularjs.org/api/ng/directive/ngBind

You could do something like this as attribute, ng-bind:

<div ng-bind="my.name"></div>

or do interpolation as below:

<div>{{my.name}}</div>

or this way with ng-cloak attributes in AngularJs:

<div id="my-name" ng-cloak>{{my.name}}</div>

ng-cloak avoid flashing on the dom and wait until all be ready! this is equal to ng-bind attribute...

C# static class why use?

Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

How do you add multi-line text to a UIButton?

I had an issue with auto-layout, after enabling multi-line the result was like this:
enter image description here
so the titleLabel size doesn't affect the button size
I've added Constraints based on contentEdgeInsets (in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport():
enter image description here
hope it helps you (swift 5.0):

extension UIButton {

    func makeMultiLineSupport() {
        guard let titleLabel = titleLabel else {
            return
        }
        titleLabel.numberOfLines = 0
        titleLabel.setContentHuggingPriority(.required, for: .vertical)
        titleLabel.setContentHuggingPriority(.required, for: .horizontal)
        addConstraints([
            .init(item: titleLabel,
                  attribute: .top,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .top,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.top),
            .init(item: titleLabel,
                  attribute: .bottom,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .bottom,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.bottom),
            .init(item: titleLabel,
                  attribute: .left,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .left,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.left),
            .init(item: titleLabel,
                  attribute: .right,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .right,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.right)
            ])
    }

}

Accessing last x characters of a string in Bash

Another workaround is to use grep -o with a little regex magic to get three chars followed by the end of line:

$ foo=1234567890
$ echo $foo | grep -o ...$
890

To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep with this regex:

$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd

You can also use different ranges, such as 5,10 to get the last five to ten chars.

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

To do it the GUI way, you need to go edit your login. One of its properties is the default database used for that login. You can find the list of logins under the Logins node under the Security node. Then select your login and right-click and pick Properties. Change the default database and your life will be better!

Note that someone with sysadmin privs needs to be able to login to do this or to run the query from the previous post.

Spring Boot application.properties value not populating

If you're working in a large multi-module project, with several different application.properties files, then try adding your value to the parent project's property file.

If you are unsure which is your parent project, check your project's pom.xml file, for a <parent> tag.

This solved the issue for me.

Get week number (in the year) from a date PHP

function last_monday($date) 
{
    if (!is_numeric($date))
        $date = strtotime($date);
    if (date('w', $date) == 1)
        return $date;
    else
        return date('Y-m-d',strtotime('last monday',$date));
}
$date = '2021-01-04';  //Enter custom date
$year = date('Y',strtotime($date));
$date1 = new DateTime($date);
$ldate = last_monday($year."-01-01");
$date2 = new DateTime($ldate);
$diff = $date2->diff($date1)->format("%a");
$diff = $diff/7;
$week = intval($diff) + 1;
echo $week;
//Returns 2.

How to check if a String contains any letter from a to z?

You can look for regular expression

Regex.IsMatch(str, @"^[a-zA-Z]+$");

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

Log record changes in SQL server in an audit table

This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.

ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
           DECLARE @bit            INT,
                   @field          INT,
                   @maxfield       INT,
                   @char           INT,
                   @fieldname      VARCHAR(128),
                   @TableName      VARCHAR(128),
                   @PKCols         VARCHAR(1000),
                   @sql            VARCHAR(2000),
                   @UpdateDate     VARCHAR(21),
                   @UserName       VARCHAR(128),
                   @Type           CHAR(1),
                   @PKSelect       VARCHAR(1000)


           --You will need to change @TableName to match the table to be audited.
           -- Here we made GUESTS for your example.
           SELECT @TableName = 'PERSON'

           SELECT @UserName = SYSTEM_USER,
                  @UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)

           -- Action
           IF EXISTS (
                  SELECT *
                  FROM   INSERTED
              )
               IF EXISTS (
                      SELECT *
                      FROM   DELETED
                  )
                   SELECT @Type = 'U'
               ELSE
                   SELECT @Type = 'I'
           ELSE
               SELECT @Type = 'D'

           -- get list of columns
           SELECT * INTO #ins
           FROM   INSERTED

           SELECT * INTO #del
           FROM   DELETED

           -- Get primary key columns for full outer join
           SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                  + ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           -- Get primary key select for insert
           SELECT @PKSelect = COALESCE(@PKSelect + '+', '') 
                  + '''<[' + COLUMN_NAME 
                  + ']=''+convert(varchar(100),
           coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           IF @PKCols IS NULL
           BEGIN
               RAISERROR('no PK on table %s', 16, -1, @TableName)

               RETURN
           END

           SELECT @field = 0,
                  -- @maxfield = MAX(COLUMN_NAME) 
                  @maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName


                  MAX(
                      COLUMNPROPERTY(
                          OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                          COLUMN_NAME,
                          'ColumnID'
                      )
                  )
           FROM   INFORMATION_SCHEMA.COLUMNS
           WHERE  TABLE_NAME = @TableName






           WHILE @field < @maxfield
           BEGIN
               SELECT @field = MIN(
                          COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          )
                      )
               FROM   INFORMATION_SCHEMA.COLUMNS
               WHERE  TABLE_NAME = @TableName
                      AND COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          ) > @field

               SELECT @bit = (@field - 1)% 8 + 1

               SELECT @bit = POWER(2, @bit - 1)

               SELECT @char = ((@field - 1) / 8) + 1





               IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
                  OR @Type IN ('I', 'D')
               BEGIN
                   SELECT @fieldname = COLUMN_NAME
                   FROM   INFORMATION_SCHEMA.COLUMNS
                   WHERE  TABLE_NAME = @TableName
                          AND COLUMNPROPERTY(
                                  OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                                  COLUMN_NAME,
                                  'ColumnID'
                              ) = @field



                   SELECT @sql = 
                          '
           insert into Audit (    Type, 
           TableName, 
           PK, 
           FieldName, 
           OldValue, 
           NewValue, 
           UpdateDate, 
           UserName)
           select ''' + @Type + ''',''' 
                          + @TableName + ''',' + @PKSelect
                          + ',''' + @fieldname + ''''
                          + ',convert(varchar(1000),d.' + @fieldname + ')'
                          + ',convert(varchar(1000),i.' + @fieldname + ')'
                          + ',''' + @UpdateDate + ''''
                          + ',''' + @UserName + ''''
                          + ' from #ins i full outer join #del d'
                          + @PKCols
                          + ' where i.' + @fieldname + ' <> d.' + @fieldname 
                          + ' or (i.' + @fieldname + ' is null and  d.'
                          + @fieldname
                          + ' is not null)' 
                          + ' or (i.' + @fieldname + ' is not null and  d.' 
                          + @fieldname
                          + ' is null)' 



                   EXEC (@sql)
               END
           END

What does "static" mean in C?

A static variable is a special variable that you can use in a function, and it saves the data between calls, and it does not delete it between calls. For example:

void func(void) {
    static int count; // If you don't declare its value, it is initialized with zero
    printf("%d, ", count);
    ++count;
}

int main(void) {
    while(true) {
        func();
    }
    return 0;
}

The output:

0, 1, 2, 3, 4, 5, ...

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

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a <frame> or <iframe>
  • window.top refers to the top-most window from a window nested in one or more layers of <iframe> sub-windows

Those will be null (or maybe undefined) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)

When is null or undefined used in JavaScript?

You get undefined for the various scenarios:

You declare a variable with var but never set it.

var foo; 
alert(foo); //undefined.

You attempt to access a property on an object you've never set.

var foo = {};
alert(foo.bar); //undefined

You attempt to access an argument that was never provided.

function myFunction (foo) {
  alert(foo); //undefined.
}

As cwolves pointed out in a comment on another answer, functions that don't return a value.

function myFunction () {
}
alert(myFunction());//undefined

A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object and undefined is of type undefined.

I should also note that null is valid in JSON but undefined is not:

JSON.parse(undefined); //syntax error
JSON.parse(null); //null

How to prevent a background process from being stopped after closing SSH client in Linux

I would recommend using GNU Screen. It allows you to disconnect from the server while all of your processes continue to run. I don't know how I lived without it before I knew it existed.

Counting Chars in EditText Changed Listener

Use

s.length()

The following was once suggested in one of the answers, but its very inefficient

textMessage.getText().toString().length()

Load and execution sequence of a web page?

1) HTML is downloaded.

2) HTML is parsed progressively. When a request for an asset is reached the browser will attempt to download the asset. A default configuration for most HTTP servers and most browsers is to process only two requests in parallel. IE can be reconfigured to downloaded an unlimited number of assets in parallel. Steve Souders has been able to download over 100 requests in parallel on IE. The exception is that script requests block parallel asset requests in IE. This is why it is highly suggested to put all JavaScript in external JavaScript files and put the request just prior to the closing body tag in the HTML.

3) Once the HTML is parsed the DOM is rendered. CSS is rendered in parallel to the rendering of the DOM in nearly all user agents. As a result it is strongly recommended to put all CSS code into external CSS files that are requested as high as possible in the <head></head> section of the document. Otherwise the page is rendered up to the occurance of the CSS request position in the DOM and then rendering starts over from the top.

4) Only after the DOM is completely rendered and requests for all assets in the page are either resolved or time out does JavaScript execute from the onload event. IE7, and I am not sure about IE8, does not time out assets quickly if an HTTP response is not received from the asset request. This means an asset requested by JavaScript inline to the page, that is JavaScript written into HTML tags that is not contained in a function, can prevent the execution of the onload event for hours. This problem can be triggered if such inline code exists in the page and fails to execute due to a namespace collision that causes a code crash.

Of the above steps the one that is most CPU intensive is the parsing of the DOM/CSS. If you want your page to be processed faster then write efficient CSS by eliminating redundent instructions and consolidating CSS instructions into the fewest possible element referrences. Reducing the number of nodes in your DOM tree will also produce faster rendering.

Keep in mind that each asset you request from your HTML or even from your CSS/JavaScript assets is requested with a separate HTTP header. This consumes bandwidth and requires processing per request. If you want to make your page load as fast as possible then reduce the number of HTTP requests and reduce the size of your HTML. You are not doing your user experience any favors by averaging page weight at 180k from HTML alone. Many developers subscribe to some fallacy that a user makes up their mind about the quality of content on the page in 6 nanoseconds and then purges the DNS query from his server and burns his computer if displeased, so instead they provide the most beautiful possible page at 250k of HTML. Keep your HTML short and sweet so that a user can load your pages faster. Nothing improves the user experience like a fast and responsive web page.

How to use goto statement correctly

goto doesn't do anything in Java.

XPath OR operator for different nodes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

Can I bind an array to an IN() condition?

As I know there is no any possibility to bind an array into PDO statement.

But exists 2 common solutions:

  1. Use Positional Placeholders (?,?,?,?) or Named Placeholders (:id1, :id2, :id3)

    $whereIn = implode(',', array_fill(0, count($ids), '?'));

  2. Quote array earlier

    $whereIn = array_map(array($db, 'quote'), $ids);

Both options are good and safe. I prefer second one because it's shorter and I can var_dump parameters if I need it. Using placeholders you must bind values and in the end your SQL code will be the same.

$sql = "SELECT * FROM table WHERE id IN ($whereIn)";

And the last and important for me is avoiding error "number of bound variables does not match number of tokens"

Doctrine it's great example of using positional placeholders, only because it has internal control over incoming parameters.

Scroll Automatically to the Bottom of the Page

Late to the party, but here's some simple javascript-only code to scroll any element to the bottom:

function scrollToBottom(e) {
  e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}

How to use the ProGuard in Android Studio?

Here is Some of Most Common Proguard Rules that you need to add in proguard-rules.pro file in Android Sutdio.

ButterKnife

 -keep class butterknife.** { *; }
 -dontwarn butterknife.internal.**
 -keep class **$$ViewBinder { *; }
 -keepclasseswithmembernames class * {
        @butterknife.* <fields>;
  }
 -keepclasseswithmembernames class * {
        @butterknife.* <methods>;
  }

Retrofit

 -dontwarn retrofit.**
 -keep class retrofit.** { *; }
 -keepattributes Signature
 -keepattributes Exceptions

OkHttp3

 -keepattributes Signature
 -keepattributes *Annotation*
 -keep class okhttp3.** { *; }
 -keep interface okhttp3.** { *; }
 -dontwarn okhttp3.** 
 -keep class sun.misc.Unsafe { *; }
 -dontwarn java.nio.file.*
 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 

Gson

 -keep class sun.misc.Unsafe { *; }
 -keep class com.google.gson.stream.** { *; }

Code obfuscation

-keepclassmembers class com.yourname.models** { <fields>; }

How to check if IEnumerable is null or empty?

Since some resources are exhausted after one read, I thought why not combine the checks and the reads, instead of the traditional separate check, then read.

First we have one for the simpler check-for-null inline extension:

public static System.Collections.Generic.IEnumerable<T> ThrowOnNull<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null) => source ?? throw new System.ArgumentNullException(paramName ?? nameof(source));

var first = source.ThrowOnNull().First();

Then we have the little more involved (well, at least the way I wrote it) check-for-null-and-empty inline extension:

public static System.Collections.Generic.IEnumerable<T> ThrowOnNullOrEmpty<T>(this System.Collections.Generic.IEnumerable<T> source, string paramName = null)
{
  using (var e = source.ThrowOnNull(paramName).GetEnumerator())
  {
    if (!e.MoveNext())
    {
      throw new System.ArgumentException(@"The sequence is empty.", paramName ?? nameof(source));
    }

    do
    {
      yield return e.Current;
    }
    while (e.MoveNext());
  }
}

var first = source.ThrowOnNullOrEmpty().First();

You can of course still call both without continuing the call chain. Also, I included the paramName, so that the caller may include an alternate name for the error if it's not "source" being checked, e.g. "nameof(target)".

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

How do I configure PyCharm to run py.test tests?

With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option --spec) (for Rspec like nice test summary language), I had to do ;

1.Edit the default py.test to include option= --spec , which means use the plugin: https://github.com/pchomik/pytest-spec

2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27 for my namings.

3.Delete the 'unittests' test configuration.

4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!

p.s. Jetbrains' doc on run/debug configs is here: https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search=py.test

The APR based Apache Tomcat Native library was not found on the java.library.path

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

CSS @media print issues with background-color;

You can use the tag canvas and "draw" the background, which work on IE9, Gecko and Webkit.

Bold & Non-Bold Text In A Single UILabel?

I've adopted Crazy Yoghurt's answer to swift's extensions.

extension UILabel {

    func boldRange(_ range: Range<String.Index>) {
        if let text = self.attributedText {
            let attr = NSMutableAttributedString(attributedString: text)
            let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
            let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
            attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
            self.attributedText = attr
        }
    }

    func boldSubstring(_ substr: String) {
        if let text = self.attributedText {
            var range = text.string.range(of: substr)
            let attr = NSMutableAttributedString(attributedString: text)
            while range != nil {
                let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
                let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
                var nsRange = NSMakeRange(start, length)
                let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
                if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
                    break
                }
                range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
            }
            if let r = range {
                boldRange(r)
            }
        }
    }
}

May be there is not good conversion between Range and NSRange, but I didn't found something better.

How to add a new column to a CSV file?

Append new column in existing csv file using python without header name

  default_text = 'Some Text'
# Open the input_file in read mode and output_file in write mode
    with open('problem-one-answer.csv', 'r') as read_obj, \
    open('output_1.csv', 'w', newline='') as write_obj:
# Create a csv.reader object from the input file object
    csv_reader = reader(read_obj)
# Create a csv.writer object from the output file object
    csv_writer = csv.writer(write_obj)
# Read each row of the input csv file as list
    for row in csv_reader:
# Append the default text in the row / list
        row.append(default_text)
# Add the updated row / list to the output file
        csv_writer.writerow(row)

Thankyou

UIBarButtonItem in navigation bar programmatically?

In Swift 3.0+, UIBarButtonItem programmatically set up as follows:

   override func viewDidLoad() {
        super.viewDidLoad()
        let testUIBarButtonItem = UIBarButtonItem(image: UIImage(named: "test.png"), style: .plain, target: self, action: #selector(self.clickButton))
        self.navigationItem.rightBarButtonItem  = testUIBarButtonItem
    }

   @objc func clickButton(){
            print("button click")
     }

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

How to change webservice url endpoint?

To add some clarification here, when you create your service, the service class uses the default 'wsdlLocation', which was inserted into it when the class was built from the wsdl. So if you have a service class called SomeService, and you create an instance like this:

SomeService someService = new SomeService();

If you look inside SomeService, you will see that the constructor looks like this:

public SomeService() {
        super(__getWsdlLocation(), SOMESERVICE_QNAME);
}

So if you want it to point to another URL, you just use the constructor that takes a URL argument (there are 6 constructors for setting qname and features as well). For example, if you have set up a local TCP/IP monitor that is listening on port 9999, and you want to redirect to that URL:

URL newWsdlLocation = new URL("http://theServerName:9999/somePath");
SomeService someService = new SomeService(newWsdlLocation);

and that will call this constructor inside the service:

public SomeService(URL wsdlLocation) {
    super(wsdlLocation, SOMESERVICE_QNAME);
}

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

To enable disable Wifi use the WifiManager class to get system(android device) services for Wifi :

WifiManager wifi =(WifiManager)getSystemService(Context.WIFI_SERVICE); 

Now the object wifi of the WifiManager class is used to get the wifi status:

if(wifi.isWifiEnabled())
    //Perform Operation
else
    //Other Operation

And most importantly do not forget to give the following permission in your Android Manifest File:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

To get detailed info and full sample code of the project for enable/disable Wifi on android visit my website link.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

HTTPS connection Python

Why haven't you tried httplib.HTTPSConnection? It doesn't do SSL validation but this isn't required to connect over https. Your code works fine with https connection:

>>> import httplib
>>> conn = httplib.HTTPSConnection("mail.google.com")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK

Get a Windows Forms control by name in C#

Use the Control.ControlCollection.Find method.

Try this:

this.Controls.Find()

Border around specific rows in a table?

How about tr {outline: thin solid black;}? Works for me on tr or tbody elements, and appears to be compatible with the most browsers, including IE 8+ but not before.

How an 'if (A && B)' statement is evaluated?

In C and C++, the && and || operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to && is false, or the first to || is true, the rest will not be evaluated.

The code you posted is safe, though I question why you'd include an empty else block.

How to create a md5 hash of a string in C?

I don't know this particular library, but I've used very similar calls. So this is my best guess:

unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);

This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string.

char md5string[33];
for(int i = 0; i < 16; ++i)
    sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

CSS3 transitions inside jQuery .css()

Step 1) Remove the semi-colon, it's an object you're creating...

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out';
});

to

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out'
});

Step 2) Vendor-prefixes... no browsers use transition since it's the standard and this is an experimental feature even in the latest browsers:

a(this).next().css({
    left             : c,
    WebkitTransition : 'opacity 1s ease-in-out',
    MozTransition    : 'opacity 1s ease-in-out',
    MsTransition     : 'opacity 1s ease-in-out',
    OTransition      : 'opacity 1s ease-in-out',
    transition       : 'opacity 1s ease-in-out'
});

Here is a demo: http://jsfiddle.net/83FsJ/

Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:

$('a').on('click', function () {
    var myTransition = ($.browser.webkit)  ? '-webkit-transition' :
                       ($.browser.mozilla) ? '-moz-transition' : 
                       ($.browser.msie)    ? '-ms-transition' :
                       ($.browser.opera)   ? '-o-transition' : 'transition',
        myCSSObj     = { opacity : 1 };

    myCSSObj[myTransition] = 'opacity 1s ease-in-out';
    $(this).next().css(myCSSObj);
});?

Here is a demo: http://jsfiddle.net/83FsJ/1/

Also note that if you specify in your transition declaration that the property to animate is opacity, setting a left property won't be animated.

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

WAMP/XAMPP is responding very slow over localhost

After try each instuction on this post, for me works when i add in:

Avira >>
Real-Time Protection >>
Configuration >>
Exception >>

Add Proccess:

  1. xampp\apache\bin\httpd.exe
  2. xampp\mysql\bin\mysqld.exe
  3. xampp\xampp-control.exe

enter image description here

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I'm astonished to see so many replies requiring coding to change a single use case (GET) in one API instead of using a proper tool what has to be installed once and can be used for any API (own or 3rd party) and all use cases.

So the good answer is:

  1. If you only want to request json or other content type install Requestly or a similar tool and modify the Accept header.
  2. If you want to use POST too and have nicely formatted json, xml, etc. use a proper API testing extension like Postman or ARC.

How to create a custom exception type in Java?

Great answers about creating custom exception classes. If you intend to reuse the exception in question then I would follow their answers/advice. However, If you only need a quick exception thrown with a message then you can use the base exception class on the spot

String word=reader.readLine();

if(word.contains(" "))
  /*create custom exeception*/
  throw new Exception("My one time exception with some message!");
}

Regex pattern inside SQL Replace function?

If you are doing this just for a parameter coming into a Stored Procedure, you can use the following:

declare @badIndex int
set @badIndex = PatIndex('%[^0-9]%', @Param)
while @badIndex > 0
    set @Param = Replace(@Param, Substring(@Param, @badIndex, 1), '')
    set @badIndex = PatIndex('%[^0-9]%', @Param)

Links not going back a directory?

You need to give a relative file path of <a href="../index.html">Home</a>

Alternately you can specify a link from the root of your site with <a href="/pages/en/index.html">Home</a>

.. and . have special meanings in file paths, .. means up one directory and . means current directory.

so <a href="index.html">Home</a> is the same as <a href="./index.html">Home</a>

How the single threaded non blocking IO model works in Node.js

if you read a bit further - "Of course, on the backend, there are threads and processes for DB access and process execution. However, these are not explicitly exposed to your code, so you can’t worry about them other than by knowing that I/O interactions e.g. with the database, or with other processes will be asynchronous from the perspective of each request since the results from those threads are returned via the event loop to your code."

about - "everything runs in parallel except your code" - your code is executed synchronously, whenever you invoke an asynchronous operation such as waiting for IO, the event loop handles everything and invokes the callback. it just not something you have to think about.

in your example: there are two requests A (comes first) and B. you execute request A, your code continue to run synchronously and execute request B. the event loop handles request A, when it finishes it invokes the callback of request A with the result, same goes to request B.

An example of how to use getopts in bash

"getops" and "getopt" are very limited. While "getopt" is suggested not to be used at all, it does offer long options. Where as "getopts" does only allow single character options such as "-a" "-b". There are a few more disadvantages when using either one.

So i've written a small script that replaces "getopts" and "getopt". It's a start, it could probably be improved a lot.

Update 08-04-2020: I've added support for hyphens e.g. "--package-name".

Usage: "./script.sh package install --package "name with space" --build --archive"

# Example:
# parseArguments "${@}"
# echo "${ARG_0}" -> package
# echo "${ARG_1}" -> install
# echo "${ARG_PACKAGE}" -> "name with space"
# echo "${ARG_BUILD}" -> 1 (true)
# echo "${ARG_ARCHIVE}" -> 1 (true)
function parseArguments() {
  PREVIOUS_ITEM=''
  COUNT=0
  for CURRENT_ITEM in "${@}"
  do
    if [[ ${CURRENT_ITEM} == "--"* ]]; then
      printf -v "ARG_$(formatArgument "${CURRENT_ITEM}")" "%s" "1" # could set this to empty string and check with [ -z "${ARG_ITEM-x}" ] if it's set, but empty.
    else
      if [[ $PREVIOUS_ITEM == "--"* ]]; then
        printf -v "ARG_$(formatArgument "${PREVIOUS_ITEM}")" "%s" "${CURRENT_ITEM}"
      else
        printf -v "ARG_${COUNT}" "%s" "${CURRENT_ITEM}"
      fi
    fi

    PREVIOUS_ITEM="${CURRENT_ITEM}"
    (( COUNT++ ))
  done
}

# Format argument.
function formatArgument() {
  ARGUMENT="${1^^}" # Capitalize.
  ARGUMENT="${ARGUMENT/--/}" # Remove "--".
  ARGUMENT="${ARGUMENT//-/_}" # Replace "-" with "_".
  echo "${ARGUMENT}"
}

How to continue a Docker container which has exited

These commands will work for any container (not only last exited ones). This way will work even after your system has rebooted. To do so, these commands will use "container id".

Steps:

  1. List all dockers by using this command and note the container id of the container you want to restart: docker ps -a

  2. Start your container using container id: docker start <container_id>

  3. Attach and run your container: docker attach <container_id>

NOTE: Works on linux

How to check status of PostgreSQL server Mac OS X

The pg_ctl status command suggested in other answers checks that the postmaster process exists and if so reports that it's running. That doesn't necessarily mean it is ready to accept connections or execute queries.

It is better to use another method like using psql to run a simple query and checking the exit code, e.g. psql -c 'SELECT 1', or use pg_isready to check the connection status.

What are the differences between LDAP and Active Directory?

Active Directory is a database based system that provides authentication, directory, policy, and other services in a Windows environment

LDAP (Lightweight Directory Access Protocol) is an application protocol for querying and modifying items in directory service providers like Active Directory, which supports a form of LDAP.

Short answer: AD is a directory services database, and LDAP is one of the protocols you can use to talk to it.

Data truncated for column?

In my case it was a table with an ENUM that accepts the days of the week as integers (0 to 6). When inserting the value 0 as an integer I got the error message "Data truncated for column ..." so to fix it I had to cast the integer to a string. So instead of:

$item->day = 0;

I had to do;

$item->day = (string) 0;

It looks silly to cast the zero like that but in my case it was in a Laravel factory, and I had to write it like this:

$factory->define(App\Schedule::class, function (Faker $faker) {
    return [
        'day' => (string) $faker->numberBetween(0, 6),
        //
    ];
});

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

Set value for particular cell in pandas DataFrame with iloc

To modify the value in a cell at the intersection of row "r" (in column "A") and column "C"

  1. retrieve the index of the row "r" in column "A"

        i = df[ df['A']=='r' ].index.values[0]
    
  2. modify the value in the desired column "C"

        df.loc[i,"C"]="newValue"
    

Note: before, be sure to reset the index of rows ...to have a nice index list!

        df=df.reset_index(drop=True)

How can I view the source code for a function?

There is a very handy function in R edit

new_optim <- edit(optim)

It will open the source code of optim using the editor specified in R's options, and then you can edit it and assign the modified function to new_optim. I like this function very much to view code or to debug the code, e.g, print some messages or variables or even assign them to a global variables for further investigation (of course you can use debug).

If you just want to view the source code and don't want the annoying long source code printed on your console, you can use

invisible(edit(optim))

Clearly, this cannot be used to view C/C++ or Fortran source code.

BTW, edit can open other objects like list, matrix, etc, which then shows the data structure with attributes as well. Function de can be used to open an excel like editor (if GUI supports it) to modify matrix or data frame and return the new one. This is handy sometimes, but should be avoided in usual case, especially when you matrix is big.

best practice font size for mobile

Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px. By declaring styles that lead to computed font-sizes of less than 12px, like so:

html {
  font-size: 8px;
}
p {
  font-size: 1.4rem;
}
// Computed p size: 11px.

You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px as 12px. So, the following is true:

h6 {
    font-size: 12px;
}
p {
   font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.   
// How unpleasant of a surprise.

I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.

I would instead, opt for something like this:

h1 {
    font-size: 2.5rem;
}

h2 {
    font-size: 2.25rem;
}

h3 {
    font-size: 2rem;
}

h4 {
    font-size: 1.75rem;
}

h5 {
    font-size: 1.5rem;
}

h6 {
    font-size: 1.25rem;
}

p {
    font-size: 1rem;
}

@media (max-width: 480px) {
    html {
        font-size: 12px;
    }
}

@media (min-width: 480px) {
    html {
        font-size: 13px;
    }
}

@media (min-width: 768px) {
    html {
        font-size: 14px;
    }
}

@media (min-width: 992px) {
    html {
        font-size: 15px;
    }
}

@media (min-width: 1200px) {
    html {
        font-size: 16px;
    }
}

You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p elements.

As a side note, setting margin-bottom equal to the font-size usually also tends to be attractive, i.e.:

h1 {
    font-size: 2.5rem;
    margin-bottom: 2.5rem;
}

Good luck.

Missing Maven dependencies in Eclipse project

Problem solved!

I don't know what exactly solved it, but I did 4 things in Eclipse:

  • Window->Preferences: Maven->Installations: Global settings -> open file and hardcoded localRepository
  • Project->Clean
  • right click on project: Maven->Update dependencies
  • right click on project: Maven->Update project configuration

I guess it was the Update dependencies since right after first two there were no change.