Programs & Examples On #Ip camera

An Internet protocol camera which sends video data over the Internet

Access IP Camera in Python OpenCV

In pycharm I wrote the code for accessing the IP Camera like:

import cv2

cap=VideoCapture("rtsp://user_name:password@IP_address:port_number")

ret, frame=cap.read()

You will need to replace user_name, password, IP and port with suitable values

Recording video feed from an IP camera over a network

Why don't you consider www.cameraftp.com? it supports image upload and online viewer

What is the reason for the error message "System cannot find the path specified"?

You just need to:

Step 1: Go home directory of C:\ with typing cd.. (2 times)

Step 2: It appears now C:\>

Step 3: Type dir Windows\System32\run

That's all, it shows complete files & folder details inside target folder.

enter image description here

Details: I used Windows\System32\com folder as example, you should type your own folder name etc. Windows\System32\run

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

for increment decrement month use << >> operators

examples

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1

MVC 4 Razor adding input type date

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

If (Array.Length == 0)

You can use .Length == 0 if the length is empty and the array exists, but are you sure it's not null?

Bootstrap - 5 column layout

Copypastable version of wearesicc's 5 col solution with bootstrap variables:

.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
    position: relative;
    min-height: 1px;
    padding-right: ($gutter / 2);
    padding-left: ($gutter / 2);
}

.col-xs-15 {
    width: 20%;
    float: left;
}
@media (min-width: $screen-sm) {
    .col-sm-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: $screen-md) {
    .col-md-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: $screen-lg) {
    .col-lg-15 {
        width: 20%;
        float: left;
    }
}

Link error "undefined reference to `__gxx_personality_v0'" and g++

It sounds like you're trying to link with your resulting object file with gcc instead of g++:

Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:

