Programs & Examples On #Cdonts

MySQL table is marked as crashed and last (automatic?) repair failed

Go to data_dir and remove the Your_table.TMP file after repairing <Your_table> table.

How do I prevent a form from being resized by the user?

If you want to prevent resize by dragging sizegrips and by the maximize button and by maximize by doubleclick on the header text, than insert the following code in the load event of the form:

    Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Prevent size grips
    Me.MaximumSize = Me.Size ' Prevent maximize (also by doubleclick of header text)

Of course all choices of a formborderstyle beginning with Fixed will do.

Starting Docker as Daemon on Ubuntu

I had the same issue on 14.04 with docker 1.9.1.

The upstart service command did work when I used sudo, even though I was root:

$ whoami
root
$ service docker status
status: Unbekannter Auftrag: docker

$ sudo service docker status
docker start/running, process 7394

It seems to depend on the environment variables.

service docker status works when becoming root with su -, but not when only using su:

$ su
Password:
$ service docker status
status: unknown job: docker
$ exit
$ su -
Password:
$ service docker status
docker start/running, process 2342

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

OpenSSH cannot use PKCS#12 files out of the box. As others suggested, you must extract the private key in PEM format which gets you from the land of OpenSSL to OpenSSH. Other solutions mentioned here don’t work for me. I use OS X 10.9 Mavericks (10.9.3 at the moment) with “prepackaged” utilities (OpenSSL 0.9.8y, OpenSSH 6.2p2).

First, extract a private key in PEM format which will be used directly by OpenSSH:

openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa > ~/.ssh/id_rsa

I strongly suggest to encrypt the private key with password:

openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa -passout 'pass:Passw0rd!' > ~/.ssh/id_rsa

Obviously, writing a plain-text password on command-line is not safe either, so you should delete the last command from history or just make sure it doesn’t get there. Different shells have different ways. You can prefix your command with space to prevent it from being saved to history in Bash and many other shells. Here is also how to delete the command from history in Bash:

history -d $(history | tail -n 2 | awk 'NR == 1 { print $1 }')

Alternatively, you can use different way to pass a private key password to OpenSSL - consult OpenSSL documentation for pass phrase arguments.

Then, create an OpenSSH public key which can be added to authorized_keys file:

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

Insert into ... values ( SELECT ... FROM ... )

INSERT INTO yourtable
SELECT fielda, fieldb, fieldc
FROM donortable;

This works on all DBMS

DataTables fixed headers misaligned with columns in wide tables

For bootstrap users, this fixed it for me:

   $($.fn.dataTable.tables(true)).DataTable()
      .columns.adjust()
      .fixedColumns().relayout();

See article here

Run a PostgreSQL .sql file using command line arguments

You have four choices to supply a password:

  1. Set the PGPASSWORD environment variable. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-envars.html
  2. Use a .pgpass file to store the password. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-pgpass.html
  3. Use "trust authentication" for that specific user: http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-TRUST
  4. Since PostgreSQL 9.1 you can also use a connection string:
    https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING

HTML/Javascript change div content

you can use following helper function:

function content(divSelector, value) {
    document.querySelector(divSelector).innerHTML = value;
}

content('#content',"whatever");

Where #content must be valid CSS selector

Here is working example.


Additionaly - today (2018.07.01) I made speed comparison for jquery and pure js solutions ( MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

document.getElementById("content").innerHTML = "whatever"; // pure JS
$('#content').html('whatever');                            // jQuery

enter image description here

The jquery solution was slower than pure js solution: 69% on firefox, 61% on safari, 56% on chrome. The fastest browser for pure js was firefox with 560M operations per second, the second was safari 426M, and slowest was chrome 122M.

So the winners are pure js and firefox (3x faster than chrome!)

You can test it in your machine: https://jsperf.com/js-jquery-html-content-change

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Change the database.php file from

$db['default']['dbdriver'] = 'mysql';

to

$db['default']['dbdriver'] = 'mysqli';

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

How do I pass a variable by reference?

alternatively you could use ctypes witch would look something like this

import ctypes

def f(a):
    a.value=2398 ## resign the value in a function

a = ctypes.c_int(0)
print("pre f", a)
f(a)
print("post f", a)

as a is a c int and not a python integer and apperently passed by reference. however you have to be carefull as strange things could happen and is therefor not advised

Unicode character for "X" cancel / close?

✕ is another great one that's not too thick. The HTML code is &#10005;, or 2715 in hex.

How to connect Robomongo to MongoDB

I exported the following connection from Studio 3T:

mongodb://youn-nosql-grej-test:[email protected]:10255/admin?3t.uriVersion=2&3t.certificatePreference=RootCACert:accept_any&3t.databases=admin&3t.connectionMode=direct&3t.useClientCertPassword=false&3t.connection.name=Grej-Test&readPreference=primary&ssl=true

And I filled it in in the following screens:

Connection

Authentication

SSL

OK!

Is there a Google Chrome-only CSS hack?

To work only chrome or safari, try it:

@media screen and (-webkit-min-device-pixel-ratio:0) { 
/* Safari and Chrome */
.myClass {
 color:red;
}

/* Safari only override */
::i-block-chrome,.myClass {
 color:blue;
}}

Using iText to convert HTML to PDF

When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.

How to delete files older than X hours

You could to this trick: create a file 1 hour ago, and use the -newer file argument.

(Or use touch -t to create such a file).

Adobe Acrobat Pro make all pages the same dimension

With Mac OS X and the more recent versions of Acrobat Pro, the PDF printer option does not work. What does work is doing basically the same thing in Preview App. Open the multi page file in Preview, select File>Print. In the Print dialog set your sheet size as if you are using a printer. You may want to select "Auto Rotate", "Scale to Fit" and "Print Entire Image". Then in the lower left corner is the drop button "PDF" and in that menu select "Save as PDF". Give it a new file name, click Save and then you can open the resulting file in whatever PDF app you want and the sheet sizes are the same.

How to customize the configuration file of the official PostgreSQL Docker image?

My solution is for colleagues who needs to make changes in config before launching docker-entrypoint-initdb.d

I was needed to change 'shared_preload_libraries' setting so during it's work postgres already has new library preloaded and code in docker-entrypoint-initdb.d can use it.

So I just patched postgresql.conf.sample file in Dockerfile:

RUN echo "shared_preload_libraries='citus,pg_cron'" >> /usr/share/postgresql/postgresql.conf.sample
RUN echo "cron.database_name='newbie'" >> /usr/share/postgresql/postgresql.conf.sample

And with this patch it become possible to add extension in .sql file in docker-entrypoint-initdb.d/:

CREATE EXTENSION pg_cron;

Format cell color based on value in another sheet and cell

I'm using Excel 2003 -

The problem with using conditional formatting here is that you can't reference another worksheet or workbook in your conditions. What you can to do is set some column on sheet 1 equal to the appropriate column on sheet 2 (in your example =Sheet2!B6). I used Column F in my example below. Then you can use conditional formatting. Select the cell at Sheet 1, row , column 1 and then go to the conditional formatting menu. Choose "Formula Is" from the drop down and set the condition to "=$F$6=4". Click on the format button and then choose the Patterns tab. Choose the color you want and you're done.

You can use the format painter tool to apply conditional formatting to other cells, but be aware that by default Excel uses absolute references in the conditions. If you want them to be relative you'll need to remove the dollar signs from the condition.

You can have up to 3 conditions applied to a cell (use the add >> button at the bottom of the Conditional formatting dialog) so if the last row is fixed (for example, you know that it will always be row 10) you can use it as a condition to set the background color to none. Assuming that the last value you care about is in row 10 then (still assuming that you've set column F on sheet1 to the corresponding cells on sheet 2) then set the 1st condition to Formula Is =$F$10="" and the pattern to None. Make it the first condition and it will override any following conflicting statements.

What is the function __construct used for?

__construct was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor). You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.

An example could go like this:

class Database {
  protected $userName;
  protected $password;
  protected $dbName;

  public function __construct ( $UserName, $Password, $DbName ) {
    $this->userName = $UserName;
    $this->password = $Password;
    $this->dbName = $DbName;
  }
}

// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );

Everything else is explained in the PHP manual: click here

Is it possible to append to innerHTML without destroying descendants' event listeners?

You could do it like this:

var anchors = document.getElementsByTagName('a'); 
var index_a = 0;
var uls = document.getElementsByTagName('UL'); 
window.onload=function()          {alert(anchors.length);};
for(var i=0 ; i<uls.length;  i++)
{
    lis = uls[i].getElementsByTagName('LI');
    for(var j=0 ;j<lis.length;j++)
    {
        var first = lis[j].innerHTML; 
        string = "<img src=\"http://g.etfv.co/" +  anchors[index_a++] + 
            "\"  width=\"32\" 
        height=\"32\" />   " + first;
        lis[j].innerHTML = string;
    }
}

Advantages of std::for_each over for loop

Mostly you'll have to iterate over the whole collection. Therefore I suggest you write your own for_each() variant, taking only 2 parameters. This will allow you to rewrite Terry Mahaffey's example as:

for_each(container, [](int& i) {
    i += 10;
});

I think this is indeed more readable than a for loop. However, this requires the C++0x compiler extensions.

How to get main window handle from process id?

This is my solution using pure Win32/C++ based on the top answer. The idea is to wrap everything required into one function without the need for external callback functions or structures:

#include <utility>

HWND FindTopWindow(DWORD pid)
{
    std::pair<HWND, DWORD> params = { 0, pid };

    // Enumerate the windows using a lambda to process each window
    BOOL bResult = EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL 
    {
        auto pParams = (std::pair<HWND, DWORD>*)(lParam);

        DWORD processId;
        if (GetWindowThreadProcessId(hwnd, &processId) && processId == pParams->second)
        {
            // Stop enumerating
            SetLastError(-1);
            pParams->first = hwnd;
            return FALSE;
        }

        // Continue enumerating
        return TRUE;
    }, (LPARAM)&params);

    if (!bResult && GetLastError() == -1 && params.first)
    {
        return params.first;
    }

    return 0;
}