$ g++ -Wall -c hello.cc
$ gcc hello.o       (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
  undefined reference to `__gxx_personality_v0'

Source: An Introduction to GCC - for the GNU compilers gcc and g++

How can I generate Unix timestamps?

In Haskell...

To get it back as a POSIXTime type:

import Data.Time.Clock.POSIX
getPOSIXTime

As an integer:

import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime

Converting file size in bytes to human-readable string

Here's mine - works for really big files too -_-

function formatFileSize(size)
{
    var sizes = [' Bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'];
    for (var i = 1; i < sizes.length; i++)
    {
        if (size < Math.pow(1024, i)) return (Math.round((size/Math.pow(1024, i-1))*100)/100) + sizes[i-1];
    }
    return size;
}

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

How to download a file via FTP with Python ftplib

The ftplib module in the Python standard library can be compared to assembler. Use a high level library like: https://pypi.python.org/pypi/ftputil

Total number of items defined in an enum

I've run a benchmark today and came up with interesting result. Among these three:

var count1 = typeof(TestEnum).GetFields().Length;
var count2 = Enum.GetNames(typeof(TestEnum)).Length;
var count3 = Enum.GetValues(typeof(TestEnum)).Length;

GetNames(enum) is by far the fastest!

|         Method |      Mean |    Error |   StdDev |
|--------------- |---------- |--------- |--------- |
| DeclaredFields |  94.12 ns | 0.878 ns | 0.778 ns |
|       GetNames |  47.15 ns | 0.554 ns | 0.491 ns |
|      GetValues | 671.30 ns | 5.667 ns | 4.732 ns |

How to convert NSData to byte array in iPhone?

That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).

The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:

[data getBytes:&byteData length:len];

Which fills the array you have allocated with data from the NSData object.

Changing precision of numeric column in Oracle

By setting the scale, you decrease the precision. Try NUMBER(16,2).

How to check if user input is not an int value

This is to keep requesting inputs while this input is integer and find whether it is odd or even else it will end.

int counter = 1;
    System.out.println("Enter a number:");
    Scanner OddInput = new Scanner(System.in);
        while(OddInput.hasNextInt()){
            int Num = OddInput.nextInt();
            if (Num %2==0){
                System.out.println("Number " + Num + " is Even");
                System.out.println("Enter a number:");
            }
            else {
                System.out.println("Number " + Num + " is Odd");
                System.out.println("Enter a number:");
                }
            }
        System.out.println("Program Ended");
    }

Deserializing JSON data to C# using JSON.NET

You can use:

JsonConvert.PopulateObject(json, obj);

here: json is the json string,obj is the target object. See: example

Note: PopulateObject() will not erase obj's list data, after Populate(), obj's list member will contains its original data and data from json string

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

Converting from longitude\latitude to Cartesian coordinates

In python3.x it can be done using :

# Converting lat/long to cartesian
import numpy as np

def get_cartesian(lat=None,lon=None):
    lat, lon = np.deg2rad(lat), np.deg2rad(lon)
    R = 6371 # radius of the earth
    x = R * np.cos(lat) * np.cos(lon)
    y = R * np.cos(lat) * np.sin(lon)
    z = R *np.sin(lat)
    return x,y,z

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Redirecting Output from within Batch file

This may fail in the case of "toxic" characters in the input. Considering an input like thisIsAnIn^^^^put is a good way how to get understand what is going on. Sure there is a rule that an input string MUST be inside double quoted marks but I have a feeling that this rule is a valid rule only if the meaning of the input is a location on a NTFS partition (maybe it is a rule for URLs I am not sure). But it is not a rule for an arbitrary input string of course (it is "a good practice" but you cannot count with it).

HttpServletRequest - Get query string parameters, no form data

I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending

http://mycompany.com/myapp/myservlet?first=11&second=22

say:

http://mycompany.com/myapp/myservlet/11/22

Finding the type of an object in C++

Your description is a little confusing.

Generally speaking, though some C++ implementations have mechanisms for it, you're not supposed to ask about the type. Instead, you are supposed to do a dynamic_cast on the pointer to A. What this will do is that at runtime, the actual contents of the pointer to A will be checked. If you have a B, you'll get your pointer to B. Otherwise, you'll get an exception or null.

XML Document to String

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Months after this question, I've levelup my Docker skills. I should use Docker container name instead.

That use dokerized-nginx as bridge to expose ip+port of the container.

Within WEB configuration, I now use mysql://USERNAME:PASSWORD@docker_container_name/DB_NAME to access to Mysql socket through docker (also works with docker-compose, use compose-name instead of container one)

Store output of subprocess.Popen call in a string

This works perfectly for me:

import subprocess
try:
    #prints results and merges stdout and std
    result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
    print result
    #causes error and merges stdout and stderr
    result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0 
    print "--------error------"
    print ex.cmd
    print ex.message
    print ex.returncode
    print ex.output # contains stdout and stderr together 

Update OpenSSL on OS X with Homebrew

On mac OS X Yosemite, after installing it with brew it put it into

/usr/local/opt/openssl/bin/openssl

But kept getting an error "Linking keg-only openssl means you may end up linking against the insecure" when trying to link it

So I just linked it by supplying the full path like so

ln -s /usr/local/opt/openssl/bin/openssl /usr/local/bin/openssl

Now it's showing version OpenSSL 1.0.2o when I do "openssl version -a", I'm assuming it worked

How to replace local branch with remote branch entirely in Git?

git checkout .

i always use this command to replace my local changes with repository changes. git checkout space dot.

How to turn on/off MySQL strict mode in localhost (xampp)?

->STRICT_TRANS_TABLES is responsible for setting MySQL strict mode.

->To check whether strict mode is enabled or not run the below sql:

SHOW VARIABLES LIKE 'sql_mode';

If one of the value is STRICT_TRANS_TABLES, then strict mode is enabled, else not. In my case it gave

+--------------+------------------------------------------+ 
|Variable_name |Value                                     |
+--------------+------------------------------------------+
|sql_mode      |STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION|
+--------------+------------------------------------------+

Hence strict mode is enabled in my case as one of the value is STRICT_TRANS_TABLES.

->To disable strict mode run the below sql:

set global sql_mode='';

[or any mode except STRICT_TRANS_TABLES. Ex: set global sql_mode='NO_ENGINE_SUBSTITUTION';]

->To again enable strict mode run the below sql:

set global sql_mode='STRICT_TRANS_TABLES';

Android Layout Weight

One more reason I found (vague as it may sound). The below did not work.

LinearLayout vertical

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

EndLinearLayout

What did work was

RelativeLayout

LinearLayout vertical

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

EndLinearLayout

EndRelativeLayout

It sounds vague by a root layout with Linear and weights under it did not work. And when I say "did not work", I mean, that after I viewed the graphical layout between various resolutions the screen consistency broke big time.

Angularjs simple file download causes router to redirect

in template

<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
    system_update_alt
</md-icon></md-button>

in controller

     $scope.export = function(){ $window.location.href = $scope.export; };

What is external linkage and internal linkage?

I think Internal and External Linkage in C++ gives a clear and concise explanation:

A translation unit refers to an implementation (.c/.cpp) file and all header (.h/.hpp) files it includes. If an object or function inside such a translation unit has internal linkage, then that specific symbol is only visible to the linker within that translation unit. If an object or function has external linkage, the linker can also see it when processing other translation units. The static keyword, when used in the global namespace, forces a symbol to have internal linkage. The extern keyword results in a symbol having external linkage.

The compiler defaults the linkage of symbols such that:

Non-const global variables have external linkage by default
Const global variables have internal linkage by default
Functions have external linkage by default

Android - save/restore fragment state

Android fragment has some advantages and some disadvantages. The most disadvantage of the fragment is that when you want to use a fragment you create it ones. When you use it, onCreateView of the fragment is called for each time. If you want to keep state of the components in the fragment you must save fragment state and yout must load its state in the next shown. This make fragment view a bit slow and weird.

I have found a solution and I have used this solution: "Everything is great. Every body can try".

When first time onCreateView is being run, create view as a global variable. When second time you call this fragment onCreateView is called again you can return this global view. The fragment component state will be kept.

View view;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    setActionBar(null);
    if (view != null) {
        if ((ViewGroup)view.getParent() != null)
            ((ViewGroup)view.getParent()).removeView(view);
        return view; 
    }
    view = inflater.inflate(R.layout.mylayout, container, false);
}

Trust Store vs Key Store - creating with keytool

In simplest terms :

Keystore is used to store your credential (server or client) while truststore is used to store others credential (Certificates from CA).

Keystore is needed when you are setting up server side on SSL, it is used to store server's identity certificate, which server will present to a client on the connection while trust store setup on client side must contain to make the connection work. If you browser to connect to any website over SSL it verifies certificate presented by server against its truststore.

How do you set the EditText keyboard to only consist of numbers on Android?

I think you used somehow the right way to show the number only on the keyboard so better try the given line with xml in your edit text and it will work perfectly so here the code is-

  android:inputType="number"

In case any doubt you can again ask to me i'll try to completely sort out your problem. Thanks

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

Try putting opacity:0; your select element will be invisible but the options will be visible when you click on it.

Read line by line in bash script

FILE=test

while read CMD; do
    echo "$CMD"
done < "$FILE"

A redirection with < "$FILE" has a few advantages over cat "$FILE" | while .... It avoids a useless use of cat, saving an unnecessary child process. It also avoids a common pitfall where the loop runs in a subshell. In bash, commands in a | pipeline run in subshells, which means variable assignments are lost after the loop ends. Redirection with < doesn't have that problem, so you could use $CMD after the loop or modify other variables inside the loop. It also, again, avoids unnecessary child processes.

There are some additional improvements that could be made:

  • Add IFS= so that read won't trim leading and trailing whitespace from each line.
  • Add -r to read to prevent from backslashes from being interpreted as escape sequences.
  • Lower case CMD and FILE. The bash convention is only environmental and internal shell variables are uppercase.
  • Use printf in place of echo which is safer if $cmd is a string like -n, which echo would interpret as a flag.
file=test

while IFS= read -r cmd; do
    printf '%s\n' "$cmd"
done < "$file"

What's the best way to store a group of constants that my program uses?

Another vote for using web.config or app.config. The config files are a good place for constants like connection strings, etc. I prefer not to have to look at the source to view or modify these types of things. A static class which reads these constants from a .config file might be a good compromise, as it will let your application access these resources as though they were defined in code, but still give you the flexibility of having them in an easily viewable/editable space.

How do I check if a property exists on a dynamic anonymous type in c#?

None of the solutions above worked for dynamic that comes from Json, I however managed to transform one with Try catch (by @user3359453) by changing exception type thrown (KeyNotFoundException instead of RuntimeBinderException) into something that actually works...

public static bool HasProperty(dynamic obj, string name)
    {
        try
        {
            var value = obj[name];
            return true;
        }
        catch (KeyNotFoundException)
        {
            return false;
        }
    }

enter image description here

Hope this saves you some time.

How to get docker-compose to always re-create containers from fresh images?

You can pass --force-recreate to docker compose up, which should use fresh containers.

I think the reasoning behind reusing containers is to preserve any changes during development. Note that Compose does something similar with volumes, which will also persist between container recreation (a recreated container will attach to its predecessor's volumes). This can be helpful, for example, if you have a Redis container used as a cache and you don't want to lose the cache each time you make a small change. At other times it's just confusing.

I don't believe there is any way you can force this from the Compose file.

Arguably it does clash with immutable infrastructure principles. The counter-argument is probably that you don't use Compose in production (yet). Also, I'm not sure I agree that immutable infra is the basic idea of Docker, although it's certainly a good use case/selling point.

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

PostgreSQL "DESCRIBE TABLE"

There are lots of ways to describe the table in PostgreSQL

The simple answer is

    > /d <table_name> -- OR

    > /d+ <table_name>

Usage

If you are in Postgres shell [psql] and you need to describe the tables

You can achieve this by Query also [As lots of friends has posted the correct ways]

There are lots of details regarding the Schema are available in Postgres's default table names information_schema. You can directly use it to retrieve the information of any of table using a simple SQL statement.

Easy query

    SELECT
      *
    FROM
      information_schema.columns
    WHERE
      table_schema = 'your_schema' AND
      table_name   = 'your_table';

Medium query

  SELECT
      a.attname AS Field,
      t.typname || '(' || a.atttypmod || ')' AS Type,
      CASE WHEN a.attnotnull = 't' THEN 'YES' ELSE 'NO' END AS Null,
      CASE WHEN r.contype = 'p' THEN 'PRI' ELSE '' END AS Key,
      (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '\'(.*)\'')
              FROM
                      pg_catalog.pg_attrdef d
              WHERE
                      d.adrelid = a.attrelid
                      AND d.adnum = a.attnum
                      AND a.atthasdef) AS Default,
      '' as Extras
  FROM
        pg_class c 
        JOIN pg_attribute a ON a.attrelid = c.oid
        JOIN pg_type t ON a.atttypid = t.oid
        LEFT JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid 
                AND r.conname = a.attname
  WHERE
        c.relname = 'tablename'
        AND a.attnum > 0

  ORDER BY a.attnum

You just need to replace the tablename.

Hard query

  SELECT  
      f.attnum AS number,  
      f.attname AS name,  
      f.attnum,  
      f.attnotnull AS notnull,  
      pg_catalog.format_type(f.atttypid,f.atttypmod) AS type,  
      CASE  
          WHEN p.contype = 'p' THEN 't'  
          ELSE 'f'  
      END AS primarykey,  
      CASE  
          WHEN p.contype = 'u' THEN 't'  
          ELSE 'f'
      END AS uniquekey,
      CASE
          WHEN p.contype = 'f' THEN g.relname
      END AS foreignkey,
      CASE
          WHEN p.contype = 'f' THEN p.confkey
      END AS foreignkey_fieldnum,
      CASE
          WHEN p.contype = 'f' THEN g.relname
      END AS foreignkey,
      CASE
          WHEN p.contype = 'f' THEN p.conkey
      END AS foreignkey_connnum,
      CASE
          WHEN f.atthasdef = 't' THEN d.adsrc
      END AS default
  FROM pg_attribute f  
      JOIN pg_class c ON c.oid = f.attrelid  
      JOIN pg_type t ON t.oid = f.atttypid  
      LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum  
      LEFT JOIN pg_namespace n ON n.oid = c.relnamespace  
      LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)  
      LEFT JOIN pg_class AS g ON p.confrelid = g.oid  
  WHERE c.relkind = 'r'::char  
      AND n.nspname = 'schema'  -- Replace with Schema name  
      AND c.relname = 'tablename'  -- Replace with table name  
      AND f.attnum > 0 ORDER BY number;

You can choose any of the above ways, to describe the table.

Any of you can edit these answers to improve the ways. I'm open to merge your changes. :)

how can I debug a jar at runtime?

With IntelliJ IDEA you can create a Jar Application runtime configuration, select the JAR, the sources, the JRE to run the Jar with and start debugging. Here is the documentation.

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

How to access SOAP services from iPhone

Have a look at gsoap that includes two iOS examples in the download package under ios_plugin. The tool converts WSDL to code for SOAP and XML REST.

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".

JTable won't show column headers

    public table2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 485, 218);
    setTitle("jtable");
    getContentPane().setLayout(null);

    String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
            { "Row2/1", "Row2/2", "Row2/3" },
            { "Row3/1", "Row3/2", "Row3/3" },
            { "Row4/1", "Row4/2", "Row4/3" }, };

    String header[] = { "Column 1", "Column 2", "Column 3" };

    // Table
    JTable table = new JTable(data,header);


    // ScrollPane
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setBounds(36, 37, 407, 79);
    getContentPane().add(scrollPane);

   }

}

try this!!

Refresh certain row of UITableView based on Int in Swift

let indexPathRow:Int = 0
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)

MySQL server has gone away - in exactly 60 seconds

I solved this problem with

if( !mysql_ping($link) ) $link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass", true);

How can I run a windows batch file but hide the command window?

Native C++ codified version of Oleg's answer -- this is copy/pasted from a project I work on under the Boost Software License.

BOOL noError;
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInformation;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
noError = CreateProcess(
    NULL,                                           //lpApplicationName
    //Okay the const_cast is bad -- this code was written a while ago.
    //should probably be &commandLine[0] instead. Oh, and commandLine is
    //a std::wstring
    const_cast<LPWSTR>(commandLine.c_str()),        //lpCommandLine
    NULL,                                           //lpProcessAttributes
    NULL,                                           //lpThreadAttributes
    FALSE,                                          //bInheritHandles
    CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,  //dwCreationFlags
    //This is for passing in a custom environment block -- you can probably
    //just use NULL here.
    options.e ? environment : NULL,                 //lpEnvironment
    NULL,                                           //lpCurrentDirectory
    &startupInfo,                                   //lpStartupInfo
    &processInformation                             //lpProcessInformation
);

if(!noError)
{
    return GetLastError();
}

DWORD exitCode = 0;

if (options.w) //Wait
{
    WaitForSingleObject(processInformation.hProcess, INFINITE);
    if (GetExitCodeProcess(processInformation.hProcess, &exitCode) == 0)
    {
        exitCode = (DWORD)-1;
    }
}

CloseHandle( processInformation.hProcess );
CloseHandle( processInformation.hThread );

Generate fixed length Strings filled with whitespaces

Since Java 1.5 we can use the method java.lang.String.format(String, Object...) and use printf like format.

The format string "%1$15s" do the job. Where 1$ indicates the argument index, s indicates that the argument is a String and 15 represents the minimal width of the String. Putting it all together: "%1$15s".

For a general method we have:

public static String fixedLengthString(String string, int length) {
    return String.format("%1$"+length+ "s", string);
}

Maybe someone can suggest another format string to fill the empty spaces with an specific character?

Else clause on Python while statement

Else is executed if while loop did not break.

I kinda like to think of it with a 'runner' metaphor.

The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.

runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
    print("Runner at: ", runner_at)
    if runner_at == unlucky_sector:
        print("Runner fell and broke his foot. Will not reach finish.")
        break
    runner_at += 1
else:
    print("Runner has finished the race!") # Not executed if runner broke his foot.

Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).

For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:

for i in [1,2,3]:
    for j in ['a', 'unlucky', 'c']:
        print(i, j)
        if j == 'unlucky':
            break
    else: 
        continue  # Only executed if inner loop didn't break.
    break         # This is only reached if inner loop 'breaked' out since continue didn't run. 

print("Finished")
# 1 a
# 1 b
# Finished

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

Change language of Visual Studio 2017 RC

Polish-> English (VS on MAC) answer: When I started a project and was forced to download Visual Studio, went to their page and saw that Microsoft logo I knew there would be problems... And here it is. It occurred difficult to change the language of VS on Mac. My OS is purely English and only because of the fact I downloaded it using a browser with Polish set as a default language I got the wrong version. I had to reinstall the version to the newest and then Visual Studio Community -> Preferences(in the environment section) -> Visual Style-> User Interface Language.

It translates to polish: Visual Studio Community -> Preferencje -> Styl Wizualny w sekcji Srodowisko -> Jezyk interfejsu uzytkownika -> English.

If you don't see such an option then, as I was, you are forced to upgrade this crappy VS to the newest version.

Write to CSV file and export it?

Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.

https://github.com/jitbit/CsvExport

It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs file to your project and you're good to go.

(disclaimer: I'm one of the contributors)

Can I loop through a table variable in T-SQL?

Following Stored Procedure loop through the Table Variable and Prints it in Ascending ORDER. This example is using WHILE LOOP.

CREATE PROCEDURE PrintSequenceSeries 
    -- Add the parameters for the stored procedure here
    @ComaSeperatedSequenceSeries nVarchar(MAX)  
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @SERIES_COUNT AS INTEGER
    SELECT @SERIES_COUNT = COUNT(*) FROM PARSE_COMMA_DELIMITED_INTEGER(@ComaSeperatedSequenceSeries, ',')  --- ORDER BY ITEM DESC

    DECLARE @CURR_COUNT AS INTEGER
    SET @CURR_COUNT = 1

    DECLARE @SQL AS NVARCHAR(MAX)

    WHILE @CURR_COUNT <= @SERIES_COUNT
    BEGIN
        SET @SQL = 'SELECT TOP 1 T.* FROM ' + 
            '(SELECT TOP ' + CONVERT(VARCHAR(20), @CURR_COUNT) + ' * FROM PARSE_COMMA_DELIMITED_INTEGER( ''' + @ComaSeperatedSequenceSeries + ''' , '','') ORDER BY ITEM ASC) AS T ' +
            'ORDER BY T.ITEM DESC '
        PRINT @SQL 
        EXEC SP_EXECUTESQL @SQL 
        SET @CURR_COUNT = @CURR_COUNT + 1
    END;

Following Statement Executes the Stored Procedure:

EXEC  PrintSequenceSeries '11,2,33,14,5,60,17,98,9,10'

The result displayed in SQL Query window is shown below:

The Result of PrintSequenceSeries

The function PARSE_COMMA_DELIMITED_INTEGER() that returns TABLE variable is as shown below :

CREATE FUNCTION [dbo].[parse_comma_delimited_integer]
        (
            @LIST       VARCHAR(8000), 
            @DELIMITER  VARCHAR(10) = ',
            '
        )

        -- TABLE VARIABLE THAT WILL CONTAIN VALUES
        RETURNS @TABLEVALUES TABLE 
        (
            ITEM INT
        )
        AS
        BEGIN 
            DECLARE @ITEM VARCHAR(255)

            /* LOOP OVER THE COMMADELIMITED LIST */
            WHILE (DATALENGTH(@LIST) > 0)
                BEGIN 
                    IF CHARINDEX(@DELIMITER,@LIST) > 0
                        BEGIN
                            SELECT @ITEM = SUBSTRING(@LIST,1,(CHARINDEX(@DELIMITER, @LIST)-1))
                            SELECT @LIST =  SUBSTRING(@LIST,(CHARINDEX(@DELIMITER, @LIST) +
                            DATALENGTH(@DELIMITER)),DATALENGTH(@LIST))
                        END
                    ELSE
                        BEGIN
                            SELECT @ITEM = @LIST
                            SELECT @LIST = NULL
                        END

                    -- INSERT EACH ITEM INTO TEMP TABLE
                    INSERT @TABLEVALUES 
                    (
                        ITEM
                    )
                    SELECT ITEM = CONVERT(INT, @ITEM) 
                END
        RETURN
        END

Setting width/height as percentage minus pixels

For a bit of a different approach you could use something like this on the list:

position: absolute;
top: 18px;
bottom: 0px;
width: 100%;

This works as long as the parent container has position: relative;

Android Location Providers - GPS or Network Provider?

There are 3 location providers in Android.

They are:

gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.

network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.

passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).

The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).

enter image description here

Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris

Code Reference : https://stackoverflow.com/a/3145655/28557

-----------------------Update-----------------------

Now Android have Fused location provider

The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage

Fused location provider provide three ways to fetch location

  1. Last Location: Use when you want to know current location once.
  2. Request Location using Listener: Use when application is on screen / frontend and require continues location.
  3. Request Location using Pending Intent: Use when application in background and require continues location.

References :

Official site : http://developer.android.com/google/play-services/location.html

Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example

http://blog.lemberg.co.uk/fused-location-provider

--------------------------------------------------------

How to create a template function within a class? (C++)

Yes, template member functions are perfectly legal and useful on numerous occasions.

The only caveat is that template member functions cannot be virtual.

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

Getting Unexpected Token Export

To use ES6 add babel-preset-env

and in your .babelrc:

{
  "presets": ["@babel/preset-env"]
}

Answer updated thanks to @ghanbari comment to apply babel 7.

PHP date() with timezone?

It should like this:

date_default_timezone_set('America/New_York');

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

How to get a list of installed android applications and pick one to run

Following is the code to get the list of activities/applications installed on Android :

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);

You will get all the necessary data in the ResolveInfo to start a application. You can check ResolveInfo javadoc here.

How to check if an element is visible with WebDriver

Verifying ele is visible.

public static boolean isElementVisible(final By by)
    throws InterruptedException {
        boolean value = false;

        if (driver.findElements(by).size() > 0) {
            value = true;
        }
        return value;
    }

Full examples of using pySerial package

import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port

use https://pythonhosted.org/pyserial/ for more examples

Plotting lines connecting points

Use the matplotlib.arrow() function and set the parameters head_length and head_width to zero to don't get an "arrow-end". The connections between the different points can be simply calculated using vector addition with: A = [1,2], B=[3,4] --> Connection between A and B is B-A = [2,2]. Drawing this vector starting at the tip of A ends at the tip of B.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')


A = np.array([[10,8],[1,2],[7,5],[3,5],[7,6],[8,7],[9,9],[4,5],[6,5],[6,8]])


fig = plt.figure(figsize=(10,10))
ax0 = fig.add_subplot(212)

ax0.scatter(A[:,0],A[:,1])


ax0.arrow(A[0][0],A[0][1],A[1][0]-A[0][0],A[1][1]-A[0][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[2][0],A[2][1],A[9][0]-A[2][0],A[9][1]-A[2][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[4][0],A[4][1],A[6][0]-A[4][0],A[6][1]-A[4][1],width=0.02,color='red',head_length=0.0,head_width=0.0)


plt.show()

enter image description here

Solving "adb server version doesn't match this client" error

  1. adb kill-server
  2. close any pc side application you are using for manage the android phone, e.g. 360mobile(360????). you might need to end them in task manager in necessary.
  3. adb start-server and it should be solved

Android Gradle Could not reserve enough space for object heap

I tried several solutions, nothing seemed to work. Setting my system JDK to match Android Studio's solved the problem.

Ensure your system java

java -version

Is the same as Androids

File > Project Structure > JDK Location

Case insensitive string compare in LINQ-to-SQL

As you say, there are some important differences between ToUpper and ToLower, and only one is dependably accurate when you're trying to do case insensitive equality checks.

Ideally, the best way to do a case-insensitive equality check would be:

String.Equals(row.Name, "test", StringComparison.OrdinalIgnoreCase)

NOTE, HOWEVER that this does not work in this case! Therefore we are stuck with ToUpper or ToLower.

Note the OrdinalIgnoreCase to make it security-safe. But exactly the type of case (in)sensitive check you use depends on what your purposes is. But in general use Equals for equality checks and Compare when you're sorting, and then pick the right StringComparison for the job.

Michael Kaplan (a recognized authority on culture and character handling such as this) has relevant posts on ToUpper vs. ToLower:

He says "String.ToUpper – Use ToUpper rather than ToLower, and specify InvariantCulture in order to pick up OS casing rules"

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

SQL: IF clause within WHERE clause

You should be able to do this without any IF or CASE

 WHERE 
   (IsNumeric(@OrderNumber) AND
      (CAST OrderNumber AS VARCHAR) = (CAST @OrderNumber AS VARCHAR)
 OR
   (NOT IsNumeric(@OrderNumber) AND
       OrderNumber LIKE ('%' + @OrderNumber))

Depending on the flavour of SQL you may need to tweak the casts on the order number to an INT or VARCHAR depending on whether implicit casts are supported.

This is a very common technique in a WHERE clause. If you want to apply some "IF" logic in the WHERE clause all you need to do is add the extra condition with an boolean AND to the section where it needs to be applied.

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Yes, on Arrays.asList, returning a fixed-size list.

Other than using a linked list, simply use addAll method list.

Example:

String idList = "123,222,333,444";

List<String> parentRecepeIdList = new ArrayList<String>();

parentRecepeIdList.addAll(Arrays.asList(idList.split(","))); 

parentRecepeIdList.add("555");

Exploitable PHP functions

I know move_uploaded_file has been mentioned, but file uploading in general is very dangerous. Just the presence of $_FILES should raise some concern.

It's quite possible to embed PHP code into any type of file. Images can be especially vulnerable with text comments. The problem is particularly troublesome if the code accepts the extension found within the $_FILES data as-is.

For example, a user could upload a valid PNG file with embedded PHP code as "foo.php". If the script is particularly naive, it may actually copy the file as "/uploads/foo.php". If the server is configured to allow script execution in user upload directories (often the case, and a terrible oversight), then you instantly can run any arbitrary PHP code. (Even if the image is saved as .png, it might be possible to get the code to execute via other security flaws.)

A (non-exhaustive) list of things to check on uploads:

  • Make sure to analyze the contents to make sure the upload is the type it claims to be
  • Save the file with a known, safe file extension that will not ever be executed
  • Make sure PHP (and any other code execution) is disabled in user upload directories

Programmatically Install Certificate into Mozilla

Firefox now (since 58) uses a SQLite database cert9.db instead of legacy cert8.db. I have made a fix to a solution presented here to make it work with new versions of Firefox:

certificateFile="MyCa.cert.pem"
certificateName="MyCA Name" 
for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert9.db")
do
  certDir=$(dirname ${certDB});
  #log "mozilla certificate" "install '${certificateName}' in ${certDir}"
  certutil -A -n "${certificateName}" -t "TCu,Cuw,Tuw" -i ${certificateFile} -d sql:${certDir}
done

PHP: How do you determine every Nth iteration of a loop?

It will not work for first position so better solution is :

if ($counter != 0 && $counter % 3 == 0) {
   echo 'image file';
}

Check it by yourself. I have tested it for adding class for every 4th element.

A top-like utility for monitoring CUDA activity on a GPU

I find gpustat very useful. In can be installed with pip install gpustat, and prints breakdown of usage by processes or users.

enter image description here

Java 8 forEach with index

It works with params if you capture an array with one element, that holds the current index.

int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));

The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.

If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:

int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));

What is the Sign Off feature in Git for?

There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).

Headers or trailers (?1) like “sign-off” (?2) is, in current practice in projects like Git and Linux, effectively structured metadata for the commit. These are all appended to the end of the commit message, after the “free form” (unstructured) part of the body of the message. These are token–value (or key–value) pairs typically delimited by a colon and a space (:?).

Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:

 mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
 This is an ancient bug that was actually attempted to be fixed once
 (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
 get_user_pages() race for write access") but that was then undone due to
 problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").

 In the meantime, the s390 situation has long been fixed, and we can now
 fix it by checking the pte_dirty() bit properly (and do it better).  The
 s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
 software dirty bits") which made it into v3.9.  Earlier kernels will
 have to look at the page state itself.

 Also, the VM has become more scalable, and what used a purely
 theoretical race back then has become easier to trigger.

 To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
 we already did a COW" rather than play racy games with FOLL_WRITE that
 is very fundamental, and then use the pte dirty flag to validate that
 the FOLL_COW flag is still valid.

 Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
 Acked-by: Hugh Dickins <[email protected]>
 Reviewed-by: Michal Hocko <[email protected]>
 Cc: Andy Lutomirski <[email protected]>
 Cc: Kees Cook <[email protected]>
 Cc: Oleg Nesterov <[email protected]>
 Cc: Willy Tarreau <[email protected]>
 Cc: Nick Piggin <[email protected]>
 Cc: Greg Thelen <[email protected]>
 Cc: [email protected]
 Signed-off-by: Linus Torvalds <[email protected]>

In addition to the “sign-off” trailer in the above, there is:

  • “Cc” (was notified about the patch)
  • “Acked-by” (acknowledged by the owner of the code, “looks good to me”)
  • “Reviewed-by” (reviewed)
  • “Reported-and-tested-by” (reported and tested the issue (I assume))

Other projects, like for example Gerrit, have their own headers and associated meaning for them.

See: https://git.wiki.kernel.org/index.php/CommitMessageConventions

Moral of the story

It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.

[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.

Get and Set a Single Cookie with Node.js HTTP Server

Let me repeat this part of question that answers here are ignoring:

Can it be done in a few lines of code, without the need to pull in a third party lib?


Reading Cookies

Cookies are read from requests with the Cookie header. They only include a name and value. Because of the way paths work, multiple cookies of the same name can be sent. In NodeJS, all Cookies in as one string as they are sent in the Cookie header. You split them with ;. Once you have a cookie, everything to the left of the equals (if present) is the name, and everything after is the value. Some browsers will accept a cookie with no equal sign and presume the name blank. Whitespaces do not count as part of the cookie. Values can also be wrapped in double quotes ("). Values can also contain =. For example, formula=5+3=8 is a valid cookie.

/**
 * @param {string} [cookieString='']
 * @return {[string,string][]} String Tuple
 */
function getEntriesFromCookie(cookieString = '') {
  return cookieString.split(';').map((pair) => {
    const indexOfEquals = pair.indexOf('=');
    let name;
    let value;
    if (indexOfEquals === -1) {
      name = '';
      value = pair.trim();
    } else {
      name = pair.substr(0, indexOfEquals).trim();
      value = pair.substr(indexOfEquals + 1).trim();
    }
    const firstQuote = value.indexOf('"');
    const lastQuote = value.lastIndexOf('"');
    if (firstQuote !== -1 && lastQuote !== -1) {
      value = value.substring(firstQuote + 1, lastQuote);
    }
    return [name, value];
  });
}

const cookieEntries = getEntriesFromCookie(request.headers.Cookie); 
const object = Object.fromEntries(cookieEntries.slice().reverse());

If you're not expecting duplicated names, then you can convert to an object which makes things easier. Then you can access like object.myCookieName to get the value. If you are expecting duplicates, then you want to do iterate through cookieEntries. Browsers feed cookies in descending priority, so reversing ensures the highest priority cookie appears in the object. (The .slice() is to avoid mutation of the array.)


Settings Cookies

"Writing" cookies is done by using the Set-Cookie header in your response. The response.headers['Set-Cookie'] object is actually an array, so you'll be pushing to it. It accepts a string but has more values than just name and value. The hardest part is writing the string, but this can be done in one line.

/**
 * @param {Object} options
 * @param {string} [options.name='']
 * @param {string} [options.value='']
 * @param {Date} [options.expires]
 * @param {number} [options.maxAge]
 * @param {string} [options.domain]
 * @param {string} [options.path]
 * @param {boolean} [options.secure]
 * @param {boolean} [options.httpOnly]
 * @param {'Strict'|'Lax'|'None'} [options.sameSite]
 * @return {string}
 */
function createSetCookie(options) {
  return (`${options.name || ''}=${options.value || ''}`)
    + (options.expires != null ? `; Expires=${options.expires.toUTCString()}` : '')
    + (options.maxAge != null ? `; Max-Age=${options.maxAge}` : '')
    + (options.domain != null ? `; Domain=${options.domain}` : '')
    + (options.path != null ? `; Path=${options.path}` : '')
    + (options.secure ? '; Secure' : '')
    + (options.httpOnly ? '; HttpOnly' : '')
    + (options.sameSite != null ? `; SameSite=${options.sameSite}` : '');
}

const newCookie = createSetCookie({
  name: 'cookieName',
  value: 'cookieValue',
  path:'/',
});
response.headers['Set-Cookie'].push(newCookie);

Remember you can set multiple cookies, because you can actually set multiple Set-Cookie headers in your request. That's why it's an array.


Note on external libraries:

If you decide to use the express, cookie-parser, or cookie, note they have defaults that are non-standard. Cookies parsed are always URI Decoded (percent-decoded). That means if you use a name or value that has any of the following characters: !#$%&'()*+/:<=>?@[]^`{|} they will be handled differently with those libraries. If you're setting cookies, they are encoded with %{HEX}. And if you're reading a cookie you have to decode them.

For example, while [email protected] is a valid cookie, these libraries will encode it as email=name%40domain.com. Decoding can exhibit issues if you are using the % in your cookie. It'll get mangled. For example, your cookie that was: secretagentlevel=50%007and50%006 becomes secretagentlevel=507and506. That's an edge case, but something to note if switching libraries.

Also, on these libraries, cookies are set with a default path=/ which means they are sent on every url request to the host.

If you want to encode or decode these values yourself, you can use encodeURIComponent or decodeURIComponent, respectively.


References:


Additional information:

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

This always can happen in DataBinding. Try to stay away from adding logic in your bindings, including appending an empty string. You can make your own custom adapter, and use it multiple times.

@BindingAdapter("numericText")
fun numericText(textView: TextView, value: Number?) {
    value?.let {
        textView.text = value.toString()
    }
}

<TextView app:numericText="@{list.size()}" .../>

PHPExcel Make first row bold

Use this:

$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);