How do I move a file from one location to another in Java?

You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:

  1. read the source file into memory
  2. write the content to a file at the new location
  3. delete the source file

File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.

java.net.SocketException: Connection reset

I also had this problem with a Java program trying to send a command on a server via SSH. The problem was with the machine executing the Java code. It didn't have the permission to connect to the remote server. The write() method was doing alright, but the read() method was throwing a java.net.SocketException: Connection reset. I fixed this problem with adding the client SSH key to the remote server known keys.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

my issues got fixed after upgrading to MySQL workbench latest version 8.0.18

How do I negate a condition in PowerShell?

You almost had it with Not. It should be:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"
} 

You can also use !: if (!(Test-Path C:\Code)){}

Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}

Correct way to import lodash

Import specific methods inside of curly brackets

import { map, tail, times, uniq } from 'lodash';

Pros:

  • Only one import line(for a decent amount of functions)
  • More readable usage: map() instead of _.map() later in the javascript code.

Cons:

  • Every time we want to use a new function or stop using another - it needs to be maintained and managed

Copied from:The Correct Way to Import Lodash Libraries - A Benchmark article written by Alexander Chertkov.

Remove menubar from Electron app

Most of the answers here are not valid for newer versions. With the version of 9.0 or upper, Menu.setApplicationMenu(null); should work. By the way, Menu exported from electron package: const {Menu} = require('electron');

Postgresql - unable to drop database because of some auto connections to DB

Whenever I try to drop database I get:

ERROR:  database "pilot" is being accessed by other users
DETAIL:  There is 1 other session using the database.

First You need to revoke

REVOKE CONNECT ON DATABASE TARGET_DB FROM public;

Then use:

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'TARGET_DB';

It will surely work.

Compare two Timestamp in java

if (!mytime.before(fromtime) && !mytime.after(totime))

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

VB.NET Connection string (Web.Config, App.Config)

Not clear where My_ConnectionString is coming from in your example, but try this

System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString

like this

Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)

Counter increment in Bash loop not working

First, you are not increasing the counter. Changing COUNTER=$((COUNTER)) into COUNTER=$((COUNTER + 1)) or COUNTER=$[COUNTER + 1] will increase it.

Second, it's trickier to back-propagate subshell variables to the callee as you surmise. Variables in a subshell are not available outside the subshell. These are variables local to the child process.

One way to solve it is using a temp file for storing the intermediate value:

TEMPFILE=/tmp/$$.tmp
echo 0 > $TEMPFILE

# Loop goes here
  # Fetch the value and increase it
  COUNTER=$[$(cat $TEMPFILE) + 1]

  # Store the new value
  echo $COUNTER > $TEMPFILE

# Loop done, script done, delete the file
unlink $TEMPFILE

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

I actually found something that worked for me. It converts the text to binary and then to UTF8.

Source Text that has encoding issues: If ‘Yes’, what was your last

SELECT CONVERT(CAST(CONVERT(
    (SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865) 
USING LATIN1) AS BINARY) USING UTF8) AS 'result';

Corrected Result text: If ‘Yes’, what was your last

My source was wrongly encoded twice so I had two do it twice. For one time you can use:

SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;

Please excuse me for any formatting mistakes

Substring a string from the end of the string

If it's an unknown amount of strings you could trim off the last character by doing s = s.TrimEnd('','!').Trim();

Have you considered using a regular expression? If you only want to allow alpha numeric characters you can use regex to replace the symbols, What if instead of a ! you get a %?

How to import CSV file data into a PostgreSQL table?

You can create a bash file as import.sh (that your CSV format is a tab delimiter)

#!/usr/bin/env bash

USER="test"
DB="postgres"
TBALE_NAME="user"
CSV_DIR="$(pwd)/csv"
FILE_NAME="user.txt"

echo $(psql -d $DB -U $USER  -c "\copy $TBALE_NAME from '$CSV_DIR/$FILE_NAME' DELIMITER E'\t' csv" 2>&1 |tee /dev/tty)

And then run this script.

Combining two sorted lists in Python

This is simple merging of two sorted lists. Take a look at the sample code below which merges two sorted lists of integers.

#!/usr/bin/env python
## merge.py -- Merge two sorted lists -*- Python -*-
## Time-stamp: "2009-01-21 14:02:57 ghoseb"

l1 = [1, 3, 4, 7]
l2 = [0, 2, 5, 6, 8, 9]

def merge_sorted_lists(l1, l2):
    """Merge sort two sorted lists

    Arguments:
    - `l1`: First sorted list
    - `l2`: Second sorted list
    """
    sorted_list = []

    # Copy both the args to make sure the original lists are not
    # modified
    l1 = l1[:]
    l2 = l2[:]

    while (l1 and l2):
        if (l1[0] <= l2[0]): # Compare both heads
            item = l1.pop(0) # Pop from the head
            sorted_list.append(item)
        else:
            item = l2.pop(0)
            sorted_list.append(item)

    # Add the remaining of the lists
    sorted_list.extend(l1 if l1 else l2)

    return sorted_list

if __name__ == '__main__':
    print merge_sorted_lists(l1, l2)

This should work fine with datetime objects. Hope this helps.

Twitter Bootstrap - how to center elements horizontally or vertically

Updated 2018

In Bootstrap 4, the centering methods have changed..

Horizontal Center in BS4

  • text-center is still used for display:inline elements
  • mx-auto replaces center-block to center display:flex children
  • offset-* or mx-auto can be used to center grid columns

mx-auto (auto x-axis margins) will center display:block or display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.

Demo Bootstrap 4 Horizontal Centering

For vertical centering in BS4 see https://stackoverflow.com/a/41464397/171456

Disable Required validation attribute under certain circumstances

I know this question has been answered a long time ago and the accepted answer will actually do the work. But there's one thing that bothers me: having to copy 2 models only to disable a validation.

Here's my suggestion:

public class InsertModel
{
    [Display(...)]
    public virtual string ID { get; set; }

    ...Other properties
}

public class UpdateModel : InsertModel
{
    [Required]
    public override string ID
    {
        get { return base.ID; }
        set { base.ID = value; }
    }
}

This way, you don't have to bother with client/server side validations, the framework will behave the way it's supposed to. Also, if you define a [Display] attribute on the base class, you don't have to redefine it in your UpdateModel.

And you can still use these classes the same way:

[HttpPost]
public ActionResult Update(UpdateModel model)
{
    ...
}

[HttpPost]
public ActionResult Insert(InsertModel model)
{
    ...
}

How can I post data as form data instead of a request payload?

In your app config -

$httpProvider.defaults.transformRequest = function (data) {
        if (data === undefined)
            return data;
        var clonedData = $.extend(true, {}, data);
        for (var property in clonedData)
            if (property.substr(0, 1) == '$')
                delete clonedData[property];

        return $.param(clonedData);
    };

With your resource request -

 headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }

How to append a date in batch files

I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19

http://cwashington.netreach.net/depo/default.asp?topic=repository&move=last&ScriptType=command&SubType=Misc

Here's the code from that site:

::~~Author~~.          Brett Middleton
::~~Email_Address~~. [email protected]
::~~Script_Type~~.   nt command line batch
::~~Sub_Type~~. Misc
::~~Keywords~~. environment variables

::~~Comment~~.
::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command.  These variables can be used to name files, control the flow of execution, etc.

::~~Script~~.

@echo off

::-----------------------------------------------------------------------------
::  SetEnvDate1.CMD                                                     6/30/98
::-----------------------------------------------------------------------------
::  Description  :  Sets or clears a group of environment variables containing
::               :  components of the current date extracted from the string
::               :  returned by the DATE /T command.  These variables can be
::               :  used to name files, control the flow of execution, etc.
::               :
::  Requires     :  Windows NT with command extensions enabled
::               :
::  Tested       :  Yes, as demonstration
::               :
::  Contact      :  Brett Middleton <[email protected]>
::               :  Animal and Dairy Science Department
::               :  University of Georgia, Athens
::-----------------------------------------------------------------------------
::  USAGE
::
::  SetEnvDate1 can be used as a model for coding date/time routines in
::  other scripts, or can be used by itself as a utility that is called
::  from other scripts.
::  
::  Run or call SetEnvDate1 without arguments to set the date variables.
::  Variables are set for the day abbreviation (DT_DAY), month number (DT_MM),
::  day number (DT_DD) and four-digit year (DT_YYYY).
::
::  When the variables are no longer needed, clean up the environment by
::  calling the script again with the CLEAR argument.  E.g.,
::
::       call SetEnvDate1 clear
::-----------------------------------------------------------------------------
::  NOTES
::
::  A time variable could be added by parsing the string returned by the
::  built-in TIME /T command.  This is left as an exercise for the reader. B-)
::
::  This script illustrates the following NT command extensions:
::
::  1.  Use of the extended IF command to do case-insensitive comparisons.
::
::  2.  Use of the extended DATE command.
::
::  3.  Use of the extended FOR command to parse a string returned by a
::      command or program.
::
::  4.  Use of the "()" conditional processing symbols to group commands
::      for conditional execution.  All commands between the parens will
::      be executed if the preceeding IF or FOR statement is TRUE.
::-----------------------------------------------------------------------------

if not "%1" == "?" goto chkarg
echo.
echo Sets or clears date/time variables in the command environment.
echo.
echo    SetEnvDate1 [clear]
echo.
echo When called without arguments, the variables are created or updated.
echo When called with the CLEAR argument, the variables are deleted.
echo.
goto endit