Using Eloquent ORM in Laravel to perform search of database using LIKE

Use double quotes instead of single quote eg :

where('customer.name', 'LIKE', "%$findcustomer%")

Below is my code:

public function searchCustomer($findcustomer)
{
    $customer = DB::table('customer')
                  ->where('customer.name', 'LIKE', "%$findcustomer%")
                  ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                  ->get();

    return View::make("your view here");
}

How to click a browser button with JavaScript automatically?

This will give you some control over the clicking, and looks tidy

<script>
var timeOut = 0;
function onClick(but)
{
    //code
    clearTimeout(timeOut);
    timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>

How do you make a div tag into a link

<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>

Is it possible to capture the stdout from the sh DSL command in the pipeline

Try this:

def get_git_sha(git_dir='') {
    dir(git_dir) {
        return sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
    }
}

node(BUILD_NODE) {
    ...
    repo_SHA = get_git_sha('src/FooBar.git')
    echo repo_SHA
    ...
}

Tested on:

  • Jenkins ver. 2.19.1
  • Pipeline 2.4

Understanding INADDR_ANY for socket programming

INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")

How to find the statistical mode?

I was looking through all these options and started to wonder about their relative features and performances, so I did some tests. In case anyone else are curious about the same, I'm sharing my results here.

Not wanting to bother about all the functions posted here, I chose to focus on a sample based on a few criteria: the function should work on both character, factor, logical and numeric vectors, it should deal with NAs and other problematic values appropriately, and output should be 'sensible', i.e. no numerics as character or other such silliness.

I also added a function of my own, which is based on the same rle idea as chrispy's, except adapted for more general use:

library(magrittr)

Aksel <- function(x, freq=FALSE) {
    z <- 2
    if (freq) z <- 1:2
    run <- x %>% as.vector %>% sort %>% rle %>% unclass %>% data.frame
    colnames(run) <- c("freq", "value")
    run[which(run$freq==max(run$freq)), z] %>% as.vector   
}

set.seed(2)

F <- sample(c("yes", "no", "maybe", NA), 10, replace=TRUE) %>% factor
Aksel(F)

# [1] maybe yes  

C <- sample(c("Steve", "Jane", "Jonas", "Petra"), 20, replace=TRUE)
Aksel(C, freq=TRUE)

# freq value
#    7 Steve

I ended up running five functions, on two sets of test data, through microbenchmark. The function names refer to their respective authors:

enter image description here

Chris' function was set to method="modes" and na.rm=TRUE by default to make it more comparable, but other than that the functions were used as presented here by their authors.

In matter of speed alone Kens version wins handily, but it is also the only one of these that will only report one mode, no matter how many there really are. As is often the case, there's a trade-off between speed and versatility. In method="mode", Chris' version will return a value iff there is one mode, else NA. I think that's a nice touch. I also think it's interesting how some of the functions are affected by an increased number of unique values, while others aren't nearly as much. I haven't studied the code in detail to figure out why that is, apart from eliminating logical/numeric as a the cause.

Calculating difference between two timestamps in Oracle in milliseconds

I know that this has been exhaustively answered, but I wanted to share my FUNCTION with everyone. It gives you the option to choose if you want your answer to be in days, hours, minutes, seconds, or milliseconds. You can modify it to fit your needs.

CREATE OR REPLACE FUNCTION Return_Elapsed_Time (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
    FUNCTION Core (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
        day_ VARCHAR2(7); /* This means this FUNCTION only supports up to 99 days */
        hour_ VARCHAR2(9); /* This means this FUNCTION only supports up to 999 hours, which is over 41 days */
        minute_ VARCHAR2(12); /* This means this FUNCTION only supports up to 9999 minutes, which is over 17 days */
        second_ VARCHAR2(18); /* This means this FUNCTION only supports up to 999999 seconds, which is over 11 days */
        msecond_ VARCHAR2(22); /* This means this FUNCTION only supports up to 999999999 milliseconds, which is over 11 days */
        d1_ NUMBER;
        h1_ NUMBER;
        m1_ NUMBER;
        s1_ NUMBER;
        ms_ NUMBER;
        /* If you choose 1, you only get seconds. If you choose 2, you get minutes and seconds etc. */
        precision_ NUMBER; /* 0 => milliseconds; 1 => seconds; 2 => minutes; 3 => hours; 4 => days */
        format_ VARCHAR2(2) := ', ';
        return_ VARCHAR2(50);
    BEGIN
        IF (syntax_ IS NULL) THEN
            precision_ := 0;
        ELSE
            IF (syntax_ = 0) THEN
                precision_ := 0;
            ELSIF (syntax_ = 1) THEN
                precision_ := 1;
            ELSIF (syntax_ = 2) THEN
                precision_ := 2;
            ELSIF (syntax_ = 3) THEN
                precision_ := 3;
            ELSIF (syntax_ = 4) THEN
                precision_ := 4;
            ELSE 
                precision_ := 0;
            END IF;
        END IF;
        SELECT EXTRACT(DAY FROM (end_ - start_)) INTO d1_ FROM DUAL;
        SELECT EXTRACT(HOUR FROM (end_ - start_)) INTO h1_ FROM DUAL;
        SELECT EXTRACT(MINUTE FROM (end_ - start_)) INTO m1_ FROM DUAL;
        SELECT EXTRACT(SECOND FROM (end_ - start_)) INTO s1_ FROM DUAL;
        IF (precision_ = 4) THEN
            IF (d1_ = 1) THEN
                day_ := ' day';
            ELSE
                day_ := ' days';
            END IF;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := d1_ || day_ || format_ || h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 3) THEN
            h1_ := (d1_ * 24) + h1_;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 2) THEN
            m1_ := (((d1_ * 24) + h1_) * 60) + m1_;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 1) THEN
            s1_ := (((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := s1_ || second_;
            RETURN return_;
        ELSE
            ms_ := ((((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_) * 1000;
            IF (ms_ = 1) THEN
                msecond_ := ' millisecond';
            ELSE
                msecond_ := ' milliseconds';
            END IF;
            return_ := ms_ || msecond_;
            RETURN return_;
        END IF;
    END Core;
BEGIN
    RETURN(Core(start_, end_, syntax_));
END Return_Elapsed_Time;

For example, if I called this function right now (12.10.2018 11:17:00.00) using Return_Elapsed_Time(TO_TIMESTAMP('12.04.2017 12:00:00.00', 'DD.MM.YYYY HH24:MI:SS.FF'),SYSTIMESTAMP), it should return something like:

47344620000 milliseconds

Turn off constraints temporarily (MS SQL)

And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.

ALTER TABLE foo CHECK CONSTRAINT ALL

or

ALTER TABLE foo CHECK CONSTRAINT FK_something

then you can run back in and do an update against any checked columns like so:

UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc

And any errors at that point will be due to failure to meet constraints.

How to disable the ability to select in a DataGridView?

I fixed this by setting the Enabled property to false.

TypeError: 'dict_keys' object does not support indexing

You're passing the result of somedict.keys() to the function. In Python 3, dict.keys doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.

To fix the problem, use list(somedict.keys()) to collect the keys, and work with that.

How to emulate GPS location in the Android Emulator?

I had the same problem on Android studio 3.5.1 When I clicked on three dots to the right of android emulator and selected location tab, I dont see a send option. I tried to set a location point but that did not change my default cupertino location. Open google maps and it will autolocate you and your cupertino location will change.

HTML5 Canvas Rotate Image

Here is Something I did

var ImgRotator = {
    angle:parseInt(45),
    image:{},
    src:"",
    canvasID:"",
    intervalMS:parseInt(500),
    jump:parseInt(5),
    start_action:function(canvasID, imgSrc, interval, jumgAngle){
        ImgRotator.jump = jumgAngle;
        ImgRotator.intervalMS = interval;
        ImgRotator.canvasID = canvasID;
        ImgRotator.src = imgSrc ;
        var image = new Image();
        var canvas = document.getElementById(ImgRotator.canvasID);
        image.onload = function() {
            ImgRotator.image = image;
            canvas.height = canvas.width = Math.sqrt( image.width* image.width+image.height*image.height);
            window.setInterval(ImgRotator.keepRotating,ImgRotator.intervalMS);
            //theApp.keepRotating();
        };
        image.src = ImgRotator.src;   
    },
    keepRotating:function(){
        ImgRotator.angle+=ImgRotator.jump;
        var canvas = document.getElementById(ImgRotator.canvasID);
        var ctx = canvas.getContext("2d");
        ctx.save();
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.translate(canvas.width/2,canvas.height/2);
        ctx.rotate(ImgRotator.angle*Math.PI/180); 
        ctx.drawImage(ImgRotator.image, -ImgRotator.image.width/2,-ImgRotator.image.height/2);
        ctx.restore();
    }
}

usage

ImgRotator.start_action("canva",
            "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBx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F8oa+tbCiwpVh10yg8eRPGbrvDPVE68kxi8IIhoiIKhhNQwhSg+zFKD7MaAShco6n5whO5+cb75Q3gTddzAaZ6mOKkm+7SCvdnqZMh6mOa0O9gVFG6yZW6mWGtJvYGGtpD6xgsDJOkJbvABLAtpFhEE5J7ctsqTQwam5UmvU/wBJKlKQ9bGofQjrOvz5T2xtN8XXqYip71Vy57A+6o7AWA9JzLSkMRpFEEcDWctT2isY0rMCAQyARSYEMkEMCWl+GxT0zmRiOo5Hsw5jUygRlgZu19pHEuKjCzZQG1JzEX1uxJOlhr0HHjMMHiDz/WLIYzB07wB4napkov7ykKG1ANQ/5TOeAzW3ZJ55OF503aBFak1OsBoAGtya+hF+YNiJ87+GbHE00N7VWFI2ZltnIAN1IJsbG1xw5TvGLrMcEtW5zMVzE6k2JXUi3S88948Z6bUnfbnGLp19m4tMSigHDFi6gkGth2I3lMDXyhCzqToFZea2nccLiFqotRGDI6q6MOBRgCp+RE0jxfhRUoYZzoXLUmtzptSckHqLZx/zvxAnr+zlj/h9JSb7tq9Jb8clKvUppf8A4qB8Jtxz8Y8sfWzARTGimasEkhEkigIZLwwFtAYwMhlRWYYxWS0ikMEa0lpR/9k=",
            500,15
            );

HTML

<canvas id="canva" width="350" height="350" style="border:solid thin black;"></canvas>

Show spinner GIF during an $http request in AngularJS?

Sharing my version of the great answer from @bulltorious, updated for newer angular builds (I used version 1.5.8 with this code), and also incorporated @JMaylin's idea of using a counter so as to be robust to multiple simultaneous requests, and the option to skip showing the animation for requests taking less than some minimum number of milliseconds:

var app = angular.module('myApp');
var BUSY_DELAY = 1000; // Will not show loading graphic until 1000ms have passed and we are still waiting for responses.

app.config(function ($httpProvider) {
  $httpProvider.interceptors.push('busyHttpInterceptor');
})
  .factory('busyHttpInterceptor', ['$q', '$timeout', function ($q, $timeout) {
    var counter = 0;
    return {
      request: function (config) {
        counter += 1;
        $timeout(
          function () {
            if (counter !== 0) {
              angular.element('#busy-overlay').show();
            }
          },
          BUSY_DELAY);
        return config;
      },
      response: function (response) {
        counter -= 1;
        if (counter === 0) {
          angular.element('#busy-overlay').hide();
        }
        return response;
      },
      requestError: function (rejection) {
        counter -= 1;
        if (counter === 0) {
          angular.element('#busy-overlay').hide();
        }
        return rejection;
      },
      responseError: function (rejection) {
        counter -= 1;
        if (counter === 0) {
          angular.element('#busy-overlay').hide();
        }
        return rejection;
      }
    }
  }]);

ImportError: No module named sqlalchemy

On Windows 10 @ 2019

I faced the same problem. Turns out I forgot to install the following package:

pip install flask_sqlalchemy

After installing the package, everything worked perfectly. Hope, it helped some other noob like me.

Getting time and date from timestamp with php

You can try this:

For Date:

$date = new DateTime($from_date);
$date = $date->format('d-m-Y');

For Time:

$time = new DateTime($from_date);
$time = $time->format('H:i:s');

What should my Objective-C singleton look like?

My way is simple like this:

static id instanceOfXXX = nil;

+ (id) sharedXXX
{
    static volatile BOOL initialized = NO;

    if (!initialized)
    {
        @synchronized([XXX class])
        {
            if (!initialized)
            {
                instanceOfXXX = [[XXX alloc] init];
                initialized = YES;
            }
        }
    }

    return instanceOfXXX;
}

If the singleton is initialized already, the LOCK block will not be entered. The second check if(!initialized) is to make sure it is not initialized yet when the current thread acquires the LOCK.

Expand a div to fill the remaining width

If the width of the other column is fixed, how about using the calc CSS function working for all common browsers:

width: calc(100% - 20px) /* 20px being the first column's width */

This way the width of the second row will be calculated (i.e. remaining width) and applied responsively.

Automatically scroll down chat div

I found out this very simple method while experimenting: set the scrollTo to the height of the div.

var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);

Bootstrap 3 hidden-xs makes row narrower

.row {
    margin-right: 15px;
}

throw this in your CSS

How to persist data in a dockerized postgres database using volumes

Strangely enough, the solution ended up being to change

volumes:
  - ./postgres-data:/var/lib/postgresql

to

volumes:
  - ./postgres-data:/var/lib/postgresql/data

How do I enable Java in Microsoft Edge web browser?

About this, java declares that on Windows 10, Edge browser does not support plugins, so it will NOT run java. (see https://www.java.com/it/download/win10.jsp --> only visible with edge in win10) It also reports a notice: java is not officially supported yet in Windows 10. (see https://www.java.com/it/download/faq/win10_faq.xml)

What is the difference between a heuristic and an algorithm?

Heuristic, in a nutshell is an "Educated guess". Wikipedia explains it nicely. At the end, a "general acceptance" method is taken as an optimal solution to the specified problem.

Heuristic is an adjective for experience-based techniques that help in problem solving, learning and discovery. A heuristic method is used to rapidly come to a solution that is hoped to be close to the best possible answer, or 'optimal solution'. Heuristics are "rules of thumb", educated guesses, intuitive judgments or simply common sense. A heuristic is a general way of solving a problem. Heuristics as a noun is another name for heuristic methods.

In more precise terms, heuristics stand for strategies using readily accessible, though loosely applicable, information to control problem solving in human beings and machines.

While an algorithm is a method containing finite set of instructions used to solving a problem. The method has been proven mathematically or scientifically to work for the problem. There are formal methods and proofs.

Heuristic algorithm is an algorithm that is able to produce an acceptable solution to a problem in many practical scenarios, in the fashion of a general heuristic, but for which there is no formal proof of its correctness.

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

HSL to RGB color conversion

I got this from Brandon Mathis' HSL Picker source code.

It was originally written in CoffeeScript. I converted it to JavaScript using an online converter, and took out the mechanism to verify the user input was a valid RGB value. This answer worked for my usecase, as the most up-voted answer on this post I found to not produce a valid HSL value.

Note that it returns an hsla value, with a representing opacity/transparency. 0 is completely transparent, and 1 fully opaque.

function rgbToHsl(rgb) {
  var a, add, b, diff, g, h, hue, l, lum, max, min, r, s, sat;
  r = parseFloat(rgb[0]) / 255;
  g = parseFloat(rgb[1]) / 255;
  b = parseFloat(rgb[2]) / 255;
  max = Math.max(r, g, b);
  min = Math.min(r, g, b);
  diff = max - min;
  add = max + min;
  hue = min === max ? 0 : r === max ? ((60 * (g - b) / diff) + 360) % 360 : g === max ? (60 * (b - r) / diff) + 120 : (60 * (r - g) / diff) + 240;
  lum = 0.5 * add;
  sat = lum === 0 ? 0 : lum === 1 ? 1 : lum <= 0.5 ? diff / add : diff / (2 - add);
  h = Math.round(hue);
  s = Math.round(sat * 100);
  l = Math.round(lum * 100);
  a = parseFloat(rgb[3]) || 1;
  return [h, s, l, a];
}

Make div 100% Width of Browser Window

.myDiv {
    background-color: red;
    width: 100%;
    min-height: 100vh;
    max-height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    margin: 0 auto;
}

Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

After following all the steps mentioned here, if it still does not connect, try adding the DNS with the IP address in the hosts file in the etc folder. Adding an IP address instead of DNS name in the connection string should be a temporary solution to check if the connection actually works.

How to add 30 minutes to a JavaScript Date object?

_x000D_
_x000D_
var oldDateObj = new Date();_x000D_
var newDateObj = new Date();_x000D_
newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));_x000D_
console.log(newDateObj);
_x000D_
_x000D_
_x000D_

How to get an MD5 checksum in PowerShell

Here is a one-line-command example with both computing the proper checksum of the file, like you just downloaded, and comparing it with the published checksum of the original.

For instance, I wrote an example for downloadings from the Apache JMeter project. In this case you have:

  1. downloaded binary file
  2. checksum of the original which is published in file.md5 as one string in the format:

3a84491f10fb7b147101cf3926c4a855 *apache-jmeter-4.0.zip

Then using this PowerShell command, you can verify the integrity of the downloaded file:

PS C:\Distr> (Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash -eq (Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash")

Output:

True

Explanation:

The first operand of -eq operator is a result of computing the checksum for the file:

(Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash

The second operand is the published checksum value. We firstly get content of the file.md5 which is one string and then we extract the hash value based on the string format:

Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash"

Both file and file.md5 must be in the same folder for this command work.

Java 256-bit AES Password-Based Encryption

Adding to @Wufoo's edits, the following version uses InputStreams rather than files to make working with a variety of files easier. It also stores the IV and Salt in the beginning of the file, making it so only the password needs to be tracked. Since the IV and Salt do not need to be secret, this makes life a little easier.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    public final static int SALT_LEN     = 8;
    static final String     HEXES        = "0123456789ABCDEF";
    String                  mPassword    = null;
    byte[]                  mInitVec     = null;
    byte[]                  mSalt        = new byte[SALT_LEN];
    Cipher                  mEcipher     = null;
    Cipher                  mDecipher    = null;
    private final int       KEYLEN_BITS  = 128;    // see notes below where this is used.
    private final int       ITERATIONS   = 65536;
    private final int       MAX_FILE_BUF = 1024;

    /**
     * create an object with just the passphrase from the user. Don't do anything else yet
     * @param password
     */
    public AES(String password) {
        mPassword = password;
    }

    public static String byteToHex(byte[] raw) {
        if (raw == null) {
            return null;
        }

        final StringBuilder hex = new StringBuilder(2 * raw.length);

        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }

        return hex.toString();
    }

    public static byte[] hexToByte(String hexString) {
        int    len = hexString.length();
        byte[] ba  = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            ba[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                                + Character.digit(hexString.charAt(i + 1), 16));
        }

        return ba;
    }

    /**
     * debug/print messages
     * @param msg
     */
    private void Db(String msg) {
        System.out.println("** Crypt ** " + msg);
    }

    /**
     * This is where we write out the actual encrypted data to disk using the Cipher created in setupEncrypt().
     * Pass two file objects representing the actual input (cleartext) and output file to be encrypted.
     *
     * there may be a way to write a cleartext header to the encrypted file containing the salt, but I ran
     * into uncertain problems with that.
     *
     * @param input - the cleartext file to be encrypted
     * @param output - the encrypted data file
     * @throws IOException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public void WriteEncryptedFile(InputStream inputStream, OutputStream outputStream)
            throws IOException, IllegalBlockSizeException, BadPaddingException {
        try {
            long             totalread = 0;
            int              nread     = 0;
            byte[]           inbuf     = new byte[MAX_FILE_BUF];
            SecretKeyFactory factory   = null;
            SecretKey        tmp       = null;

            // crate secureRandom salt and store  as member var for later use
            mSalt = new byte[SALT_LEN];

            SecureRandom rnd = new SecureRandom();

            rnd.nextBytes(mSalt);
            Db("generated salt :" + byteToHex(mSalt));
            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

            /*
             *  Derive the key, given password and salt.
             *
             * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
             * The end user must also install them (not compiled in) so beware.
             * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
             */
            KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

            tmp = factory.generateSecret(spec);

            SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

            /*
             *  Create the Encryption cipher object and store as a member variable
             */
            mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            mEcipher.init(Cipher.ENCRYPT_MODE, secret);

            AlgorithmParameters params = mEcipher.getParameters();

            // get the initialization vectory and store as member var
            mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();
            Db("mInitVec is :" + byteToHex(mInitVec));
            outputStream.write(mSalt);
            outputStream.write(mInitVec);

            while ((nread = inputStream.read(inbuf)) > 0) {
                Db("read " + nread + " bytes");
                totalread += nread;

                // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
                // and results in full blocks of MAX_FILE_BUF being written.
                byte[] trimbuf = new byte[nread];

                for (int i = 0; i < nread; i++) {
                    trimbuf[i] = inbuf[i];
                }

                // encrypt the buffer using the cipher obtained previosly
                byte[] tmpBuf = mEcipher.update(trimbuf);

                // I don't think this should happen, but just in case..
                if (tmpBuf != null) {
                    outputStream.write(tmpBuf);
                }
            }

            // finalize the encryption since we've done it in blocks of MAX_FILE_BUF
            byte[] finalbuf = mEcipher.doFinal();

            if (finalbuf != null) {
                outputStream.write(finalbuf);
            }

            outputStream.flush();
            inputStream.close();
            outputStream.close();
            outputStream.close();
            Db("wrote " + totalread + " encrypted bytes");
        } catch (InvalidKeyException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidParameterSpecException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
     * to disk as (output) File.
     *
     * I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
     *  and still have a correctly decrypted file in the end. Seems to work so left it in.
     *
     * @param input - File object representing encrypted data on disk
     * @param output - File object of cleartext data to write out after decrypting
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws IOException
     */
    public void ReadEncryptedFile(InputStream inputStream, OutputStream outputStream)
            throws IllegalBlockSizeException, BadPaddingException, IOException {
        try {
            CipherInputStream cin;
            long              totalread = 0;
            int               nread     = 0;
            byte[]            inbuf     = new byte[MAX_FILE_BUF];

            // Read the Salt
            inputStream.read(this.mSalt);
            Db("generated salt :" + byteToHex(mSalt));

            SecretKeyFactory factory = null;
            SecretKey        tmp     = null;
            SecretKey        secret  = null;

            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

            KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

            tmp    = factory.generateSecret(spec);
            secret = new SecretKeySpec(tmp.getEncoded(), "AES");

            /* Decrypt the message, given derived key and initialization vector. */
            mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            // Set the appropriate size for mInitVec by Generating a New One
            AlgorithmParameters params = mDecipher.getParameters();

            mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

            // Read the old IV from the file to mInitVec now that size is set.
            inputStream.read(this.mInitVec);
            Db("mInitVec is :" + byteToHex(mInitVec));
            mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));

            // creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
            cin = new CipherInputStream(inputStream, mDecipher);

            while ((nread = cin.read(inbuf)) > 0) {
                Db("read " + nread + " bytes");
                totalread += nread;

                // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
                byte[] trimbuf = new byte[nread];

                for (int i = 0; i < nread; i++) {
                    trimbuf[i] = inbuf[i];
                }

                // write out the size-adjusted buffer
                outputStream.write(trimbuf);
            }

            outputStream.flush();
            cin.close();
            inputStream.close();
            outputStream.close();
            Db("wrote " + totalread + " encrypted bytes");
        } catch (Exception ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * adding main() for usage demonstration. With member vars, some of the locals would not be needed
     */
    public static void main(String[] args) {

        // create the input.txt file in the current directory before continuing
        File   input   = new File("input.txt");
        File   eoutput = new File("encrypted.aes");
        File   doutput = new File("decrypted.txt");
        String iv      = null;
        String salt    = null;
        AES    en      = new AES("mypassword");

        /*
         * write out encrypted file
         */
        try {
            en.WriteEncryptedFile(new FileInputStream(input), new FileOutputStream(eoutput));
            System.out.printf("File encrypted to " + eoutput.getName() + "\niv:" + iv + "\nsalt:" + salt + "\n\n");
        } catch (IllegalBlockSizeException | BadPaddingException | IOException e) {
            e.printStackTrace();
        }

        /*
         * decrypt file
         */
        AES dc = new AES("mypassword");

        /*
         * write out decrypted file
         */
        try {
            dc.ReadEncryptedFile(new FileInputStream(eoutput), new FileOutputStream(doutput));
            System.out.println("decryption finished to " + doutput.getName());
        } catch (IllegalBlockSizeException | BadPaddingException | IOException e) {
            e.printStackTrace();
        }
    }
}

Java random number with given length

For the follow-up question, you can get a number between 36^5 and 36^6 and convert it in base 36

UPDATED:

using this code

http://javaconfessions.com/2008/09/convert-between-base-10-and-base-62-in_28.html

It's written BaseConverterUtil.toBase36(60466176+r.nextInt(2116316160))

but in your use case, it can be optimized by using a StringBuilder and having the number in the reverse order ie 71 should be converted in Z1 instead of 1Z

EDITED:

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

For what it's worth - I had a similar issue, assuming it's related to a Chrome update.

I had to add font-src, and then specify the url because I was using a CDN

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; font-src 'self' data: fonts.gstatic.com;">

Convert ASCII TO UTF-8 Encoding

If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.

But if you still want to convert, just to be sure that its UTF-8, then you can use iconv

$string = iconv('ASCII', 'UTF-8//IGNORE', $string);

The IGNORE will discard any invalid characters just in case some were not valid ASCII.

What is the difference between \r and \n?

  • "\r" => Return
  • "\n" => Newline or Linefeed (semantics)

  • Unix based systems use just a "\n" to end a line of text.

  • Dos uses "\r\n" to end a line of text.
  • Some other machines used just a "\r". (Commodore, Apple II, Mac OS prior to OS X, etc..)

Getting unix timestamp from Date()

To get a timestamp from Date(), you'll need to divide getTime() by 1000, i.e. :

Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691

or simply:

long unixTime = System.currentTimeMillis() / 1000L;

CASE IN statement with multiple values

If you have more numbers or if you intend to add new test numbers for CASE then you can use a more flexible approach:

DECLARE @Numbers TABLE
(
    Number VARCHAR(50) PRIMARY KEY
    ,Class TINYINT NOT NULL
);
INSERT @Numbers
VALUES ('1121231',1);
INSERT @Numbers
VALUES ('31242323',1);
INSERT @Numbers
VALUES ('234523',2);
INSERT @Numbers
VALUES ('2342423',2);

SELECT c.*, n.Class
FROM   tblClient c  
LEFT OUTER JOIN   @Numbers n ON c.Number = n.Number;

Also, instead of table variable you can use a regular table.

favicon not working in IE

Care to share the URL? Many browsers cope with favicons in (e.g.) png format while IE had often troubles. - Also older versions of IE did not check the html source for the location of the favicon but just single-mindedly tried to get "/favicon.ico" from the webserver.

Cannot find R.layout.activity_main

it happens when you change the project name

in my case, I just change

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="xxxx.newName"

Can I change a column from NOT NULL to NULL without dropping it?

For MYSQL

ALTER TABLE myTable MODIFY myColumn {DataType} NULL

Windows.history.back() + location.reload() jquery

Try these ...

Option1

window.location=document.referrer;

Option2

window.location.reload(history.back());

What is the difference between #import and #include in Objective-C?

#include works just like the C #include.

#import keeps track of which headers have already been included and is ignored if a header is imported more than once in a compilation unit. This makes it unnecessary to use header guards.

The bottom line is just use #import in Objective-C and don't worry if your headers wind up importing something more than once.

Install psycopg2 on Ubuntu

Using Ubuntu 12.04 it appears to work fine for me:

jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon: 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  python-psycopg2-doc
The following NEW packages will be installed
  python-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 334 not upgraded.
Need to get 153 kB of archives.

What error are you getting exactly? - double check you've spelt psycopg right - that's quite often a gotcha... and it never hurts to run an apt-get update to make sure your repo. is up to date.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Include a connection string variable before the MySQL query. For example, $connt in this code:

$results = mysql_query($connt, "SELECT * FROM users");

How do I iterate through each element in an n-dimensional matrix in MATLAB?

If you look deeper into the other uses of size you can see that you can actually get a vector of the size of each dimension. This link shows you the documentation:

www.mathworks.com/access/helpdesk/help/techdoc/ref/size.html

After getting the size vector, iterate over that vector. Something like this (pardon my syntax since I have not used Matlab since college):

d = size(m);
dims = ndims(m);
for dimNumber = 1:dims
   for i = 1:d[dimNumber]
      ...

Make this into actual Matlab-legal syntax, and I think it would do what you want.

Also, you should be able to do Linear Indexing as described here.

Returning JSON from PHP to JavaScript?

There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

If you don't, here's the PECL library you can install.

<?php
    $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

    echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Send raw ZPL to Zebra printer via USB

I've found yet an easier way to write to a Zebra printer over a COM port. I went to the Windows control panel and added a new printer. For the port, I chose COM1 (the port the printer was plugged in to). I used a "Generic / Text Only" printer driver. I disabled the print spooler (a standard option in the printer preferences) as well as all advanced printing options. Now, I can just print any string to that printer and if the string contains ZPL, the printer renders the ZPL just fine! No need for special "start sequences" or funky stuff like that. Yay for simplicity!

working with negative numbers in python

Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions

#this is apparently a better way of getting multiple inputs at the same time than the 
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])

#standing variables
total = 0

if numb > 0:
    repeat = numb
else:
    repeat = -numb

#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
    total += numa


#check to make sure the output is accurate
if numb < 0:
    total = -total


print total

Thanks for all the help everyone.

How can I show dots ("...") in a span with hidden overflow?

You can try this:

_x000D_
_x000D_
.classname{_x000D_
    width:250px;_x000D_
    overflow:hidden;_x000D_
    text-overflow:ellipsis;_x000D_
}
_x000D_
_x000D_
_x000D_

How to change font in ipython notebook

I would also suggest that you explore the options offered by the jupyter themer. For more modest interface changes you may be satisfied with running the syntax:

jupyter-themer [-c COLOR, --color COLOR]
                      [-l LAYOUT, --layout LAYOUT]
                      [-t TYPOGRAPHY, --typography TYPOGRAPHY]

where the options offered by themer would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the .css files if the changes you want to apply are elaborate.

How can I remove text within parentheses with a regex?

>>> import re
>>> filename = "Example_file_(extra_descriptor).ext"
>>> p = re.compile(r'\([^)]*\)')
>>> re.sub(p, '', filename)
'Example_file_.ext'

RegEx to extract all matches from string using RegExp.exec

Here is my answer:

var str = '[me nombre es] : My name is. [Yo puedo] is the right word'; 

var reg = /\[(.*?)\]/g;

var a = str.match(reg);

a = a.toString().replace(/[\[\]]/g, "").split(','));

How to pause a YouTube player when hiding the iframe?

Hey an easy way is to simply set the src of the video to nothing, so that the video will desapear while it's hidden an then set the src back to the video you want when you click on the link that opens the video.. to do that simply set an id to the youtube iframe and call the src function using that id like this:

<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}