::-----------------------------------------------------------------------------
::  Check arguments and select SET or CLEAR routine.  Unrecognized arguments
::  are ignored and SET is assumed.
::-----------------------------------------------------------------------------

:chkarg

if /I "%1" == "CLEAR" goto clrvar
goto setvar

::-----------------------------------------------------------------------------
::  Set variables for the day abbreviation (DAY), month number (MM), 
::  day number (DD) and 4-digit year (YYYY). 
::-----------------------------------------------------------------------------

:setvar

for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO (
set DT_DAY=%%i
set DT_MM=%%j
set DT_DD=%%k
set DT_YYYY=%%l)

goto endit

::-----------------------------------------------------------------------------
::  Clear all variables from the environment.
::-----------------------------------------------------------------------------

:clrvar
for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v=
goto endit

:endit

Representing Directory & File Structure in Markdown Syntax

If you wish to generate it dynamically I recommend using Frontend-md. It is simple to use.

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

Android Use Done button on Keyboard to click button

if you want to catch the keyboard enter button for doing your job which you want to done through any event like button click, you can write the below simple code for that text view

Edittext ed= (EditText) findViewById(R.id.edit_text);

ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        // Do you job here which you want to done through event
    }
    return false;
}
});

Converting unix time into date-time via excel

in case the above does not work for you. for me this did not for some reasons;

the UNIX numbers i am working on are from the Mozilla place.sqlite dates.

to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)

Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked

What is the simplest and most robust way to get the user's current location on Android?

Recently refactored to obtain the location of the code, learn some good ideas, and finally achieved a relatively perfect library and Demo.

//request all valid provider(network/gps)
private boolean requestAllProviderUpdates() {
    checkRuntimeEnvironment();
    checkPermission();

    if (isRequesting) {
        EasyLog.d("Request location update is busy");
        return false;
    }


    long minTime = getCheckTimeInterval();
    float minDistance = getCheckMinDistance();

    if (mMapLocationListeners == null) {
        mMapLocationListeners = new HashMap<>();
    }

    mValidProviders = getValidProviders();
    if (mValidProviders == null || mValidProviders.isEmpty()) {
        throw new IllegalArgumentException("Not available provider.");
    }

    for (String provider : mValidProviders) {
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (location == null) {
                    EasyLog.e("LocationListener callback location is null.");
                    return;
                }
                printf(location);
                mLastProviderTimestamp = location.getTime();

                if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    finishResult(location);
                } else {
                    doLocationResult(location);
                }

                removeProvider(location.getProvider());
                if (isEmptyValidProviders()) {
                    requestTimeoutMsgInit();
                    removeUpdates();
                }
            }

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

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };
        getLocationManager().requestLocationUpdates(provider, minTime, minDistance, locationListener);
        mMapLocationListeners.put(provider, locationListener);
        EasyLog.d("Location request %s provider update.", provider);
    }
    isRequesting = true;
    return true;
}

//remove request update
public void removeUpdates() {
    checkRuntimeEnvironment();

    LocationManager locationManager = getLocationManager();
    if (mMapLocationListeners != null) {
        Set<String> keys = mMapLocationListeners.keySet();
        for (String key : keys) {
            LocationListener locationListener = mMapLocationListeners.get(key);
            if (locationListener != null) {
                locationManager.removeUpdates(locationListener);
                EasyLog.d("Remove location update, provider is " + key);
            }
        }
        mMapLocationListeners.clear();
        isRequesting = false;
    }
}

//Compared with the last successful position, to determine whether you need to filter
private boolean isNeedFilter(Location location) {
    checkLocation(location);

    if (mLastLocation != null) {
        float distance = location.distanceTo(mLastLocation);
        if (distance < getCheckMinDistance()) {
            return true;
        }
        if (location.getAccuracy() >= mLastLocation.getAccuracy()
                && distance < location.getAccuracy()) {
            return true;
        }
        if (location.getTime() <= mLastProviderTimestamp) {
            return true;
        }
    }
    return false;
}

private void doLocationResult(Location location) {
    checkLocation(location);

    if (isNeedFilter(location)) {
        EasyLog.d("location need to filtered out, timestamp is " + location.getTime());
        finishResult(mLastLocation);
    } else {
        finishResult(location);
    }
}

//Return to the finished position
private void finishResult(Location location) {
    checkLocation(location);

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    float accuracy = location.getAccuracy();
    long time = location.getTime();
    String provider = location.getProvider();

    if (mLocationResultListeners != null && !mLocationResultListeners.isEmpty()) {
        String format = "Location result:<%f, %f> Accuracy:%f Time:%d Provider:%s";
        EasyLog.i(String.format(format, latitude, longitude, accuracy, time, provider));

        mLastLocation = location;
        synchronized (this) {
            Iterator<LocationResultListener> iterator =  mLocationResultListeners.iterator();
            while (iterator.hasNext()) {
                LocationResultListener listener = iterator.next();
                if (listener != null) {
                    listener.onResult(location);
                }
                iterator.remove();
            }
        }
    }
}

Complete code: https://github.com/bingerz/FastLocation/blob/master/fastlocationlib/src/main/java/cn/bingerz/fastlocation/FastLocation.java

*Each request to complete the location, it is best to removeUpdates, otherwise the phone status bar will always display the positioning icon.

Remove grid, background color, and top and right borders from ggplot2

Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes. Most notably, opts() is now deprecated, having been replaced by theme(). Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.

Here's updated code reflecting current ggplot syntax:

library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

#base ggplot object
p <- ggplot(df, aes(x = a, y = b))

p +
  #plots the points
  geom_point() +

  #theme with white background
  theme_bw() +

  #eliminates background, gridlines, and chart border
  theme(
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank()
  ) +

  #draws x and y axis line
  theme(axis.line = element_line(color = 'black'))

generates:

plot output

Brackets.io: Is there a way to auto indent / format <html>

The Identator plugin works to me in Brackets Release 1.13 versión 1.13.0-17696 (release 49d29a8bc) on S.O. Windows 10

What's the best way to iterate an Android Cursor?

How about using foreach loop:

Cursor cursor;
for (Cursor c : CursorUtils.iterate(cursor)) {
    //c.doSth()
}

However my version of CursorUtils should be less ugly, but it automatically closes the cursor:

public class CursorUtils {
public static Iterable<Cursor> iterate(Cursor cursor) {
    return new IterableWithObject<Cursor>(cursor) {
        @Override
        public Iterator<Cursor> iterator() {
            return new IteratorWithObject<Cursor>(t) {
                @Override
                public boolean hasNext() {
                    t.moveToNext();
                    if (t.isAfterLast()) {
                        t.close();
                        return false;
                    }
                    return true;
                }
                @Override
                public Cursor next() {
                    return t;
                }
                @Override
                public void remove() {
                    throw new UnsupportedOperationException("CursorUtils : remove : ");
                }
                @Override
                protected void onCreate() {
                    t.moveToPosition(-1);
                }
            };
        }
    };
}

private static abstract class IteratorWithObject<T> implements Iterator<T> {
    protected T t;
    public IteratorWithObject(T t) {
        this.t = t;
        this.onCreate();
    }
    protected abstract void onCreate();
}

private static abstract class IterableWithObject<T> implements Iterable<T> {
    protected T t;
    public IterableWithObject(T t) {
        this.t = t;
    }
}
}

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Django - after login, redirect user to his custom page --> mysite.com/username

When using Class based views, another option is to use the dispatch method. https://docs.djangoproject.com/en/2.2/ref/class-based-views/base/

Example Code:

Settings.py

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'

urls.py