function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>

<body>

<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>

<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>

</boby>

How do I correctly detect orientation change using Phonegap on iOS?

Although the question refers to only PhoneGap and iOS usage, and although it was already answered, I can add a few points to the broader question of detecting screen orientation with JS in 2019:

  1. window.orientation property is deprecated and not supported by Android browsers.There is a newer property that provides more information about the orientation - screen.orientation. But it is still experimental and not supported by iOS Safari. So to achieve the best result you probably need to use the combination of the two: const angle = screen.orientation ? screen.orientation.angle : window.orientation.

  2. As @benallansmith mentioned in his comment, window.onorientationchange event is fired before window.onresize, so you won't get the actual dimensions of the screen unless you add some delay after the orientationchange event.

  3. There is a Cordova Screen Orientation Plugin for supporting older mobile browsers, but I believe there is no need in using it nowadays.

  4. There was also a screen.onorientationchange event, but it is deprecated and should not be used. Added just for completeness of the answer.

In my use-case, I didn't care much about the actual orientation, but rather about the actual width and height of the window, which obviously changes with orientation. So I used resize event to avoid dealing with delays between orientationchange event and actualizing window dimensions:

window.addEventListener('resize', () => {
  console.log(`Actual dimensions: ${window.innerWidth}x${window.innerHeight}`);
  console.log(`Actual orientation: ${screen.orientation ? screen.orientation.angle : window.orientation}`);
});