from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('login/', auth_views.LoginView.as_view(),name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

views.py

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic import View
from django.shortcuts import redirect

@method_decorator([login_required], name='dispatch')
class HomeView(View):
    model = models.User

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('login')
        elif some-logic:
            return redirect('some-page') #needs defined as valid url
        return super(HomeView, self).dispatch(request, *args, **kwargs)

2D cross-platform game engine for Android and iOS?

Recently I used an AS3 engine: PushButton (now is dead, but it's still functional and you could use something else) to do this job. To make it works with Android and iOS, the project was compiled in AIR for both platforms and everything worked with no performance damage. Since Flash Builder is kinda expensive ($249), you could use FlashDevelop (there is some tutorials to compile in AIR with it).

Flash could be an option since is very easy to learn.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

apt-get install python-dev

...solved the problem for me.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

Had the same issue installing angular material CDK:

npm install --save @angular/material @angular/cdk @angular/animations

Adding -dev like below worked for me:

npm install --save-dev @angular/material @angular/cdk @angular/animations

Visual Studio loading symbols

I had a similar issue where visual studio keeps loading symbol and got stuck.

It turns out I added some "Command line arguments" in the Debug options, and one of the parameters is invalid(I am supposed to pass in some values). enter image description here

After I remove the extra parameter, it starts working again.

How to check if input is numeric in C++

Why not just using scanf("%i") and check its return?

Map a network drive to be used by a service

You could us the 'net use' command:

var p = System.Diagnostics.Process.Start("net.exe", "use K: \\\\Server\\path");
var isCompleted = p.WaitForExit(5000);

If that does not work in a service, try the Winapi and PInvoke WNetAddConnection2

Edit: Obviously I misunderstood you - you can not change the sourcecode of the service, right? In that case I would follow the suggestion by mdb, but with a little twist: Create your own service (lets call it mapping service) that maps the drive and add this mapping service to the dependencies for the first (the actual working) service. That way the working service will not start before the mapping service has started (and mapped the drive).

Install GD library and freetype on Linux

For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd

Call a child class method from a parent class object

NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.

However.. you should be able to do it like:

void calculate(Person p) {
    ((Student)p).method();
}

a safe way would be:

void calculate(Person p) {
    if(p instanceof Student) ((Student)p).method();
}

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

Regular Expression for matching parentheses

  • You can escape any meta-character by using a backslash, so you can match ( with the pattern \(.
  • Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
  • Some flavors support \Q and \E, with literal text between them.
  • Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

Foreign keys in mongo?

We can define the so-called foreign key in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: ['bio101', 'bio102']   // <= ids of the courses
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

The courses field contains _ids of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane, we need to perform another operation to retrieve the course document via _id.

If the course bio101 is removed, we need to perform another operation to update the courses field in the student document.

More: MongoDB Schema Design

The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:

Embedded document

  1. Suitable for one-to-few.
  2. Advantage: no need to perform additional queries to another document.
  3. Disadvantage: cannot manage the entity of embedded documents individually.

Example:

student
{
  name: 'Kate Monster',
  addresses : [
     { street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
     { street: '123 Avenue Q', city: 'New York', cc: 'USA' }
  ]
}

Child referencing

Like the student/course example above.

Parent referencing

Suitable for one-to-squillions, such as log messages.

host
{
    _id : ObjectID('AAAB'),
    name : 'goofy.example.com',
    ipaddr : '127.66.66.66'
}

logmsg
{
    time : ISODate("2014-03-28T09:42:41.382Z"),
    message : 'cpu is on fire!',
    host: ObjectID('AAAB')       // Reference to the Host document
}

Virtually, a host is the parent of a logmsg. Referencing to the host id saves much space given that the log messages are squillions.

References:

  1. 6 Rules of Thumb for MongoDB Schema Design: Part 1
  2. 6 Rules of Thumb for MongoDB Schema Design: Part 2
  3. 6 Rules of Thumb for MongoDB Schema Design: Part 3
  4. Model One-to-Many Relationships with Document References

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

How to stop BackgroundWorker correctly

If you add a loop between the CancelAsync() and the RunWorkerAsync() like so it will solve your problem

 private void combobox2_TextChanged(object sender, EventArgs e)
 {
     if (cmbDataSourceExtractor.IsBusy)
        cmbDataSourceExtractor.CancelAsync();

     while(cmbDataSourceExtractor.IsBusy)
        Application.DoEvents();

     var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
        V2 = combobox2.Text};
     cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
  }

The while loop with the call to Application.DoEvents() will hault the execution of your new worker thread until the current one has properly cancelled, keep in mind you still need to handle the cancellation of your worker thread. With something like:

 private void cmbDataSourceExtractor_DoWork(object sender, DoWorkEventArgs e)
 {
      if (this.cmbDataSourceExtractor.CancellationPending)
      {
          e.Cancel = true;
          return;
      }
      // do stuff...
 }

The Application.DoEvents() in the first code snippet will continue to process your GUI threads message queue so the even to cancel and update the cmbDataSourceExtractor.IsBusy property will still be processed (if you simply added a continue instead of Application.DoEvents() the loop would lock the GUI thread into a busy state and would not process the event to update the cmbDataSourceExtractor.IsBusy)

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Javascript to stop HTML5 video playback on modal window close

I searched all over the internet for an answer for this question. none worked for me except this code. Guaranteed. It work perfectly.

$('body').on('hidden.bs.modal', '.modal', function () {
$('video').trigger('pause');
});

Getting visitors country from their IP

echo json_decode(file_get_contents('https://iplocation.hirak.cc/?ip='.$_SERVER['REMOTE_ADDR']))->country; 
// for ip=190.2.145.41 output: Natherlands

Explination: previous api provide result like this for my ip (for exemple);

 {
    ip: "105.103.124.4",
    country_code: "DZ",
    country: "Algeria",
    attribution: "Data from https://lite.ip2location.com/"
 }

so to access to the country, we will need to decode the result as stdClass, to be accessible, because the result is text format, we add the json_decode() to the file_get_contents(), & from json_decode() returning stdClass (the same format) will access to country by ->country

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

lexers vs parsers

Yes, they are very different in theory, and in implementation.

Lexers are used to recognize "words" that make up language elements, because the structure of such words is generally simple. Regular expressions are extremely good at handling this simpler structure, and there are very high-performance regular-expression matching engines used to implement lexers.

Parsers are used to recognize "structure" of a language phrases. Such structure is generally far beyond what "regular expressions" can recognize, so one needs "context sensitive" parsers to extract such structure. Context-sensitive parsers are hard to build, so the engineering compromise is to use "context-free" grammars and add hacks to the parsers ("symbol tables", etc.) to handle the context-sensitive part.

Neither lexing nor parsing technology is likely to go away soon.

They may be unified by deciding to use "parsing" technology to recognize "words", as is currently explored by so-called scannerless GLR parsers. That has a runtime cost, as you are applying more general machinery to what is often a problem that doesn't need it, and usually you pay for that in overhead. Where you have lots of free cycles, that overhead may not matter. If you process a lot of text, then the overhead does matter and classical regular expression parsers will continue to be used.

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

How to retrieve the first word of the output of a command in bash?

I was working with a embedded device which had neither perl, awk or python and did it with sed instead. It supports multiple spaces before the first word (which the cut and bash solutions did not handle).

VARIABLE="  first_word_with_spaces_before_and_after  another_word  "
echo $VARIABLE | sed 's/ *\([^ ]*\).*/\1/'

This was very useful when grepping ps for process IDs since the other solutions here using only bash was not able to remove the first spaces which ps uses to align.

How to update Ruby to 1.9.x on Mac?

There are several other version managers to consider, see for a few examples and one that's not listed there that I'll be giving a try soon is ch-ruby. I tried rbenv but had too many problems with it. RVM is my mainstay, though it sometimes has the odd problem (hence my wish to try ch-ruby when I get a chance). I wouldn't touch the system Ruby, as other things may rely on it.

I should add I've also compiled my own Ruby several times, and using the Hivelogic article (as Dave Everitt has suggested) is a good idea if you take that route.

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

Split a String into an array in Swift?

Swift 4

let words = "these words will be elements in an array".components(separatedBy: " ")

How to unapply a migration in ASP.NET Core with EF Core

In general if you are using the Package Manager Console the right way to remove a specific Migration is by referencing the name of the migration

Update-Database -Migration {Name of Migration} -Context {context}

Another way to remove the last migration you have applied according to the docs is by using the command:

dotnet ef migrations remove

This command should be executed from the developer command prompt (how to open command prompt) inside your solution directory.

For example if your application is inside name "Application" and is in the folder c:\Projects. Then your path should be:

C:\Projects\Application

iOS how to set app icon and launch images

You can easily do it without resizing yourself or doing anything, just choose your icon at an app store icon generator website https://getappscreenshots.com/app-icon-generator and it'll generate all required files and all icon sizes so you can just copy the files and paste in your project's folder!

JSON.NET Error Self referencing loop detected for type

For .NET Core 3.0, update the Startup.cs class as shown below.

public void ConfigureServices(IServiceCollection services)
{
...

services.AddControllers()
    .AddNewtonsoftJson(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

...
}

See: https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-core-3-0-preview-5/

Need to combine lots of files in a directory

Yes , A plugin is available named "combine" for notepad++.Link: .>> Combine Plugin for Notepad++

You can install it via plugin manager. Extra benifit of this plugin is: "You can maintain the sequence of files while merging, it's according to the sequence of opened files are opened (see tabs)".

Query to get only numbers from a string

Firstly find out the number's starting length then reverse the string to find out the first position again(which will give you end position of number from the end). Now if you deduct 1 from both number and deduct it from string whole length you'll get only number length. Now get the number using SUBSTRING

declare @fieldName nvarchar(100)='AAAA1221.121BBBB'

declare @lenSt int=(select PATINDEX('%[0-9]%', @fieldName)-1)
declare @lenEnd int=(select PATINDEX('%[0-9]%', REVERSE(@fieldName))-1)

select SUBSTRING(@fieldName, PATINDEX('%[0-9]%', @fieldName), (LEN(@fieldName) - @lenSt -@lenEnd))

Jackson and generic type reference

I modified rushidesai1's answer to include a working example.

JsonMarshaller.java

import java.io.*;
import java.util.*;

public class JsonMarshaller<T> {
    private static ClassLoader loader = JsonMarshaller.class.getClassLoader();

    public static void main(String[] args) {
        try {
            JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
            String jsonString = read(loader.getResourceAsStream("data.json"));
            List<Station> stations = marshaller.unmarshal(jsonString);
            stations.forEach(System.out::println);
            System.out.println(marshaller.marshal(stations));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("resource")
    public static String read(InputStream ios) {
        return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
    }
}

Output

Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]

JsonMarshallerUnmarshaller.java

import java.io.*;
import java.util.List;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

public class JsonMarshallerUnmarshaller<T> {
    private ObjectMapper mapper;
    private Class<T> targetClass;

    public JsonMarshallerUnmarshaller(Class<T> targetClass) {
        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

        mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(introspector);
        mapper.getSerializationConfig().with(introspector);

        this.targetClass = targetClass;
    }

    public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
        return parseList(jsonString, mapper, targetClass);
    }

    public String marshal(List<T> list) throws JsonProcessingException {
        return mapper.writeValueAsString(list);
    }

    public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(str, listType(mapper, clazz));
    }

    public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(is, listType(mapper, clazz));
    }

    public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
        return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
    }
}

Station.java

public class Station {
    private long id;
    private String title;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
    }
}

data.json

[{
  "id": 123,
  "title": "my title",
  "name": "my name"
}, {
  "id": 456,
  "title": "my title 2",
  "name": "my name 2"
}]

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

How can I give the Intellij compiler more heap space?

I had a similar problem with Ant build (started by hand from IDEA GUI). In my case there was the right solution to right click on the Ant task, choose properties and set a higher value to "Maximum heap space (Mb):" and "Maximum stack space (Mb):" input fields.

enter image description here

How to apply CSS page-break to print a table with lots of rows?

You should use

<tbody> 
  <tr>
  first page content here 
  </tr>
  <tr>
  ..
  </tr>
</tbody>
<tbody>
  next page content...
</tbody>

And CSS:

tbody { display: block; page-break-before: avoid; }
tbody { display: block; page-break-after: always; }

Finding second occurrence of a substring in a string in Java

You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy

public static ArrayList<Integer> occurrencesPos(String str, String substr) {
    final boolean ignoreCase = true;
    int substrLength = substr.length();
    int strLength = str.length();

    ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();

    for(int i = 0; i < strLength - substrLength + 1; i++) {
        if(str.regionMatches(ignoreCase, i, substr, 0, substrLength))  {
            occurrenceArr.add(i);
        }
    }
    return occurrenceArr;
}

Use latest version of Internet Explorer in the webbrowser control

It is best to force the highest mode possible. That can be accomplished by adding:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

and it is always good to include the polyfill library in order to support IE:

<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>

before any script.

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

Re-order columns of table in Oracle

Use the View for your efforts in altering the position of the column: CREATE VIEW CORRECTED_POSITION AS SELECT co1_1, col_3, col_2 FROM UNORDERDED_POSITION should help.

This requests are made so some reports get produced where it is using SELECT * FROM [table_name]. Or, some business has a hierarchy approach of placing the information in order for better readability from the back end.

Thanks Dilip

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

How to set value to variable using 'execute' in t-sql?

The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised

You'll have to use a temp table/table variable outside of the dynamic SQL:

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)

INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')  

select * FROM @siteId

Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY

What does the "@" symbol do in Powershell?

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is denoted @().

How to increase number of threads in tomcat thread pool?

Sounds like you should stay with the defaults ;-)

Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.

See here how to configure...

Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html

Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html

Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html

Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html

How to see top processes sorted by actual memory usage?

First, repeat this mantra for a little while: "unused memory is wasted memory". The Linux kernel keeps around huge amounts of file metadata and files that were requested, until something that looks more important pushes that data out. It's why you can run:

find /home -type f -name '*.mp3'
find /home -type f -name '*.aac'

and have the second find instance run at ridiculous speed.

Linux only leaves a little bit of memory 'free' to handle spikes in memory usage without too much effort.

Second, you want to find the processes that are eating all your memory; in top use the M command to sort by memory use. Feel free to ignore the VIRT column, that just tells you how much virtual memory has been allocated, not how much memory the process is using. RES reports how much memory is resident, or currently in ram (as opposed to swapped to disk or never actually allocated in the first place, despite being requested).

But, since RES will count e.g. /lib/libc.so.6 memory once for nearly every process, it isn't exactly an awesome measure of how much memory a process is using. The SHR column reports how much memory is shared with other processes, but there is no guarantee that another process is actually sharing -- it could be sharable, just no one else wants to share.

The smem tool is designed to help users better gage just how much memory should really be blamed on each individual process. It does some clever work to figure out what is really unique, what is shared, and proportionally tallies the shared memory to the processes sharing it. smem may help you understand where your memory is going better than top will, but top is an excellent first tool.

How link to any local file with markdown syntax?

If you have spaces in the filename, try these:

[file](./file%20with%20spaces.md)
[file](<./file with spaces.md>)

First one seems more reliable

How to bind an enum to a combobox control in WPF?

Nick's solutuion can be simplified more, with nothing fancy, you would only need a single converter:

[ValueConversion(typeof(Enum), typeof(IEnumerable<Enum>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var r = Enum.GetValues(value.GetType());
        return r;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

You then use this wherever you want your combo box to appear:

<ComboBox ItemsSource="{Binding PagePosition, Converter={converter:EnumToCollectionConverter}, Mode=OneTime}"  SelectedItem="{Binding PagePosition}" />

Cannot run Eclipse; JVM terminated. Exit code=13

I had the same error when configuring eclipse.ini to use JRE6. Turns out I caused this error by incorrectly configuring eclipse to use the 64 bit JVM while running a 32 bit version of eclipse 3.7.

The correct configuration required the eclipse.ini -vm argumument to use "C:/Program Files (x86)/" instead of "C:/Program Files/".

Make sure that the JVM version (32/64 bit) you use matches the eclipse version (32/64 bit).

Getting the last element of a list

In Python, how do you get the last element of a list?

To just get the last element,

  • without modifying the list, and
  • assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation

Indexes and slices can take negative integers as arguments.

I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python", -1 references the last element, the character, 'n':

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking

This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable - not just lists):

>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:

>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:

*_, last = a_list

Or, really, if you know it's a list (or at least accepts subscript notation):

last = a_list[-1]

In a function

A commenter said:

I wish Python had a function for first() and last() like Lisp does... it would get rid of a lot of unnecessary lambda functions.

These would be quite simple to define:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter:

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases

If you're doing something more complicated, you may find it more performant to get the last element in slightly different ways.

If you're new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.

I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I'm leaving a caveat out.

Slicing

A slice of a list returns a new list - so we can slice from -1 to the end if we are going to want the element in a new list:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:

  • a new list created
  • and the new list to be empty if the prior list was empty.

for loops

As a feature of Python, there is no inner scoping in a for loop.

If you're performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

This is not semantically the last thing in the list. This is semantically the last thing that the name, item, was bound to.

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you

  • are already looping, and
  • you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.

Getting and removing it

We can also mutate our original list by removing and returning the last element:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.

(-1 is actually the default argument, so list.pop can be used without an index argument):

>>> a_list.pop()
'two'

Only do this if

  • you know the list has elements in it, or are prepared to handle the exception if it is empty, and
  • you do intend to remove the last element from the list, treating it like a stack.

These are valid use-cases, but not very common.

Saving the rest of the reverse for later:

I don't know why you'd do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next:

>>> next(reversed([1,2,3]))
3

So it's like doing the reverse of this:

>>> next(iter([1,2,3]))
1

But I can't think of a good reason to do this, unless you'll need the rest of the reverse iterator later, which would probably look more like this:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:

>>> use_later
[2, 1]
>>> last_element
3

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

I just run into the similar issue today. Unfortunately my HD died on me so I couldn't do the migration mentioned here in the accepted answer. I had to do the following steps:

  1. Connect to the Apple Developer member center then the iOS provisional portal.
  2. Revoke my certificate.
  3. Create a new certificate by providing a new pair of private and public key.
  4. Remove all the previous provisioning profiles and create new ones.
  5. Download the new provisioning profiles and install them in Xcode by just dragging them to the Xcode icon in the dock.

The same action is also mentioned on this post.

Date format in dd/MM/yyyy hh:mm:ss

SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)

Error "library not found for" after putting application in AdMob

This happens if you're using cocoapods, use the .xcworkspace file instead of the default .xcodeproj file.

Turning Sonar off for certain code

You can annotate a class or a method with SuppressWarnings

@java.lang.SuppressWarnings("squid:S00112")

squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

How To have Dynamic SQL in MySQL Stored Procedure

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.

Is it ok to scrape data from Google results?

Google will eventually block your IP when you exceed a certain amount of requests.

Classpath including JAR within a JAR

If you are building with ant (I am using ant from eclipse), you can just add the extra jar files by saying to ant to add them... Not necessarily the best method if you have a project maintained by multiple people but it works for one person project and is easy.

for example my target that was building the .jar file was:

<jar destfile="${plugin.jar}" basedir="${plugin.build.dir}">
    <manifest>
        <attribute name="Author" value="ntg"/>
        ................................
        <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/>
    </manifest>
</jar>

I just added one line to make it:

<jar ....">
    <zipgroupfileset dir="${external-lib-dir}" includes="*.jar"/>
    <manifest>
        ................................
    </manifest>
</jar>

where

<property name="external-lib-dir" 
          value="C:\...\eclipseWorkspace\Filter\external\...\lib" />

was the dir with the external jars. And that's it...

jquery - is not a function error

When converting an ASP.Net webform prototype to a MVC site I got these errors:

TypeError: $(...).accordion is not a function
$("#accordion").accordion(


$('#dialog').dialog({
TypeError: $(...).dialog is not a function

It worked fine in the webforms. The problem/solution was this line in the _Layout.cshtml

@Scripts.Render("~/bundles/jquery")

Comment it out to see if the errors go away. Then fix it in the BundlesConfig:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

Get individual query parameters from Uri

This should work:

string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters = 
   System.Web.HttpUtility.ParseQueryString(querystring);

According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.

Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

It seems that in the debug log for Java 6 the request is send in SSLv2 format.

main, WRITE: SSLv2 client hello message, length = 110

This is not mentioned as enabled by default in Java 7.
Change the client to use SSLv3 and above to avoid such interoperability issues.

Look for differences in JSSE providers in Java 7 and Java 6

Extract digits from a string in Java

I inspired by code Sean Patrick Floyd and little rewrite it for maximum performance i get.

public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );

    while ( buffer.hasRemaining() ) {
        char chr = buffer.get();
        if ( chr > 47 && chr < 58 )
            result[cursor++] = chr;
    }

    return new String( result, 0, cursor );
}

i do Performance test to very long String with minimal numbers and result is:

  • Original code is 25,5% slower
  • Guava approach is 2.5-3 times slower
  • Regular expression with D+ is 3-3.5 times slower
  • Regular expression with only D is 25+ times slower

Btw it depends on how long that string is. With string that contains only 6 number is guava 50% slower and regexp 1 times slower

Disable Laravel's Eloquent timestamps

If you only need to only to disable updating updated_at just add this method to your model.

public function setUpdatedAtAttribute($value)
{
    // to Disable updated_at
}

This will override the parent setUpdatedAtAttribute() method. created_at will work as usual. Same way you can write a method to disable updating created_at only.

How to make Visual Studio copy a DLL file to the output directory?

Add builtin COPY in project.csproj file:

  <Project>
    ...
    <Target Name="AfterBuild">
      <Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Debug\bin" SkipUnchangedFiles="false" />
      <Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Release\bin" SkipUnchangedFiles="false" />
    </Target>
  </Project>

How do I make a simple makefile for gcc on Linux?

For example this simple Makefile should be sufficient:

CC=gcc 
CFLAGS=-Wall

all: program
program: program.o
program.o: program.c program.h headers.h

clean:
    rm -f program program.o
run: program
    ./program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied

jquery input select all on focus

There are some decent answers here and @user2072367 's is my favorite, but it has an unexpected result when you focus via tab rather than via click. ( unexpected result: to select text normally after focus via tab, you must click one additional time )

This fiddle fixes that small bug and additionally stores $(this) in a variable to avoid redundant DOM selection. Check it out! (:

Tested in IE > 8

$('input').on('focus', function() {
    var $this = $(this)
        .one('mouseup.mouseupSelect', function() {
            $this.select();
            return false;
        })
        .one('mousedown', function() {
            // compensate for untriggered 'mouseup' caused by focus via tab
            $this.off('mouseup.mouseupSelect');
        })
        .select();
});

Python: 'break' outside loop

This is an old question, but if you wanted to break out of an if statement, you could do:

while 1:
    if blah:
        break

PHP - Getting the index of a element from a array

foreach() {
    $i++;
    if(index($key) == $i){}
    //
}

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Take a look at FileSaver.js. It provides a handy saveAs function which takes care of most browser specific quirks.

How to get label text value form a html page?

Use innerText/textContent:

  var el = document.getElementById('*spaM4');
  console.log(el.innerText || el.textContent);

Fiddle: http://jsfiddle.net/NeTgC/2/

__proto__ VS. prototype in JavaScript

I've made for myself a small drawing that represents the following code snippet:

var Cat = function() {}
var tom = new Cat()

Understanding __proto__ and prototype

I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)

Objects in JavaScript have properties and __proto__ is just one of them.

The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.

The root object in JavaScript is Object.prototype and all other objects are descendants of this one. The __proto__ property of the root object is null, which represents the end of inheritance chain.

You'll notice that prototype is a property of functions. Cat is a function, but also Function and Object are (native) functions. tom is not a function, thus it does not have this property.

The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new operator on that function.

Note that prototype objects (yellow rectangles) have another property called constructor which points back to the respective function object. For brevity reasons this was not depicted.

Indeed, when we create the tom object with new Cat(), the created object will have the __proto__ property set to the prototype object of the constructor function.

In the end, let us play with this diagram a bit. The following statements are true:

  • tom.__proto__ property points to the same object as Cat.prototype.

  • Cat.__proto__ points to the Function.prototype object, just like Function.__proto__ and Object.__proto__ do.

  • Cat.prototype.__proto__ and tom.__proto__.__proto__ point to the same object and that is Object.prototype.

Cheers!

How to run Node.js as a background process and never die?

nohup will allow the program to continue even after the terminal dies. I have actually had situations where nohup prevents the SSH session from terminating correctly, so you should redirect input as well:

$ nohup node server.js </dev/null &

Depending on how nohup is configured, you may also need to redirect standard output and standard error to files.

How to instantiate a File object in JavaScript?

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.

google maps v3 marker info window on mouseover

var icon1 = "imageA.png";
var icon2 = "imageB.png";

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: icon1,
    title: "some marker"
});

google.maps.event.addListener(marker, 'mouseover', function() {
    marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
    marker.setIcon(icon1);
});

How to convert from java.sql.Timestamp to java.util.Date?

java.sql.ResultSet rs;
//fill rs somehow
java.sql.Timestamp timestamp = rs.getTimestamp(1); //get first column
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
java.util.Date date = return new java.util.Date(milliseconds);

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Permanently add a directory to PYTHONPATH?

Adding export PYTHONPATH="${PYTHONPATH}:/my/other/path" to the ~/.bashrc might not work if PYTHONPATH does not currently exist (because of the :).

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

Adding the above to my ~/.bashrc did the trick for me on Ubuntu 16.04

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Self-Signed Certificate Authorities pip / conda

After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:

NEVER disable all SSL verification!

This creates a bad security culture. Don't be that person.

tl;dr

pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify

# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt

But where do we get ca-bundle.crt?


Get an up to date CA Bundle

cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox

https://curl.haxx.se/docs/caextract.html

I recommend you open up this cacert.pem file in a text editor as we will need to add our self-signed CA to this file.

Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:

----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----

https://support.ssl.com/Knowledgebase/Article/View/19/0/der-vs-crt-vs-cer-vs-pem-certificates-and-how-to-convert-them


Getting our Self Signed Certificate

Below are a few options on how to get our self signed certificate:

  • Via OpenSSL CLI
  • Via Browser
  • Via Python Scripting

Get our Self-Signed Certificate by OpenSSL CLI

https://unix.stackexchange.com/questions/451207/how-to-trust-self-signed-certificate-in-curl-command-line/468360#468360

echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem

Get our Self-Signed Certificate Authority via Browser

Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.

Copy the contents of this exported file and paste it at the end of your cacerts.pem file.

For consistency rename this file cacerts.pem --> ca-bundle.crt and place it somewhere easy like:

# Windows
%USERPROFILE%\certs\ca-bundle.crt

# or *nix
$HOME/certs/cabundle.crt

Get our Self-Signed Certificate Authority via Python

Thanks to all the brilliant answers in:

How to get response SSL certificate from requests in python?

I have put together the following to attempt to take it a step further.

https://github.com/neozenith/get-ca-py


Finally

Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.

pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt

OR

pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt

THEN

pip config list
conda config --show ssl_verify

# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'

References

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

Adding div element to body or document in JavaScript

Try this out:-

http://jsfiddle.net/adiioo7/vmfbA/

Use

document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

instead of

document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

Edit:- Ideally you should use body.appendChild method instead of changing the innerHTML

var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);

What is the difference between 'git pull' and 'git fetch'?

A git repository contains immutable data blobs and a few mutable pointers/references/names (we call them branches, HEADS) for usability (in theory, git could be a pure append-only store, accessed only by commit hashes).

The immutable blobs are usually always eventually shared among all contributors. Every developer has a copy of all of these on his machine.

git fetch downloads the latest blobs and remote mutable files to your machine.

It does not change your mutable files nor create any blobs that did not previously exist somewhere.

git pull is git fetch then git merge. git merge creates new blobs that never existed in the remote repository before and updates your mutable files (your references).

How to get a cross-origin resource sharing (CORS) post request working

I had the exact same issue where jquery ajax only gave me cors issues on post requests where get requests worked fine - I tired everything above with no results. I had the correct headers in my server etc. Changing over to use XMLHTTPRequest instead of jquery fixed my issue immediately. No matter which version of jquery I used it didn't fix it. Fetch also works without issues if you don't need backward browser compatibility.

        var xhr = new XMLHttpRequest()
        xhr.open('POST', 'https://mywebsite.com', true)
        xhr.withCredentials = true
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 2) {// do something}
        }
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(json)

Hopefully this helps anyone else with the same issues.

Posting raw image data as multipart/form-data in curl

CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA

// files to upload

$filename = "https://example.s3.amazonaws.com/0.jpg";       

// URL to upload to (Destination server)

$url = "https://otherserver/image";

AND

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        //CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => file_get_contents($filename),
        CURLOPT_HTTPHEADER => array(
            //"Authorization: Bearer $TOKEN",
            "Content-Type: multipart/form-data",
            "Content-Length: " . strlen(file_get_contents($filename)),
            "API-Key: abcdefghi" //Optional if required
        ),
    ));

   $response = curl_exec($curl);

    $info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";

//print_r($info['request_header']);

    var_dump($response);
    $err = curl_error($curl);

    echo "error";
    var_dump($err);
    curl_close($curl);

Java, How to get number of messages in a topic in apache kafka

I haven't tried this myself, but it seems to make sense.

You can also use kafka.tools.ConsumerOffsetChecker (source).

OR, AND Operator

I'm not sure if this answers your question, but for example:

if (A || B)
{
    Console.WriteLine("Or");
}

if (A && B)
{
    Console.WriteLine("And");
}

How to make an empty div take space

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key here is the Box-Sizing and Padding.

Using comma as list separator with AngularJS

Also:

angular.module('App.filters', [])
    .filter('joinBy', function () {
        return function (input,delimiter) {
            return (input || []).join(delimiter || ',');
        };
    });

And in template:

{{ itemsArray | joinBy:',' }}

How to check if mysql database exists

Using the INFORMATION_SCHEMA or show databases is not reliable when you do not have enough permissions to see the database. It will seem that the DB does not exist when you just don't have access to it. The creation would then fail afterwards. Another way to have a more precise check is to use the output of the use command, even though I do not know how solid this approach could be (text output change in future versions / other languages...) so be warned.

CHECK=$(mysql -sNe "use DB_NAME" 2>&1)
if [ $? -eq 0 ]; then
  # database exists and is accessible
elif [ ! -z "$(echo $CHECK | grep 'Unknown database')" ]; then
  # database does not exist
elif [ ! -z "$(echo $CHECK | grep 'Access denied')" ]; then
  # cannot tell if database exists (not enough permissions)"
else
  # unexpected output
fi

gradlew command not found?

In addition is @suraghch

Linux / MacOS ./gradlew clean

Windows PowerShell .\gradlew clean

Windows cmd gradlew clean

Verifying a specific parameter with Moq

A simpler way would be to do:

ObjectA.Verify(
    a => a.Execute(
        It.Is<Params>(p => p.Id == 7)
    )
);

Decoding JSON String in Java

Well your jsonString is wrong.