Note 1: I used EcmaScript 6 syntax here, make sure to compile it to ES5 if needed.

Note 2: window.onresize event is also fired when virtual keyboard is toggled, not only when orientation changes.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

For a lot of projects, there is actually 0% difference between the different pythons in terms of speed. That is those that are dominated by engineering time and where all pythons have the same amount of library support.

Getting parts of a URL (Regex)

I tried a few of these that didn't cover my needs, especially the highest voted which didn't catch a url without a path (http://example.com/)

also lack of group names made it unusable in ansible (or perhaps my jinja2 skills are lacking).

so this is my version slightly modified with the source being the highest voted version here:

^((?P<protocol>http[s]?|ftp):\/)?\/?(?P<host>[^:\/\s]+)(?P<path>((\/\w+)*\/)([\w\-\.]+[^#?\s]+))*(.*)?(#[\w\-]+)?$

What is (x & 1) and (x >>= 1)?

x & 1 is equivalent to x % 2.

x >> 1 is equivalent to x / 2

So, these things are basically the result and remainder of divide by two.

jQuery - Redirect with post data

Before document/window ready add "extend" to jQuery :

$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {

            form += '<input type="hidden" name="'+value.name+'" value="'+value.value+'">';
            form += '<input type="hidden" name="'+key+'" value="'+value.value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
    }
});

Use :

$.redirectPost("someurl.com", $("#SomeForm").serializeArray());

Note : this method cant post files .

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

Getting the last revision number in SVN?

<?php
    $url = 'your repository here';
    $output = `svn info $url`;
    echo "<pre>$output</pre>";
?>

You can get the output in XML like so:

$output = `svn info $url --xml`;

If there is an error then the output will be directed to stderr. To capture stderr in your output use thusly:

$output = `svn info $url 2>&1`;

I can't delete a remote master branch on git

The quickest way is to switch default branch from master to another and you can remove master branch from the web interface.

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

Maximum packet size for a TCP connection

According to http://en.wikipedia.org/wiki/Maximum_segment_size, the default largest size for a IPV4 packet on a network is 536 octets (bytes of size 8 bits). See RFC 879

Calculate difference between two datetimes in MySQL

my two cents about logic:

syntax is "old date" - :"new date", so:

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')

gives 30,

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')

gives: -40

How to convert array to a string using methods other than JSON?

Display array in beautiful way:

function arrayDisplay($input)
{
    return implode(
        ', ',
        array_map(
            function ($v, $k) {
                return sprintf("%s => '%s'", $k, $v);
            },
            $input,
            array_keys($input)
        )
    );
}

$arr = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo arrayDisplay($arr);

Displays:

foo => 'bar', baz => 'boom', cow => 'milk', php => 'hypertext processor'

Jquery Open in new Tab (_blank)

Replace this line:

$(this).target = "_blank";

With:

$( this ).attr( 'target', '_blank' );

That will set its HREF to _blank.

PHP cURL GET request and request's body

For those coming to this with similar problems, this request library allows you to make external http requests seemlessly within your php application. Simplified GET, POST, PATCH, DELETE and PUT requests.

A sample request would be as below

use Libraries\Request;

$data = [
  'samplekey' => 'value',
  'otherkey' => 'othervalue'
];

$headers = [
  'Content-Type' => 'application/json',
  'Content-Length' => sizeof($data)
];

$response = Request::post('https://example.com', $data, $headers);
// the $response variable contains response from the request

Documentation for the same can be found in the project's README.md

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

Implementing multiple interfaces with Java - is there a way to delegate?

There's no pretty way. You might be able to use a proxy with the handler having the target methods and delegating everything else to them. Of course you'll have to use a factory because there'll be no constructor.

Cannot find module cv2 when using OpenCV

IF YOU ARE BUILDING FROM SCRATCH, GO THROUGH THIS

You get No module named cv2.cv. Son, you did all step right, since your sudo make install gave no errors.

However look at this step

$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
$ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so

THE VERY IMPORTANT STEP OF ALL THESE IS TO LINK IT.

ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so 
or 
ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so

The moment you choose wise linking, or by brute force just find the cv2.so file if that exist or not

Here I am throwing my output.

    Successfully installed numpy-1.15.3
(cv) demonLover-desktop:~$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ pip list
Package    Version
---------- -------
numpy      1.15.3 
pip        18.1   
setuptools 40.5.0 
wheel      0.32.2 
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ python
Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv2
>>> 
[2]+  Stopped                 python
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/c
ls: cannot access '/usr/local/lib/python2.7/site-packages/c': No such file or directory
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ deactivate 
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls
cv2.so  easy_install.py  easy_install.pyc  numpy  numpy-1.15.3.dist-info  pip  pip-18.1.dist-info  pkg_resources  setuptools  setuptools-40.5.0.dist-info  wheel  wheel-0.32.2.dist-info
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls -l  /usr/local/lib/python2.7/site-packages/
total 0
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls
cv2.so  easy_install.py  easy_install.pyc  numpy  numpy-1.15.3.dist-info  pip  pip-18.1.dist-info  pkg_resources  setuptools  setuptools-40.5.0.dist-info  wheel  wheel-0.32.2.dist-info
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ workon cv
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ python
Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv2
>>> 
[3]+  Stopped                 python
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ find / -name "cv2.so"
find: ‘/lost+found’: Permission denied
find: ‘/run/udisks2’: Permission denied
find: ‘/run/docker’: Permission denied
find: ‘/run/exim4’: Permission denied
find: ‘/run/lightdm’: Permission denied
find: ‘/run/cups/certs’: Permission denied
find: ‘/run/sudo’: Permission denied
find: ‘/run/samba/ncalrpc/np’: Permission denied
find: ‘/run/postgresql/9.5-main.pg_stat_tmp’: Permission denied
find: ‘/run/postgresql/10-main.pg_stat_tmp’: Permission denied
find: ‘/run/lvm’: Permission denied
find: ‘/run/systemd/inaccessible’: Permission denied
find: ‘/run/lock/lvm’: Permission denied
find: ‘/root’: Permission denied
^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ sudofind / -name "cv2.so"
sudofind: command not found
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ sudo find / -name "cv2.so"
[sudo] password for app: 
find: ‘/run/user/1000/gvfs’: Permission denied
^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ sudo find /usr/ -name "cv2.so"
/usr/local/lib/python2.7/dist-packages/cv2.so
^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/dist-packages/ccv2.so cv2.so
click/                        clonevirtualenv.pyc           configparser-3.5.0.dist-info/ configparser.py               cv2.so                        cycler.py
clonevirtualenv.py            concurrent/                   configparser-3.5.0-nspkg.pth  configparser.pyc              cycler-0.10.0.dist-info/      cycler.pyc
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so
ln: failed to create symbolic link 'cv2.so': File exists
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ rm cv2.so 
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls
cv2.so  easy_install.py  easy_install.pyc  numpy  numpy-1.15.3.dist-info  pip  pip-18.1.dist-info  pkg_resources  setuptools  setuptools-40.5.0.dist-info  wheel  wheel-0.32.2.dist-info
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ python
Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> 

My step will only help, if your built is done right.

How to revert multiple git commits?

I really wanted to avoid hard resets, this is what I came up with.

A -> B -> C -> D -> HEAD

To go back to A (which is 4 steps back):

git pull                  # Get latest changes
git reset --soft HEAD~4   # Set back 4 steps
git stash                 # Stash the reset
git pull                  # Go back to head
git stash pop             # Pop the reset 
git commit -m "Revert"    # Commit the changes

Fetching data from MySQL database to html dropdown list

# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

Converting a view to Bitmap without displaying it in Android?

Hope this helps

View view="some view instance";        
view.setDrawingCacheEnabled(true);
Bitmap bitmap=view.getDrawingCache();
view.setDrawingCacheEnabled(false);

Update
getDrawingCache() method is deprecated in API level 28. So look for other alternative for API level > 28.

Converting integer to string in Python

You can use %s or .format:

>>> "%s" % 10
'10'
>>>

Or:

>>> '{}'.format(10)
'10'
>>>

Sending the bearer token with axios

Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;

Edit, Thanks to Jason Norwood-Young.

Some API require bearer to be written as Bearer, so you can do:

axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}

Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.

java.lang.RuntimeException: Uncompilable source code - what can cause this?

It's caused by NetBeans retaining some of the old source and/or compiled code in its cache and not noticing that e.g. some of the code's dependencies (i.e. referenced packages) have changed, and that a proper refresh/recompile of the file would be in order.

The solution is to force that refresh by either:

a) locating & editing the offending source file to force its recompilation (e.g. add a dummy line, save, remove it, save again),
b) doing a clean build (sometimes will work, sometimes won't),
c) disabling "Compile on save" (not recommended, since it can make using the IDE a royal PITA), or
d) simply remove NetBeans cache by hand, forcing the recompilation.

As to how to remove the cache:

If you're using an old version of NetBeans:

  • delete everything related to your project in .netbeans/6.9/var/cache/index/ (replace 6.9 with your version).

If you're using a newer one:

  • delete everything related to your project in AppData/Local/NetBeans/Cache/8.1/index/ (replace 8.1 with your version).

The paths may vary a little e.g. on different platforms, but the idea is still the same.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

you can use Android Asset in android studio , and android Asset will give you image in this size as a drawable and the application will automatically use the size based on screen of device or emulate

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

how to add lines to existing file using python

Use 'a', 'a' means append. Anything written to a file opened with 'a' attribute is written at the end of the file.

with open('file.txt', 'a') as file:
    file.write('input')

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

2.Create a folder where the generated files will be stored:

C:\GREGTESTING

3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )



INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]



SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   

BEGIN    

SELECT 
    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1
END   

5.The results is shown below: enter image description here

How to remove CocoaPods from a project?

To remove pods from a project completely you need to install two thing first...those are follows(Assuming you have already cocoa-pods installed in your system.)...

  1. Cocoapods-Deintegrate Plugin
  2. Cocoapods-Clean Plugin

Installation

  1. Cocoapods-Deintegrate Plugin

    Use this following command on your terminal to install it.

    sudo gem install cocoapods-deintegrate
    
  2. Cocoapods-Clean Plugin

    Use this following command on your terminal to install it.

    sudo gem install cocoapods-clean
    