String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{\"1\":2},{\"2\":3}]}}";

use this jsonString and if you use the same JSONParser and ContainerFactory in the example you will see that it will be encoded/decoded.

Additionally if you want to print your string after stat here it goes:

     try{
        Map json = (Map)parser.parse(jsonString, containerFactory);
        Iterator iter = json.entrySet().iterator();
        System.out.println("==iterate result==");
        Object entry = json.get("stat");
        System.out.println(entry);
      }

And about the json libraries, there are a lot of them. Better you check this.

Determining the last row in a single column

To get the number of columns or last column's index:

var numColumns = sheet.getLastColumn()

To get the no of rows or last row's index:

var numRows = sheet.getLastRow()

where

var sheet = SpreadsheetApp.getActiveSheet()

Concat all strings inside a List<string> using LINQ

I have done this using LINQ:

var oCSP = (from P in db.Products select new { P.ProductName });

string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));

In Django, how do I check if a user is in a certain group?

You just need one line:

from django.contrib.auth.decorators import user_passes_test  

@user_passes_test(lambda u: u.groups.filter(name='companyGroup').exists())
def you_view():
    return HttpResponse("Since you're logged in, you can see this text!")

Java Replace Character At Specific Position Of String?

Use StringBuilder:

StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();

Checking if any elements in one list are in another

I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.

def reachedGoal(a,b):
    if(len(a)!=len(b)):
        raise ValueError("Wrong lists provided")

    for val1 in range(0,len(a)):
        temp1=a[val1]
        temp2=b[val1]
        for val2 in range(0,len(b)):
            if(temp1[val2]!=temp2[val2]):
                return False
    return True

Exploring Docker container's file system

On Ubuntu 14.04 running Docker 1.3.1, I found the container root filesystem on the host machine in the following directory:

/var/lib/docker/devicemapper/mnt/<container id>/rootfs/

Full Docker version information:

Client version: 1.3.1
Client API version: 1.15
Go version (client): go1.3.3
Git commit (client): 4e9bbfa
OS/Arch (client): linux/amd64
Server version: 1.3.1
Server API version: 1.15
Go version (server): go1.3.3
Git commit (server): 4e9bbfa

Clearing content of text file using C#

You can use always stream writer.It will erase old data and append new one each time.

using (StreamWriter sw = new StreamWriter(filePath))
{                            
    getNumberOfControls(frm1,sw);
}

Passive Link in Angular 2 - <a href=""> equivalent

A really simple solution is not to use an A tag - use a span instead:

<span class='link' (click)="doSomething()">Click here</span>

span.link {
  color: blue;
  cursor: pointer;
  text-decoration: underline;
}

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

Comparing object properties in c#

sometimes you don't want to compare all public properties and want to compare only the subset of them, so in this case you can just move logic to compare the desired list of properties to abstract class

public abstract class ValueObject<T> where T : ValueObject<T>
{
    protected abstract IEnumerable<object> GetAttributesToIncludeInEqualityCheck();

    public override bool Equals(object other)
    {
        return Equals(other as T);
    }

    public bool Equals(T other)
    {
        if (other == null)
        {
            return false;
        }

        return GetAttributesToIncludeInEqualityCheck()
            .SequenceEqual(other.GetAttributesToIncludeInEqualityCheck());
    }

    public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
    {
        return !(left == right);
    }

    public override int GetHashCode()
    {
        int hash = 17;
        foreach (var obj in this.GetAttributesToIncludeInEqualityCheck())
            hash = hash * 31 + (obj == null ? 0 : obj.GetHashCode());

        return hash;
    }
}

and use this abstract class later to compare the objects

public class Meters : ValueObject<Meters>
{
    ...

    protected decimal DistanceInMeters { get; private set; }

    ...

    protected override IEnumerable<object> GetAttributesToIncludeInEqualityCheck()
    {
        return new List<Object> { DistanceInMeters };
    }
}

java.lang.UnsupportedClassVersionError

Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

Setting width and height

Works for me too

responsive:true
maintainAspectRatio: false


<div class="row">
        <div class="col-xs-12">
            <canvas id="mycanvas" width="500" height="300"></canvas>
        </div>
    </div>

Thank You

Using local makefile for CLion instead of CMake

Currently, only CMake is supported by CLion. Others build systems will be added in the future, but currently, you can only use CMake.

An importer tool has been implemented to help you to use CMake.

Edit:

Source : http://blog.jetbrains.com/clion/2014/09/clion-answers-frequently-asked-questions/

Return JSON for ResponseEntity<String>

This is a String, not a json structure(key, value), try:

return new ResponseEntity("{"vale" : "This is a String"}", HttpStatus.OK);

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

With EF 7:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Column(TypeName = "datetime2")]
DateTime? Dateadded { get; set; }

migration script:

AlterColumn("myschema.mytable", "Dateadded", c => c.DateTime(nullable: false, precision: 7, storeType: "datetime2", defaultValueSql: "getutcdate()"));

result:

ALTER TABLE [MySchema].[MyTable] ADD  CONSTRAINT [DF_MySchema.MyTable_Dateadded]  DEFAULT (getutcdate()) FOR [Dateadded]

How can I find all the subsets of a set, with exactly n elements?

Here's a function that gives you all subsets of the integers [0..n], not just the subsets of a given length:

from itertools import combinations, chain

def allsubsets(n):
    return list(chain(*[combinations(range(n), ni) for ni in range(n+1)]))

so e.g.

>>> allsubsets(3)
[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]

Getting Textarea Value with jQuery

you have id="#message"... should be id="message"

http://jsfiddle.net/q5EXG/1/

NULL or BLANK fields (ORACLE)

You can not count nulls (at least not in Oracle). Instead try this

SELECT count(1) FROM TABLE WHERE COL_NAME IS NULL

How can I return two values from a function in Python?

I would like to return two values from a function in two separate variables.

What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.

Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).

When i tried to to use return i, card, it returns a tuple and this is not what i want.

Actually, it's exactly what you want. All you have to do is take the tuple apart again.

And i want to be able to use these values separately.

So just grab the values out of the tuple.

The easiest way to do this is by unpacking:

a, b = select_choice()

How to add a progress bar to a shell script?

I wanted to track progress based on the number of lines a command output against a target number of lines from a previous run:

#!/bin/bash
function lines {
  local file=$1
  local default=$2
  if [[ -f $file ]]; then
    wc -l $file | awk '{print $1}';
  else
    echo $default
  fi
}

function bar {
  local items=$1
  local total=$2
  local size=$3
  percent=$(($items*$size/$total % $size))
  left=$(($size-$percent))
  chars=$(local s=$(printf "%${percent}s"); echo "${s// /=}")
  echo -ne "[$chars>";
  printf "%${left}s"
  echo -ne ']\r'
}

function clearbar {
  local size=$1
  printf " %${size}s  "
  echo -ne "\r"
}

function progress {
  local pid=$1
  local total=$2
  local file=$3

  bar 0 100 50
  while [[ "$(ps a | awk '{print $1}' | grep $pid)" ]]; do
    bar $(lines $file 0) $total 50
    sleep 1
  done
  clearbar 50
  wait $pid
  return $?
}

Then use it like this:

target=$(lines build.log 1000)
(mvn clean install > build.log 2>&1) &
progress $! $target build.log

It outputs a progress bar that looks something like this:

[===============================================>   ]

The bar grows as the number of lines output reaches the target. If the number of lines exceeds the target, the bar starts over (hopefully the target is good).

BTW: I'm using bash on Mac OSX. I based this code on a spinner from mariascio.

How to open html file?

CODE:

import codecs

path="D:\\Users\\html\\abc.html" 
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

Format with Currency format string

=Format(Fields!Price.Value, "C")

It will give you 2 decimal places with "$" prefixed.

You can find other format strings on MSDN: Adding Style and Formatting to a ReportViewer Report

Note: The MSDN article has been archived to the "VS2005_General" document, which is no longer directly accessible online. Here is the excerpt of the formatting strings referenced:

Formatting Numbers

The following table lists common .NET Framework number formatting strings.

Format string, Name

C or c Currency

D or d Decimal

E or e Scientific

F or f Fixed-point

G or g General

N or n Number

P or p Percentage

R or r Round-trip

X or x Hexadecimal

You can modify many of the format strings to include a precision specifier that defines the number of digits to the right of the

decimal point. For example, a formatting string of D0 formats the number so that it has no digits after the decimal point. You

can also use custom formatting strings, for example, #,###.

Formatting Dates

The following table lists common .NET Framework date formatting strings.

Format string, Name

d Short date

D Long date

t Short time

T Long time

f Full date/time (short time)

F Full date/time (long time)

g General date/time (short time)

G General date/time (long time)

M or m Month day

R or r RFC1123 pattern

Y or y Year month

You can also a use custom formatting strings; for example, dd/MM/yy. For more information about .NET Framework formatting strings, see Formatting Types.

How to execute an external program from within Node.js?

var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
    // result
});

How to clone an InputStream?

The class below should do the trick. Just create an instance, call the "multiply" method, and provide the source input stream and the amount of duplicates you need.

Important: you must consume all cloned streams simultaneously in separate threads.

package foo.bar;