Usage

First of all goto your project folder by using the as usual command like..

cd (path of the project) //Remove the braces after cd

Now use those two plugins to remove it completely as follows..

  1. Cocoapods-Deintegrate Plugin

    Use this following command on your terminal to deintegrate the pods from your project first.

     pod deintegrate
    

Deintegrating Pods

  1. Cocoapods-Clean Plugin

    After deintegration of pod from your project use this following command on your terminal to clean it completely.

     pod clean
    

    After completing the above tasks there should be the Podfile still remaining on your project directory..Just delete that manually or use this following command on the terminal..

     rm Podfile
    

Thats it...Now you have your project free from pods...Cleaned.

Removing Cocoapods from the system.

Any way try to use the following command on your terminal to uninstall/remove the coca-pods from your system.

sudo gem uninstall cocoapods

It will remove the coca-pods automatically.

Thanks. Hope this helped.

Removing multiple classes (jQuery)

$("element").removeClass("class1 class2");

From removeClass(), the class parameter:

One or more CSS classes to remove from the elements, these are separated by spaces.

Failed to find Build Tools revision 23.0.1

On my system, Android SDK Manager showed /usr/local/Cellar/android-sdk as the SDK path, when $ANDROID_HOME was /Users/james/Library/Android/sdk. I just added a symlink for the correct build tools version.

Remove columns from DataTable in C#

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
    if (dt.Columns.Contains(ColName))
        dt.Columns.Remove(ColName);
}

Occurrences of substring in a string

here is the other solution without using regexp/patterns/matchers or even not using StringUtils.

String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
        String findStr = "hello";
        int count =0;
        int findStrLength = findStr.length();
        for(int i=0;i<str.length();i++){
            if(findStr.startsWith(Character.toString(str.charAt(i)))){
                if(str.substring(i).length() >= findStrLength){
                    if(str.substring(i, i+findStrLength).equals(findStr)){
                        count++;
                    }
                }
            }
        }
        System.out.println(count);

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

How to get the anchor from the URL using jQuery?

Use

window.location.hash

to retrieve everything beyond and including the #

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

The simple command 'keytool' also works on Windows and/or with Cygwin.

IF you're using Cygwin here is the modified command that I used from the bottom of "S.Botha's" answer :

  1. make sure you identify the JRE inside the JDK that you will be using
  2. Start your prompt/cygwin as admin
  3. go inside the bin directory of that JDK e.g. cd /cygdrive/c/Program\ Files/Java/jdk1.8.0_121/jre/bin
  4. Execute the keytool command from inside it, where you provide the path to your new Cert at the end, like so:

    ./keytool.exe -import -trustcacerts -keystore ../lib/security/cacerts  -storepass changeit -noprompt -alias myownaliasformysystem -file "D:\Stuff\saved-certs\ca.cert"
    

Notice, because if this is under Cygwin you're giving a path to a non-Cygwin program, so the path is DOS-like and in quotes.

how to use javascript Object.defineProperty

Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...

How do I configure HikariCP in my Spring Boot app in my application.properties files?

So it turns out that almost all the default settings for HikariCP work for me except the number of DB connections. I set that property in my application.properties:

spring.datasource.maximumPoolSize=20

And Andy Wilkinson is correct as far as I can tell in that you can't use the dataSourceClassName configuration approach for HikariCP with Spring Boot.

How can I align text in columns using Console.WriteLine?

Do some padding, i.e.

          public static void prn(string fname, string fvalue)
            {
                string outstring = fname.PadRight(20)  +"\t\t  " + fvalue;
                Console.WriteLine(outstring);

            }

This worked well, at least for me.

How to parse a date?

We now have a more modern way to do this work.

java.time

The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.

Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.

By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.

String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );

Dump to console.

System.out.println ( "zdt : " + zdt );

When run.

zdt : 2009-06-18T20:56:02-04:00[America/New_York]

Adjust Time Zone

For fun let's adjust to the India time zone.

ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );

zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]

Convert to j.u.Date

If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Prevent content from expanding grid items

The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:


.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;  
}

.day-item-wrapper {
  position: relative;
}

.day-item {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 10px;

  background: rgba(0,0,0,0.1);
}

https://codepen.io/bjnsn/pen/vYYVPZv

How to write character & in android strings.xml

Mac and Android studio users:

Type your char such as & in the string.xml or layout and choose "Option" and "return" keys. Please refer the screen shot

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

no such table found is mainly when you have not opened the SQLiteOpenHelper class with getwritabledata() and before this you also have to call make constructor with databasename & version. And OnUpgrade is called whenever there is upgrade value in version number given in SQLiteOpenHelper class.

Below is the code snippet (No such column found may be because of spell in column name):

public class database_db {
    entry_data endb;
    String file_name="Record.db";
    SQLiteDatabase sq;
    public database_db(Context c)
    {
        endb=new entry_data(c, file_name, null, 8);
    }
    public database_db open()
    {
        sq=endb.getWritableDatabase();
        return this;
    }
    public Cursor getdata(String table)
    {
        return sq.query(table, null, null, null, null, null, null);
    }
    public long insert_data(String table,ContentValues value)
    {
        return sq.insert(table, null, value);
    }
    public void close()
    {
        sq.close();
    }
    public void delete(String table)
    {
        sq.delete(table,null,null);
    }
}
class entry_data extends SQLiteOpenHelper
{

    public entry_data(Context context, String name, SQLiteDatabase.CursorFactory factory,
                      int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase sqdb) {
        // TODO Auto-generated method stub

        sqdb.execSQL("CREATE TABLE IF NOT EXISTS 'YOUR_TABLE_NAME'(Column_1 text not null,Column_2 text not null);");

    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          onCreate(db);
    }

}

Get environment value in controller

All of the variables listed in .env file will be loaded into the $_ENV PHP super-global when your application receives a request. Check out the Laravel configuration page.

$_ENV['yourkeyhere'];

How to show loading spinner in jQuery?

$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();

function showResponse() {
    hideLoad();
    ...
}

http://docs.jquery.com/Ajax/load#urldatacallback

Kill python interpeter in linux from the terminal

pgrep -f <your process name> | xargs kill -9

This will kill the your process service. In my case it is

pgrep -f python | xargs kill -9

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I have this issue, and all I did was make sure that I was referencing the right .Net framework in all the projects then just change the web.config from

From

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

To

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework" requirePermission="false"/>

All works..

npm not working - "read ECONNRESET"

If you're using Windows you should follow up on Advanced System Settings to check the env vars declared over there, you should notice that the proxy configuration may lie within environment variables, like in the picture below:

Windows env vars

So if your proxy server is not available or is blocking traffic from npm you might notice the aforementioned error in this topic. Maybe you don't need any proxy at all, in this case, just remove this HTTP_PROXY env variables.

I had turned all proxy configurations off in my Windows and npm settings, however, npm was still getting timeout and connection errors while downloading resources, then I figured out there was still a proxy configuration left on env variables, which was causing all the trouble.

Python: Pandas Dataframe how to multiply entire column with a scalar

A little late to the game, but for future searchers, this also should work:

df.quantity = df.quantity  * -1

How do I find out what version of WordPress is running?

On the Admin Panel Dashboard, you can find a box called "Right Now". There you can see the version of the WordPress installation. I have seen this result in WordPress 3.2.1. You can also see this in version 3.7.1

WordPress Version 3.7.1

UPDATE:

In WP Version 3.8.3

WordPress Version 3.8.3

In WP Version 3.9.1 Admin Side, You can see the version by clicking the WP logo which is located at the left-top position.

WordPress Version 3.9.1

You can use yoursitename/readme.html

In the WordPress Admin Footer at the Right side, you will see the version info(Version 3.9.1).

In WP 4

You can get the WordPress version using the following code:

<?php bloginfo('version'); ?>

The below file is having all version details

wp-includes/version.php   

Update for WP 4.1.5

In WP 4.1.5, If it was the latest WP version in the footer right part, it will show the version as it is. If not, it will show the latest WP version with the link to update.

Check the below screenshot.

WP 4.1.5

Reset the Value of a Select Box

The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:

<form>
  <select>
    <option>one</option>
    <option>two</option>
    <option selected>three</option>
  </select>
  <input type="reset" value="Reset" />
</form>

Or, using JavaScript, it can be done in following way:

HTML Code:

<select>
  <option selected>one</option>
  <option>two</option>
  <option>three</option>
</select>
<button id="revert">Reset</button>

And JavaScript code:

const button = document.getElementById("revert");
const options = document.querySelectorAll('select option');
button.onclick = () => {
  for (var i = 0; i < options.length; i++) {
    options[i].selected = options[i].defaultSelected;
  }
}

Both of these methods will work if you have multiple selected items or single selected item.

Count unique values in a column in Excel

If using a Mac

  1. highlight column
  2. copy
  3. open terminal.app
  4. type pbpaste|sort -u|wc -l

Linux users replace pbpaste with xclip xsel or similar

Windows users, it's possible but would take some scripting... start with http://brianreiter.org/2010/09/03/copy-and-paste-with-clipboard-from-powershell/

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Automating running command on Linux from Windows using PuTTY

In case you are using Key based authentication, using saved Putty session seems to work great, for example to run a shell script on a remote server(In my case an ec2).Saved configuration will take care of authentication.

C:\Users> plink saved_putty_session_name path_to_shell_file/filename.sh

Please remember if you save your session with name like(user@hostname), this command would not work as it will be treated as part of the remote command.

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

How can I take a screenshot with Selenium WebDriver?

Ruby

time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M_%S')
file_path = File.expand_path(File.dirname(__FILE__) + 'screens_shot')+'/'+time +'.png'
#driver.save_screenshot(file_path)
page.driver.browser.save_screenshot file_path

Is there a better way to run a command N times in bash?

Yet another answer: Use parameter expansion on empty parameters:

# calls curl 4 times 
curl -s -w "\n" -X GET "http:{,,,}//www.google.com"

Tested on Centos 7 and MacOS.

How can I scan barcodes on iOS?

Check out ZBar reads QR Code and ECN/ISBN codes and is available as under the LGPL v2 license.

How to use setInterval and clearInterval?

clearInterval is one option:

var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec 
function doStuff() {
  alert('this is a 2 second warning');
  clearInterval(interval);
}