import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class InputStreamMultiplier {
    protected static final int BUFFER_SIZE = 1024;
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public InputStream[] multiply(final InputStream source, int count) throws IOException {
        PipedInputStream[] ins = new PipedInputStream[count];
        final PipedOutputStream[] outs = new PipedOutputStream[count];

        for (int i = 0; i < count; i++)
        {
            ins[i] = new PipedInputStream();
            outs[i] = new PipedOutputStream(ins[i]);
        }

        executorService.execute(new Runnable() {
            public void run() {
                try {
                    copy(source, outs);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        return ins;
    }

    protected void copy(final InputStream source, final PipedOutputStream[] outs) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        int n = 0;
        try {
            while (-1 != (n = source.read(buffer))) {
                //write each chunk to all output streams
                for (PipedOutputStream out : outs) {
                    out.write(buffer, 0, n);
                }
            }
        } finally {
            //close all output streams
            for (PipedOutputStream out : outs) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Adding an assets folder in Android Studio

To specify any additional asset folder I've used this with my Gradle. This adds moreAssets, a folder in the project root, to the assets.

android {
    sourceSets {
        main.assets.srcDirs += '../moreAssets'
    }
}

Why is semicolon allowed in this python snippet?

It's allowed because authors decided to allow it: https://docs.python.org/2/reference/simple_stmts.html

If move to question why authors decided todo so, I guess it's so because semi-column is allowed as simple statement termination at least in the following langages: C++, C, C#, R, Matlab,Perl,...

So it's faster to move into usage of Python for people with background in other language. And there are no lose of generality in such deicison.

Homebrew install specific version of formula?

I've tried most of the solutions here and they are outdated. I had to combine some ideas from here with my own work. As a result I've created a script to help me do the heavy lifting which you can find here

Usage:

brewv.sh formula_name desired_version

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is only supported by IE - the other browsers use a plugin architecture called NPAPI. However, there's a cross-browser plugin framework called Firebreath that you might find useful.

Does Visual Studio have code coverage for unit tests?

For anyone that is looking for an easy solution in Visual Studio Community 2019, Fine Code Coverage is simple but it works well.

It cannot give accurate numbers on the precise coverage, but it will tell which lines are being covered with green/red gutters.

Multi-line string with extra space (preserved indentation)

Just to mention a simple one-line concatenation as it can be useful sometimes.

# for bash

v=" guga "$'\n'"   puga "

# Just for an example.
v2="bar "$'\n'"   foo "$'\n'"$v"

# Let's simplify the previous version of $v2.
n=$'\n'
v3="bar ${n}   foo ${n}$v"

echo "$v3" 

You'll get something like this

bar 
   foo 
 guga 
   puga 

All leading and ending white spaces will be preserved right for

echo "$v3" > filename

Create directories using make file

Or, KISS.

DIRS=build build/bins

... 

$(shell mkdir -p $(DIRS))

This will create all the directories after the Makefile is parsed.

how to stop Javascript forEach?

forEach does not break on return, there are ugly solutions to get this work but I suggest not to use it, instead try to use Array.prototype.some or Array.prototype.every

_x000D_
_x000D_
var ar = [1,2,3,4,5];_x000D_
_x000D_
ar.some(function(item,index){_x000D_
  if(item == 3){_x000D_
     return true;_x000D_
  }_x000D_
  console.log("item is :"+item+" index is : "+index);_x000D_
});
_x000D_
_x000D_
_x000D_

Git push requires username and password

I just came across the same problem, and the simplest solution I found was to use SSH URL instead of HTTPS one:

ssh://[email protected]/username/repo.git

And not this:

https://github.com/username/repo.git

You can now validate with just the SSH key instead of the username and password.

Oracle listener not running and won't start

I solved it by updating listener.ora file inside oracle directory oraclexe\app\oracle\product\11.2.0\server\network\ADMIN.

Why did it happen to me was because I changed my system name but inside listener.ora there was old name for HOST.

This might be one of the reasons... for those who still face such issue might think of this possibility as well.

openCV video saving in python

Please make sure to set correct width and height. You can set it like bellow

cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you have this listener:

    <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on"/>

on your server.xml, remove it and try. You can not use a keystore if you are using the APR connector

extract the date part from DateTime in C#

DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date

if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.

code snippet

DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
    Console.WriteLine("d1 < d2");
else
    if (d1.DayOfYear < d2.DayOfYear)
        Console.WriteLine("d1 < d2");

Aborting a shell script if any command returns a non-zero value

An expression like

dosomething1 && dosomething2 && dosomething3

will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":

cat nosuchfile && echo "done"
echo $?
1

How can I simulate an array variable in MySQL?

Inspired by the function ELT(index number, string1, string2, string3,…),I think the following example works as an array example:

set @i := 1;
while @i <= 3
do
  insert into table(val) values (ELT(@i ,'val1','val2','val3'...));
set @i = @i + 1;
end while;

Hope it help.

How do I add options to a DropDownList using jQuery?

You may want to clear your DropDown first $('#DropDownQuality').empty();

I had my controller in MVC return a select list with only one item.

$('#DropDownQuality').append(
        $('<option></option>').val(data[0].Value).html(data[0].Text));    

How to make an installer for my C# application?

  1. Add a new install project to your solution.
  2. Add targets from all projects you want to be installed.
  3. Configure pre-requirements and choose "Check for .NET 3.5 and SQL Express" option. Choose the location from where missing components must be installed.
  4. Configure your installer settings - company name, version, copyright, etc.
  5. Build and go!

Warning: comparison with string literals results in unspecified behaviour

There is a distinction between 'a' and "a":

  • 'a' means the value of the character a.
  • "a" means the address of the memory location where the string "a" is stored (which will generally be in the data section of your program's memory space). At that memory location, you will have two bytes -- the character 'a' and the null terminator for the string.

RSA: Get exponent and modulus given a public key

I manage to find the answer for this solution, have to do javascript injection for this to install atob

const atob:any = require('atob');
asn1(pem: any){
      asn1parser.Enc.base64ToBuf = function (b64:any) {
    return asn1parser.Enc.binToBuf(atob(b64));
  };
  const dertest = asn1parser.PEM.parseBlock(pem).der;
   var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
   var buf = asn1parser.ASN1.parse(dertest);
  var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );

This declaration has no storage class or type specifier in C++

You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :--> (inside main)

Orderbook o1;
o1.m.check(side)

but that would be unnecessary. Keeping things short :-

You can't call functions inside a Class

CSS: How to position two elements on top of each other, without specifying a height?

Here's another solution using display: flex instead of position: absolute or display: grid.

_x000D_
_x000D_
.container_row{_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.layer1 {_x000D_
  width: 100%;_x000D_
  background-color: rgba(255,0,0,0.5);  // red_x000D_
}_x000D_
_x000D_
.layer2{_x000D_
  width: 100%;_x000D_
  margin-left: -100%;_x000D_
  background-color: rgba(0,0,255,0.5);  // blue_x000D_
}
_x000D_
<div class="container_row">_x000D_
    <div class="layer1">_x000D_
        <span>Lorem ipsum...</span>_x000D_
    </div>_x000D_
    <div class="layer2">_x000D_
        More lorem ipsum..._x000D_
    </div>_x000D_
</div>_x000D_
<div class="container_row">_x000D_
    ...same HTML as above. This one should never overlap the .container_row above._x000D_
</div>
_x000D_
_x000D_
_x000D_

Where to find Application Loader app in Mac?

In more modern versions of Xcode, you'll find "Application Loader" under the "Xcode" menu (the first menu to the right of the Apple in the menu bar) and it'll be hiding in the "Open Developer Tools" submenu.

enter image description here

PHP - Insert date into mysql

Unless you want to insert different dates than "today", you can use CURDATE():

$sql = 'INSERT INTO data_tables (title, date_of_event) VALUES ("%s", CURDATE())';
$sql = sprintf ($sql, $_POST['post_title']);

PS! Please do not forget to sanitize your MySQL input, especially via mysql_real_escape_string ()

Pygame mouse clicking detection

I assume your game has a main loop, and all your sprites are in a list called sprites.

In your main loop, get all events, and check for the MOUSEBUTTONDOWN or MOUSEBUTTONUP event.

while ... # your main loop
  # get all events
  ev = pygame.event.get()

  # proceed events
  for event in ev:

    # handle MOUSEBUTTONUP
    if event.type == pygame.MOUSEBUTTONUP:
      pos = pygame.mouse.get_pos()

      # get a list of all sprites that are under the mouse cursor
      clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
      # do something with the clicked sprites...

So basically you have to check for a click on a sprite yourself every iteration of the mainloop. You'll want to use mouse.get_pos() and rect.collidepoint().

Pygame does not offer event driven programming, as e.g. cocos2d does.

Another way would be to check the position of the mouse cursor and the state of the pressed buttons, but this approach has some issues.

if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
  print ("You have opened a chest!")

You'll have to introduce some kind of flag if you handled this case, since otherwise this code will print "You have opened a chest!" every iteration of the main loop.

handled = False

while ... // your loop

  if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
    print ("You have opened a chest!")
    handled = pygame.mouse.get_pressed()[0]

Of course you can subclass Sprite and add a method called is_clicked like this:

class MySprite(Sprite):
  ...

  def is_clicked(self):
    return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())

So, it's better to use the first approach IMHO.

What is <scope> under <dependency> in pom.xml for?

.pom dependency scope can contain:

  • compile - available at Compile-time and Run-time
  • provided - available at Compile-time. (this dependency should be provided by outer container like OS...)
  • runtime - available at Run-time
  • test - test compilation and run time
  • system - is similar to provided but exposes <systemPath>path/some.jar</systemPath> to point on .jar
  • import - is available from Maven v2.0.9 for <type>pom</type> and it should be replaced by effective dependency from this file <dependencyManagement/>

Android: Cancel Async Task

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

Strip last two characters of a column in MySQL

Why not using LEFT(string, length) function instead of substring.

LEFT(col,char_length(col)-2) 

you can visit here https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_left to know more about Mysql String Functions.

How to shift a column in Pandas DataFrame

This is how I do it:

df_ext = pd.DataFrame(index=pd.date_range(df.index[-1], periods=8, closed='right'))
df2 = pd.concat([df, df_ext], axis=0, sort=True)
df2["forecast"] = df2["some column"].shift(7)

Basically I am generating an empty dataframe with the desired index and then just concatenate them together. But I would really like to see this as a standard feature in pandas so I have proposed an enhancement to pandas.

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.