Programs & Examples On #R5rs

The 5th Revised Report on the Algorithmic Language Scheme

Sequelize, convert entity to plain object

Here's what I'm using to get plain response object with non-stringified values and all nested associations from sequelize v4 query.

With plain JavaScript (ES2015+):

const toPlain = response => {
  const flattenDataValues = ({ dataValues }) => {
    const flattenedObject = {};

    Object.keys(dataValues).forEach(key => {
      const dataValue = dataValues[key];

      if (
        Array.isArray(dataValue) &&
        dataValue[0] &&
        dataValue[0].dataValues &&
        typeof dataValue[0].dataValues === 'object'
      ) {
        flattenedObject[key] = dataValues[key].map(flattenDataValues);
      } else if (dataValue && dataValue.dataValues && typeof dataValue.dataValues === 'object') {
        flattenedObject[key] = flattenDataValues(dataValues[key]);
      } else {
        flattenedObject[key] = dataValues[key];
      }
    });

    return flattenedObject;
  };

  return Array.isArray(response) ? response.map(flattenDataValues) : flattenDataValues(response);
};

With lodash (a bit more concise):

const toPlain = response => {
  const flattenDataValues = ({ dataValues }) =>
    _.mapValues(dataValues, value => (
      _.isArray(value) && _.isObject(value[0]) && _.isObject(value[0].dataValues)
        ? _.map(value, flattenDataValues)
        : _.isObject(value) && _.isObject(value.dataValues)
          ? flattenDataValues(value)
          : value
    ));

  return _.isArray(response) ? _.map(response, flattenDataValues) : flattenDataValues(response);
};

Usage:

const res = await User.findAll({
  include: [{
    model: Company,
    as: 'companies',
    include: [{
      model: Member,
      as: 'member',
    }],
  }],
});

const plain = toPlain(res);

// 'plain' now contains simple db object without any getters/setters with following structure:
// [{
//   id: 123,
//   name: 'John',
//   companies: [{
//     id: 234,
//     name: 'Google',
//     members: [{
//       id: 345,
//       name: 'Paul',
//     }]
//   }]
// }]

How do you remove duplicates from a list whilst preserving order?

sequence = ['1', '2', '3', '3', '6', '4', '5', '6']
unique = []
[unique.append(item) for item in sequence if item not in unique]

unique ? ['1', '2', '3', '6', '4', '5']

How do I increment a DOS variable in a FOR /F loop?

Or you can do this without using Delay.

set /a "counter=0"

-> your for loop here

do (
   statement1
   statement2
   call :increaseby1
 )

:increaseby1
set /a "counter+=1"

ASP.NET: Session.SessionID changes between requests

My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue

<sessionState cookieless="true"  />

Here's a REALLY old article about it: Cookieless ASP.NET

How to get first 5 characters from string

You can use the substr function like this:

echo substr($myStr, 0, 5);

The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How to assign a NULL value to a pointer in python?

Normally you can use None, but you can also use objc.NULL, e.g.

import objc
val = objc.NULL

Especially useful when working with C code in Python.

Also see: Python objc.NULL Examples

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

I want to convert std::string into a const wchar_t *

First convert it to std::wstring:

std::wstring widestr = std::wstring(str.begin(), str.end());

Then get the C string:

const wchar_t* widecstr = widestr.c_str();

This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

Callback after all asynchronous forEach callbacks are completed

var i=0;
const waitFor = (ms) => 
{ 
  new Promise((r) => 
  {
   setTimeout(function () {
   console.log('timeout completed: ',ms,' : ',i); 
     i++;
     if(i==data.length){
      console.log('Done')  
    }
  }, ms); 
 })
}
var data=[1000, 200, 500];
data.forEach((num) => {
  waitFor(num)
})

How can I obfuscate (protect) JavaScript?

You can't secure client side code: just press F12 on Google Chrome, pause javascript execution and you will get all strings, even those encrypted. Beautify it and rename variables and you will get almost the original code.

If you're writing server side javascript (i.e. NodeJS) is afraid of someone hacking into your server and want to make the hacker work more difficult, giving you more time to get your access back, then use javacript compilers:

You need to use Closure Compiler on Advanced Compilation, as it's the only tool that renames all your variables, even if those are used in multiple files/modules. But it just have a problem: it only work if you write in it's coding style.

Tooltip with HTML content without JavaScript

I have made a little example using css

_x000D_
_x000D_
.hover {_x000D_
  position: relative;_x000D_
  top: 50px;_x000D_
  left: 50px;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
  /* hide and position tooltip */_x000D_
  top: -10px;_x000D_
  background-color: black;_x000D_
  color: white;_x000D_
  border-radius: 5px;_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
  -webkit-transition: opacity 0.5s;_x000D_
  -moz-transition: opacity 0.5s;_x000D_
  -ms-transition: opacity 0.5s;_x000D_
  -o-transition: opacity 0.5s;_x000D_
  transition: opacity 0.5s;_x000D_
}_x000D_
_x000D_
.hover:hover .tooltip {_x000D_
  /* display tooltip on hover */_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div class="hover">hover_x000D_
  <div class="tooltip">asdadasd_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

FIDDLE

http://jsfiddle.net/8gC3D/471/

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

Run a PostgreSQL .sql file using command line arguments

2021 Solution

if your PostgreSQL database is on your system locally.

psql dbname < sqldump.sql username

If its hosted online

psql -h hostname dbname < sqldump.sql username

If you have any doubts or questions, please ask them in the comments.

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).

However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.

Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:

`-mcmodel=small'
     Generate code for the small code model: the program and its
     symbols must be linked in the lower 2 GB of the address space.
     Pointers are 64 bits.  Programs can be statically or dynamically
     linked.  This is the default code model.

`-mcmodel=kernel'
     Generate code for the kernel code model.  The kernel runs in the
     negative 2 GB of the address space.  This model has to be used for
     Linux kernel code.

`-mcmodel=medium'
     Generate code for the medium model: The program is linked in the
     lower 2 GB of the address space but symbols can be located
     anywhere in the address space.  Programs can be statically or
     dynamically linked, but building of shared libraries are not
     supported with the medium model.

`-mcmodel=large'
     Generate code for the large model: This model makes no assumptions
     about addresses and sizes of sections.

You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.

Formatting numbers (decimal places, thousands separators, etc) with CSS

You cannot use CSS for this purpose. I recommend using JavaScript if it's applicable. Take a look at this for more information: JavaScript equivalent to printf/string.format

Also As Petr mentioned you can handle it on server-side but it's totally depends on your scenario.

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

How to check what version of jQuery is loaded?

You can just check if the jQuery object exists:

if( typeof jQuery !== 'undefined' ) ... // jQuery loaded

jQuery().jquery has the version number.

As for the prefix, jQuery should always work. If you want to use $ you can wrap your code to a function and pass jQuery to it as the parameter:

(function( $ ) {
    $( '.class' ).doSomething();  // works always
})( jQuery )

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

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

For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column): Pandas has a built in replace method available on a dataframe object.

df.replace(',', '-', regex=True)

Source: Docs

How to get first object out from List<Object> using Linq

I would to it like this:

//Dictionary object with Key as string and Value as List of Component type object
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();

//from each element of the dictionary select first component if any
IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep"));

but only if it is sure that list contains only objects of Component class or children

How do I escape a single quote in SQL Server?

The following syntax will escape you ONLY ONE quotation mark:

SELECT ''''

The result will be a single quote. Might be very helpful for creating dynamic SQL :). enter image description here

What is the canonical way to check for errors using the CUDA runtime API?

The C++-canonical way: Don't check for errors...use the C++ bindings which throw exceptions.

I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.

So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd sample - with complete error checking of every runtime API call:

// (... prepare host-side buffers here ...)

auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);

cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);

// (... prepare a launch configuration here... )

cuda::launch(vectorAdd, launch_config,
    d_A.get(), d_B.get(), d_C.get(), numElements
);    
cuda::memory::copy(h_C.get(), d_C.get(), size);

// (... verify results here...)

Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none() command).

The code above uses my

Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)

Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.

A few links to how CUDA errors are automagically checked with these wrappers:

Check substring exists in a string in C

Using C - No built in functions

string_contains() does all the heavy lifting and returns 1 based index. Rest are driver and helper codes.

Assign a pointer to the main string and the substring, increment substring pointer when matching, stop looping when substring pointer is equal to substring length.

read_line() - A little bonus code for reading the user input without predefining the size of input user should provide.

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

int string_len(char * string){
  int len = 0;
  while(*string!='\0'){
    len++;
    string++;
  }
  return len;
}

int string_contains(char *string, char *substring){
  int start_index = 0;
  int string_index=0, substring_index=0;
  int substring_len =string_len(substring);
  int s_len = string_len(string);
  while(substring_index<substring_len && string_index<s_len){
    if(*(string+string_index)==*(substring+substring_index)){
      substring_index++;
    }
    string_index++;
    if(substring_index==substring_len){
      return string_index-substring_len+1;
    }
  }

  return 0;

}

#define INPUT_BUFFER 64
char *read_line(){
  int buffer_len = INPUT_BUFFER;
  char *input = malloc(buffer_len*sizeof(char));
  int c, count=0;

  while(1){
    c = getchar();

    if(c==EOF||c=='\n'){
      input[count]='\0';
      return input;
    }else{
      input[count]=c;
      count++;
    }

    if(count==buffer_len){
      buffer_len+=INPUT_BUFFER;
      input = realloc(input, buffer_len*sizeof(char));
    }

  }
}

int main(void) {
  while(1){
    printf("\nEnter the string: ");
    char *string = read_line();
    printf("Enter the sub-string: ");
    char *substring = read_line(); 
    int position = string_contains(string,substring);
    if(position){ 
      printf("Found at position: %d\n", position);
    }else{
      printf("Not Found\n");
    }
  }
  return 0;
}

How does ifstream's eof() work?

eof() checks the eofbit in the stream state.

On each read operation, if the position is at the end of stream and more data has to be read, eofbit is set to true. Therefore you're going to get an extra character before you get eofbit=1.

The correct way is to check whether the eof was reached (or, whether the read operation succeeded) after the reading operation. This is what your second version does - you do a read operation, and then use the resulting stream object reference (which >> returns) as a boolean value, which results in check for fail().

How to remove new line characters from a string?

If speed and low memory usage are important, do something like this:

var sb = new StringBuilder(s.Length);

foreach (char i in s)
    if (i != '\n' && i != '\r' && i != '\t')
        sb.Append(i);

s = sb.ToString();

Reading a JSP variable from JavaScript

alert("${variable}");

or

alert("<%=var%>");

or full example

<html> 
<head>
<script language="javascript"> 

function access(){ 
  <% String str="Hello World"; %>
   var s="<%=str%>"; 
   alert(s); 
} 

</script> 
</head> 

<body onload="access()"> 
</body> 

</html>

Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities

How to find current transaction level?

SELECT CASE  
          WHEN transaction_isolation_level = 1 
             THEN 'READ UNCOMMITTED' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 1 
             THEN 'READ COMMITTED SNAPSHOT' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 0 THEN 'READ COMMITTED' 
          WHEN transaction_isolation_level = 3 
             THEN 'REPEATABLE READ' 
          WHEN transaction_isolation_level = 4 
             THEN 'SERIALIZABLE' 
          WHEN transaction_isolation_level = 5 
             THEN 'SNAPSHOT' 
          ELSE NULL
       END AS TRANSACTION_ISOLATION_LEVEL 
FROM   sys.dm_exec_sessions AS s
       CROSS JOIN sys.databases AS d
WHERE  session_id = @@SPID
  AND  d.database_id = DB_ID();

Passing HTML input value as a JavaScript Function Parameter

   <form action="" onsubmit="additon()" name="form1" id="form1">
      a: <input type="number" name="a" id="a"><br>
      b: <input type="number" name="b" id="b"><br>
      <input type="submit" value="Submit" name="submit">
   </form>
  <script>
      function additon() 
      {
           var a = document.getElementById('a').value;
           var b = document.getElementById('b').value;
           var sum = parseInt(a) + parseInt(b);
           return sum;
      }
  </script>

SQL Server: Null VS Empty String

NULL values are stored separately in a special bitmap space for all the columns.

If you do not distinguish between NULL and '' in your application, then I would recommend you to store '' in your tables (unless the string column is a foreign key, in which case it would probably be better to prohibit the column from storing empty strings and allow the NULLs, if that is compatible with the logic of your application).

Node.js: How to read a stream into a buffer?

You can convert your readable stream to a buffer and integrate it in your code in an asynchronous way like this.

async streamToBuffer (stream) {
    return new Promise((resolve, reject) => {
      const data = [];

      stream.on('data', (chunk) => {
        data.push(chunk);
      });

      stream.on('end', () => {
        resolve(Buffer.concat(data))
      })

      stream.on('error', (err) => {
        reject(err)
      })
   
    })
  }

the usage would be as simple as:

 // usage
  const myStream // your stream
  const buffer = await streamToBuffer(myStream) // this is a buffer

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

This is the far best solution I can suggest to any one for debug-ing eloquent last query or final query although this has been discussed as well:

// query builder
$query = DB::table('table_name')->where('id', 1);

// binding replaced
$sql = str_replace_array('?', $query->getBindings(), $query->toSql());

// for laravel 5.8^
$sql = Str::replaceArray('?', $query->getBindings(), $query->toSql());

// print
dd($sql);

Why does this CSS margin-top style not work?

Not exactly sure why, but changing the inner CSS to

display: inline-block;

seems to work.

How to fix 'android.os.NetworkOnMainThreadException'?

NOTE : AsyncTask was deprecated in API level 30.
https://developer.android.com/reference/android/os/AsyncTask

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:

class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected RSSFeed doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader xmlreader = parser.getXMLReader();
            RssHandler theRSSHandler = new RssHandler();
            xmlreader.setContentHandler(theRSSHandler);
            InputSource is = new InputSource(url.openStream());
            xmlreader.parse(is);

            return theRSSHandler.getFeed();
        } catch (Exception e) {
            this.exception = e;

            return null;
        } finally {
            is.close();
        }
    }

    protected void onPostExecute(RSSFeed feed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

How to execute the task:

In MainActivity.java file you can add this line within your oncreate() method

new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

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

How to add RSA key to authorized_keys file?

There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.

ssh-copy-id -i /path/to/key/file [email protected]

If the key you are installing is ~/.ssh/id_rsa then you can even drop the -i flag completely.

Much better than manually doing it!

Find the version of an installed npm package

We can use npm view any-promise(your module name) -v

Network tools that simulate slow network connection

If you'd like a hardware solution, Netgear has a series of cheap ($50 or so) switches that do bandwidth limiting. Netgear Prosafe GS105E and similar switches are worth investigating.

Uninstall all installed gems, in OSX?

When trying to remove gems installed as root, xargs seems to halt when it encounters an error trying to uninstall a default gem:

sudo gem list | cut -d" " -f1 | xargs gem uninstall -aIx
# ERROR:  While executing gem ... (Gem::InstallError)
#    gem "test-unit" cannot be uninstalled because it is a default gem


This won't work for everyone, but here's what I used instead:

sudo for gem (`gem list | cut -d" " -f1`); do gem uninstall $gem -aIx; done

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

 $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

Get file content from URL?

1) local simplest methods

<?php
echo readfile("http://example.com/");   //needs "Allow_url_include" enabled
//OR
echo include("http://example.com/");    //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb"  //needs "Allow_url_fopen" enabled
?> 

2) Better Way is CURL:

echo get_remote_data('http://example.com'); // GET request 
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request

It automatically handles FOLLOWLOCATION problem + Remote urls:
src="./imageblabla.png" turned into:
src="http://example.com/path/imageblabla.png"

Code : https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php

How to set time zone in codeigniter?

you can try this:

date_default_timezone_set('Asia/Kolkata');

In application/config.php OR application/autoload.php

There is look like this:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

date_default_timezone_set('Asia/Kolkata');

It's working fine for me, i think this is the best way to define DEFAULT TIMEZONE in codeignitor.

replace anchor text with jquery

Try

$("#link1").text()

to access the text inside your element. The # indicates you're searching by id. You aren't looking for a child element, so you don't need children(). Instead you want to access the text inside the element your jQuery function returns.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Small correction, unescape and escape are deprecated, so:

function utf8_to_b64( str ) {
    return window.btoa(decodeURIComponent(encodeURIComponent(str)));
}

function b64_to_utf8( str ) {
     return decodeURIComponent(encodeURIComponent(window.atob(str)));
}


function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(encodeURIComponent(window.atob(str)));
}

How can I get the corresponding table header (th) from a table cell (td)?

You can do it by using the td's index:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');

How to get status code from webclient?

You should be able to use the "client.ResponseHeaders[..]" call, see this link for examples of getting stuff back from the response

Check for file exists or not in sql server?

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END

Format price in the current locale and currency

For formatting the price in another currency than the current one:

Mage::app()->getLocale()->currency('EUR')->toCurrency($price);

"Cannot GET /" with Connect on Node.js

You might be needed to restart the process if app.get not working. Press ctl+c and then restart node app.

How to execute command stored in a variable?

I think you should put

`

(backtick) symbols around your variable.

What is the equivalent to getch() & getche() in Linux?

#include <unistd.h>
#include <termios.h>

char getch(void)
{
    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if(tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if(tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if(read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    printf("%c\n", buf);
    return buf;
 }

Remove the last printf if you don't want the character to be displayed.

How to check if X server is running?

The bash script solution:

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

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

Javascript: Extend a Function

Use extendFunction.js

init = extendFunction(init, function(args) {
  doSomethingHereToo();
});

But in your specific case, it's easier to extend the global onload function:

extendFunction('onload', function(args) {
  doSomethingHereToo();
});

I actually really like your question, it's making me think about different use cases.

For javascript events, you really want to add and remove handlers - but for extendFunction, how could you later remove functionality? I could easily add a .revert method to extended functions, so init = init.revert() would return the original function. Obviously this could lead to some pretty bad code, but perhaps it lets you get something done without touching a foreign part of the codebase.

Returning multiple values from a C++ function

There are a bunch of ways to return multiple parameters. I'm going to be exhastive.

Use reference parameters:

void foo( int& result, int& other_result );

use pointer parameters:

void foo( int* result, int* other_result );

which has the advantage that you have to do a & at the call-site, possibly alerting people it is an out-parameter.

Write a template and use it:

template<class T>
struct out {
  std::function<void(T)> target;
  out(T* t):target([t](T&& in){ if (t) *t = std::move(in); }) {}
  out(std::optional<T>* t):target([t](T&& in){ if (t) t->emplace(std::move(in)); }) {}
  out(std::aligned_storage_t<sizeof(T), alignof(T)>* t):
    target([t](T&& in){ ::new( (void*)t ) T(std::move(in)); } ) {}
  template<class...Args> // TODO: SFINAE enable_if test
  void emplace(Args&&...args) {
    target( T(std::forward<Args>(args)...) );
  }
  template<class X> // TODO: SFINAE enable_if test
  void operator=(X&&x){ emplace(std::forward<X>(x)); }
  template<class...Args> // TODO: SFINAE enable_if test
  void operator()(Args...&&args){ emplace(std::forward<Args>(args)...); }
};

then we can do:

void foo( out<int> result, out<int> other_result )

and all is good. foo is no longer able to read any value passed in as a bonus.

Other ways of defining a spot you can put data can be used to construct out. A callback to emplace things somewhere, for example.

We can return a structure:

struct foo_r { int result; int other_result; };
foo_r foo();

whick works ok in every version of C++, and in this also permits:

auto&&[result, other_result]=foo();

at zero cost. Parameters can even not even be moved thanks to guaranteed elision.

We could return a std::tuple:

std::tuple<int, int> foo();

which has the downside that parameters are not named. This permits the :

auto&&[result, other_result]=foo();

as well. Prior to we can instead do:

int result, other_result;
std::tie(result, other_result) = foo();

which is just a bit more awkward. Guaranteed elision doesn't work here, however.

Going into stranger territory (and this is after out<>!), we can use continuation passing style:

void foo( std::function<void(int result, int other_result)> );

and now callers do:

foo( [&](int result, int other_result) {
  /* code */
} );

a benefit of this style is you can return an arbitrary number of values (with uniform type) without having to manage memory:

void get_all_values( std::function<void(int)> value )

the value callback could be called 500 times when you get_all_values( [&](int value){} ).

For pure insanity, you could even use a continuation on the continuation.

void foo( std::function<void(int, std::function<void(int)>)> result );

whose use looks like:

foo( [&](int result, auto&& other){ other([&](int other){
  /* code */
}) });

which would permit many-one relationships between result and other.

Again with uniforn values, we can do this:

void foo( std::function< void(span<int>) > results )

here, we call the callback with a span of results. We can even do this repeatedly.

Using this, you can have a function that efficiently passes megabytes of data without doing any allocation off the stack.

void foo( std::function< void(span<int>) > results ) {
  int local_buffer[1024];
  std::size_t used = 0;
  auto send_data=[&]{
    if (!used) return;
    results({ local_buffer, used });
    used = 0;
  };
  auto add_datum=[&](int x){
    local_buffer[used] = x;
    ++used;
    if (used == 1024) send_data();
  };
  auto add_data=[&](gsl::span<int const> xs) {
    for (auto x:xs) add_datum(x);
  };
  for (int i = 0; i < 7+(1<<20); ++i) {
    add_datum(i);
  }
  send_data(); // any leftover
}

Now, std::function is a bit heavy for this, as we would be doing this in zero-overhead no-allocation environments. So we'd want a function_view that never allocates.

Another solution is:

std::function<void(std::function<void(int result, int other_result)>)> foo(int input);

where instead of taking the callback and invoking it, foo instead returns a function which takes the callback.

foo(7)([&](int result, int other_result){ /* code */ });

this breaks the output parameters from the input parameters by having separate brackets.

With variant and coroutines, you could make foo a generator of a variant of the return types (or just the return type). The syntax is not yet fixed, so I won't give examples.

In the world of signals and slots, a function that exposes a set of signals:

template<class...Args>
struct broadcaster;

broadcaster<int, int> foo();

allows you to create a foo that does work async and broadcasts the result when it is finished.

Down this line we have a variety of pipeline techniques, where a function doesn't do something but rather arranges for data to be connected in some way, and the doing is relatively independant.

foo( int_source )( int_dest1, int_dest2 );

then this code doesn't do anything until int_source has integers to provide it. When it does, int_dest1 and int_dest2 start recieving the results.

How do I check if the Java JDK is installed on Mac?

Type in a terminal:

which javac

It should show you something like

/usr/bin/javac

Adding gif image in an ImageView in android

In your build.gradle(Module:app), add android-gif-drawable as a dependency by adding the following code:

allprojects {
    repositories {
       mavenCentral()
    }
}

dependencies {
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.+'
}


UPDATE: As of Android Gradle Plugin 3.0.0, the new command for compiling is implementation, so the above line might have to be changed to:

dependencies {
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.17'
}

Then sync your project. When synchronization ends, go to your layout file and add the following code:

<pl.droidsonroids.gif.GifImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/gif_file"
/>

And that's it, you can manage it with a simple ImageView.

When adding a Javascript library, Chrome complains about a missing source map, why?

When it s annoying with warnings like: DevTools failed to load SourceMap: Could not load content for http://********/bootstrap/4.5.0/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

Follow this path and remove that tricky /*# sourceMappingURL=bootstrap.min.css.map */ in bootstrap.min.css

Socket.IO - how do I get a list of connected sockets/clients?

I've gone through this pain today. Socket.io will be much better if they could make a proper documentation for their API.

Anyway, I tried to look into io.sockets and found a number of options we can use:

io.sockets.connected //Return {socket_1_id: {}, socket_2_id: {}} . This is the most convenient one, since you can just refer to io.sockets.connected[id] then do common things like emit()
io.sockets.sockets //Returns [{socket_1}, {socket_2}, ....]. Can refer to socket_i.id to distinguish
io.sockets.adapter.sids //Return {socket_1_id: {}, socket_2_id: {}} . Looks similar to the first one but the object is not actually the socket, just the information.

// Not directly helps but still relevant
io.sockets.adapter.rooms //Returns {room_1_id: {}, room_2_id: {}}
io.sockets.server.eio.clients //Return client sockets
io.sockets.server.eio.clientsCount //Return number of connected clients

Also, do note that when using socket.io with namespace, the above methods will break since io.sockets becomes an array instead of an object. To resolve, just replace io.sockets by io (i.e io.sockets.connected becomes io.connected, io.sockets.adapter.rooms becomes io.adapter.rooms ...)

Tested on socket.io 1.3.5

Spring data JPA query with parameter properties

This link will help you: Spring Data JPA M1 with SpEL expressions supported. The similar example would be:

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

Use jQuery to change an HTML tag?

I came up with an approach where you use a string representation of your jQuery object and replace the tag name using regular expressions and basic JavaScript. You will not loose any content and don't have to loop over each attribute/property.

/*
 * replaceTag
 * @return {$object} a new object with replaced opening and closing tag
 */
function replaceTag($element, newTagName) {

  // Identify opening and closing tag
  var oldTagName = $element[0].nodeName,
    elementString = $element[0].outerHTML,
    openingRegex = new RegExp("^(<" + oldTagName + " )", "i"),
    openingTag = elementString.match(openingRegex),
    closingRegex = new RegExp("(<\/" + oldTagName + ">)$", "i"),
    closingTag = elementString.match(closingRegex);

  if (openingTag && closingTag && newTagName) {
    // Remove opening tag
    elementString = elementString.slice(openingTag[0].length);
    // Remove closing tag
    elementString = elementString.slice(0, -(closingTag[0].length));
    // Add new tags
    elementString = "<" + newTagName + " " + elementString + "</" + newTagName + ">";
  }

  return $(elementString);
}

Finally, you can replace the existing object/node as follows:

var $newElement = replaceTag($rankingSubmit, 'a');
$('#not-an-a-element').replaceWith($newElement);

Is there a way to select sibling nodes?

var childNodeArray = document.getElementById('somethingOtherThanid').childNodes;

Error Importing SSL certificate : Not an X.509 Certificate

Many CAs will provide a cert in PKCS7 format.

According to Oracle documentation, the keytool commmand can handle PKCS#7 but sometimes it fails

The keytool command can import X.509 v1, v2, and v3 certificates, and PKCS#7 formatted certificate chains consisting of certificates of that type. The data to be imported must be provided either in binary encoding format or in printable encoding format (also known as Base64 encoding) as defined by the Internet RFC 1421 standard. In the latter case, the encoding must be bounded at the beginning by a string that starts with -----BEGIN, and bounded at the end by a string that starts with -----END.

If the PKCS7 file can't be imported try to transform it from PKCS7 to X.509:

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer

Remove padding or margins from Google Charts

I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.

For anyone interested, here is the actual solution:

... //rest of options
width: '100%',
height: '350',
chartArea:{
    left:5,
    top: 20,
    width: '100%',
    height: '350',
}
... //rest of options

The key here has nothing to do with the "left" or "top" values. But rather that the:

Dimensions of both the chart and chart-area are SET and set to the SAME VALUE

As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.

How to check if running as root in a bash script

if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi

or

if [[ `id -u` -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi

:)

How to refresh Android listview?

Call runnable whenever you want:

runOnUiThread(run);

OnCreate(), you set your runnable thread:

run = new Runnable() {
    public void run() {
        //reload content
        arraylist.clear();
        arraylist.addAll(db.readAll());
        adapter.notifyDataSetChanged();
        listview.invalidateViews();
        listview.refreshDrawableState();
    }
};

How can I expose more than 1 port with Docker?

Step1

In your Dockerfile, you can use the verb EXPOSE to expose multiple ports.
e.g.

EXPOSE 3000 80 443 22

Step2

You then would like to build an new image based on above Dockerfile.
e.g.

docker build -t foo:tag .

Step3

Then you can use the -p to map host port with the container port, as defined in above EXPOSE of Dockerfile.
e.g.

docker run -p 3001:3000 -p 23:22

In case you would like to expose a range of continuous ports, you can run docker like this:

docker run -it -p 7100-7120:7100-7120/tcp 

A potentially dangerous Request.Path value was detected from the client (*)

You should encode the route value and then (if required) decode the value before searching.

Redirect output of mongo query to a csv file

Have a look at this

for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.

Why should C++ programmers minimize use of 'new'?

  • C++ doesn't employ any memory manager by its own. Other languages like C#, Java has garbage collector to handle the memory
  • C++ implementations typically use operating system routines to allocate the memory and too much new/delete could fragment the available memory
  • With any application, if the memory is frequently being used it's advisable to pre-allocate it and release when not required.
  • Improper memory management could lead memory leaks and it's really hard to track. So using stack objects within the scope of function is a proven technique
  • The downside of using stack objects are, it creates multiple copies of objects on returning, passing to functions etc. However smart compilers are well aware of these situations and they've been optimized well for performance
  • It's really tedious in C++ if the memory being allocated and released in two different places. The responsibility for release is always a question and mostly we rely on some commonly accessible pointers, stack objects (maximum possible) and techniques like auto_ptr (RAII objects)
  • The best thing is that, you've control over the memory and the worst thing is that you will not have any control over the memory if we employ an improper memory management for the application. The crashes caused due to memory corruptions are the nastiest and hard to trace.

Javascript - Append HTML to container element without innerHTML

How to fish and while using strict code. There are two prerequisite functions needed at the bottom of this post.

xml_add('before', id_('element_after'), '<span xmlns="http://www.w3.org/1999/xhtml">Some text.</span>');

xml_add('after', id_('element_before'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

xml_add('inside', id_('element_parent'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

Add multiple elements (namespace only needs to be on the parent element):

xml_add('inside', id_('element_parent'), '<div xmlns="http://www.w3.org/1999/xhtml"><input type="text" /><input type="button" /></div>');

Dynamic reusable code:

function id_(id) {return (document.getElementById(id)) ? document.getElementById(id) : false;}

function xml_add(pos, e, xml)
{
 e = (typeof e == 'string' && id_(e)) ? id_(e) : e;

 if (e.nodeName)
 {
  if (pos=='after') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e.nextSibling);}
  else if (pos=='before') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  else if (pos=='inside') {e.appendChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true));}
  else if (pos=='replace') {e.parentNode.replaceChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  //Add fragment and have it returned.
 }
}

HTML img scaling

Adding max-width: 100%; to the img tag works for me.

T-SQL Format integer to 2-digit string

DECLARE @Number int = 1;
SELECT RIGHT('0'+ CONVERT(VARCHAR, @Number), 2)
--OR
SELECT RIGHT(CONVERT(VARCHAR, 100 + @Number), 2)
GO

How to use a variable inside a regular expression?

more example

I have configus.yml with flows files

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

in python code I use

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

You could try by these ways. 1st.

sudo chown -R mongod:mongod /data/db

but at some times,this is not useful. 2nd. if the above way is not useful,you can try to do this:

mkdir /data/db #as the database storage path

nohup mongod --dbpath /data/db &

or type:

mongod --dbpath /data/db

to get the output stream

How can I wait for set of asynchronous callback functions?

You can emulate it like this:

  countDownLatch = {
     count: 0,
     check: function() {
         this.count--;
         if (this.count == 0) this.calculate();
     },
     calculate: function() {...}
  };

then each async call does this:

countDownLatch.count++;

while in each asynch call back at the end of the method you add this line:

countDownLatch.check();

In other words, you emulate a count-down-latch functionality.

What is the difference between precision and scale?

Scale is the number of digit after the decimal point (or colon depending your locale)

Precision is the total number of significant digits

scale VS precision

Powershell script does not run via Scheduled Tasks

NOTE: Please ensure that you select Create a Basic task Action and NOT the Create Task Action.

I found the following solution:

1) Make powershell.exe run as administrator for this

  1. right-click on the powershell.exe icon
  2. click on properties under the shortcut key menu
  3. click on the advance button; check that "run as administrator" is checked.

2) in the task scheduler window under the action pane add the following script as a new command

%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Bypass -noexit -File "C:\ps1\BackUp.ps1"

enter image description here

What are my options for storing data when using React Native? (iOS and Android)

you can use sync storage that is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.

import SyncStorage from 'sync-storage';

SyncStorage.set('foo', 'bar');
const result = SyncStorage.get('foo');
console.log(result); // 'bar'

Cannot lower case button text in android studio

in XML Code
add this line android:textAllCaps="false" like bellow code

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_1_name"
        android:id="@+id/button2"
        android:layout_marginTop="140dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
       ** android:textAllCaps="false" ** />

or

in Java code (programmatically)
add this line to your button setAllCaps(false)

Button btn = (Button) findViewById(R.id.button2);
btn.setAllCaps(false);

comma separated string of selected values in mysql

Use group_concat() function of mysql.

SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;

It'll give you concatenated string like :

5,6,9,10,12,14,15,17,18,779 

Add ... if string is too long PHP

For some of you who uses Yii2 there is a method under the hood yii\helpers\StringHelper::truncate().

Example of usage:

$sting = "stringToTruncate";
$truncatedString = \yii\helpers\StringHelper::truncate($string, 6, '...');
echo $truncatedString; // result: "string..."

Here is the doc: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basestringhelper#truncate()-detail

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

How can I permanently enable line numbers in IntelliJ?

IntelliJ IDEA 15

5 approaches


Global change

  1. File > Settings... > Editor > General > Appearance > Show line numbers

    show line numbers

  2. Hit Shift twice > write "line numbers" > Show Line Numbers (that one that has the toggle) > change the toggle to ON

    shift shift


Change for the Active Editor

  1. Right click on the left side bar > Show Line Numbers

    right click

  2. Hit Shift twice > write "line" > Show Line Numbers (the line doesn't have the toggle)

    shift shift line

  3. Ctrl + Shift + A > write "Show line" > Active Editor: Show Line Numbers > change the toggle to ON

    Ctrl Shift A

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

'git' is not recognized as an internal or external command

Windows 7 32 - bit

I am using git for my Ruby on Rails application. First time so...

I created a .bat file for loading my RoR applications with the paths manually typed using this tutorial at "http://www.youtube.com/watch?v=-eFwV8lRu1w" If you are new to Ruby on Rails you might want to check it out as I followed all steps and it works flawlessly after a few trials and errors.

(The .bat file is editable using notepad++ hence no need for the long process whenever you need to edit a path, you can follow these simple process after creating a .bat file following the tutorials on the link above "file is called row.bat".)

  1. right click on the .bat file,
  2. edit with notepad++.
  3. find path.
  4. insert path below the last path you inputted.

    )
    During the tutorials I don't remember anything said in regards to using the git command so when starting a new project I had this same problem after installing git. The main issue I had was locating the folder with the bin/git.exe (git.exe did not show up in search using start menu's "search programs and files" ) NOTE I now understood that the location might vary drastically --- see below.

To locate the bin/git.exe i followed this steps

1 left click start menu and locate ->> all programs ->> GitHub inc. 2 right click git shell and select open file location 3 click through folders in the file location for the folder "bin"

(I had 4 folders named 1. IgnoreTemplates_fdbf2020839cde135ff9dbed7d503f8e03fa3ab4 2. lfs-x86_0.5.1 3. PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad ("bin/exe, found here <<-") 4. PoshGit_869d4c5159797755bc04749db47b166136e59132 )

Copy the full link by clicking on the explorers url (mine was "C:\Users\username\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin") open .bat file in notepad++ and paste using instructions on how to add a path to your .bat file from tutorials above. Problem solved!

Find the nth occurrence of substring in a string

Here is my solution for finding nth occurrance of b in string a:

from functools import reduce


def findNth(a, b, n):
    return reduce(lambda x, y: -1 if y > x + 1 else a.find(b, x + 1), range(n), -1)

It is pure Python and iterative. For 0 or n that is too large, it returns -1. It is one-liner and can be used directly. Here is an example:

>>> reduce(lambda x, y: -1 if y > x + 1 else 'bibarbobaobaotang'.find('b', x + 1), range(4), -1)
7

Javascript Append Child AFTER Element

This suffices :

 parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);

since if the refnode (second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore

Actually I doubt that the || null is required, try it and see.

sql set variable using COUNT

You can select directly into the variable rather than using set:

DECLARE @times int

SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

If you need to set multiple variables you can do it from the same select (example a bit contrived):

DECLARE @wins int, @losses int

SELECT @wins = SUM(DidWin), @losses = SUM(DidLose)
FROM thetable
WHERE Playername='Me'

If you are partial to using set, you can use parentheses:

DECLARE @wins int, @losses int

SET (@wins, @losses) = (SELECT SUM(DidWin), SUM(DidLose)
FROM thetable
WHERE Playername='Me');

How do I split a string on a delimiter in Bash?

How about this one liner, if you're not using arrays:

IFS=';' read ADDR1 ADDR2 <<<$IN

How to get distinct results in hibernate with joins and row-based limiting (paging)?

A slight improvement building on FishBoy's suggestion.

It is possible to do this kind of query in one hit, rather than in two separate stages. i.e. the single query below will page distinct results correctly, and also return entities instead of just IDs.

Simply use a DetachedCriteria with an id projection as a subquery, and then add paging values on the main Criteria object.

It will look something like this:

DetachedCriteria idsOnlyCriteria = DetachedCriteria.forClass(MyClass.class);
//add other joins and query params here
idsOnlyCriteria.setProjection(Projections.distinct(Projections.id()));

Criteria criteria = getSession().createCriteria(myClass);
criteria.add(Subqueries.propertyIn("id", idsOnlyCriteria));
criteria.setFirstResult(0).setMaxResults(50);
return criteria.list();

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

The X-Frame-Options header is a security feature enforced at the browser level.

If you have control over your user base (IT dept for corp app), you could try something like a greasemonkey script (if you can a) deploy greasemonkey across everyone and b) deploy your script in a shared way)...

Alternatively, you can proxy their result. Create an endpoint on your server, and have that endpoint open a connection to the target endpoint, and simply funnel traffic backwards.

How can I read numeric strings in Excel cells as string (not numbers)?

As long as the cell is in text format before the user types in the number, POI will allow you to obtain the value as a string. One key is that if there is a small green triangle in the upper left-hand corner of cell that is formatted as Text, you will be able to retrieve its value as a string (the green triangle appears whenever something that appears to be a number is coerced into a text format). If you have Text formatted cells that contain numbers, but POI will not let you fetch those values as strings, there are a few things you can do to the Spreadsheet data to allow that:

  • Double click on the cell so that the editing cursor is present inside the cell, then click on Enter (which can be done only one cell at a time).
  • Use the Excel 2007 text conversion function (which can be done on multiple cells at once).
  • Cut out the offending values to another location, reformat the spreadsheet cells as text, then repaste the previously cut out values as Unformatted Values back into the proper area.

One final thing that you can do is that if you are using POI to obtain data from an Excel 2007 spreadsheet, you can the Cell class 'getRawValue()' method. This does not care what the format is. It will simply return a string with the raw data.

Combine two tables that have no common fields

select 
    status_id, 
    status, 
    null as path, 
    null as Description 
from 
    zmw_t_status

union
select 
    null, 
    null, 
    path as cid, 
    Description from zmw_t_path;

How to convert a String to a Date using SimpleDateFormat?

Use the below function

/**
     * Format a time from a given format to given target format
     * 
     * @param inputFormat
     * @param inputTimeStamp
     * @param outputFormat
     * @return
     * @throws ParseException
     */
    private static String TimeStampConverter(final String inputFormat,
            String inputTimeStamp, final String outputFormat)
            throws ParseException {
        return new SimpleDateFormat(outputFormat).format(new SimpleDateFormat(
                inputFormat).parse(inputTimeStamp));
    }

Sample Usage is as Following:

    try {
        String inputTimeStamp = "08/16/2011";

        final String inputFormat = "MM/dd/yyyy";
        final String outputFormat = "EEE MMM dd HH:mm:ss z yyyy";

        System.out.println(TimeStampConverter(inputFormat, inputTimeStamp,
                outputFormat));

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Select SQL results grouped by weeks

Base on @increddibelly answer, I applied to my query as below.

I share for whom concerned.

My table structure FamilyData(Id, nodeTime, totalEnergy)

select
   sum(totalEnergy) as TotalEnergy,
   DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)

What is a "cache-friendly" code?

Processors today work with many levels of cascading memory areas. So the CPU will have a bunch of memory that is on the CPU chip itself. It has very fast access to this memory. There are different levels of cache each one slower access ( and larger ) than the next, until you get to system memory which is not on the CPU and is relatively much slower to access.

Logically, to the CPU's instruction set you just refer to memory addresses in a giant virtual address space. When you access a single memory address the CPU will go fetch it. in the old days it would fetch just that single address. But today the CPU will fetch a bunch of memory around the bit you asked for, and copy it into the cache. It assumes that if you asked for a particular address that is is highly likely that you are going to ask for an address nearby very soon. For example if you were copying a buffer you would read and write from consecutive addresses - one right after the other.

So today when you fetch an address it checks the first level of cache to see if it already read that address into cache, if it doesn't find it, then this is a cache miss and it has to go out to the next level of cache to find it, until it eventually has to go out into main memory.

Cache friendly code tries to keep accesses close together in memory so that you minimize cache misses.

So an example would be imagine you wanted to copy a giant 2 dimensional table. It is organized with reach row in consecutive in memory, and one row follow the next right after.

If you copied the elements one row at a time from left to right - that would be cache friendly. If you decided to copy the table one column at a time, you would copy the exact same amount of memory - but it would be cache unfriendly.

Opposite of %in%: exclude rows with values specified in a vector

library(roperators)

1 %ni% 2:10

If you frequently need to use custom infix operators, it is easier to just have them in a package rather than declaring the same exact functions over and over in each script or project.

How to lock orientation of one view controller to portrait mode only in Swift

Here is a simple way that works for me with Swift 4.2 (iOS 12.2), put this in a UIViewController for which you want to disable shouldAutorotate:

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

The .portrait part tells it in which orientation(s) to remain, you can change this as you like. Choices are: .portrait, .all, .allButUpsideDown, .landscape, .landscapeLeft, .landscapeRight, .portraitUpsideDown.

Error message "Strict standards: Only variables should be passed by reference"

Consider the following code:

error_reporting(E_STRICT);
class test {
    function test_arr(&$a) {
        var_dump($a);
    }
    function get_arr() {
        return array(1, 2);
    }
}

$t = new test;
$t->test_arr($t->get_arr());

This will generate the following output:

Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

The reason? The test::get_arr() method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr() method returns an array value.

To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:

function test_arr($a) {
    var_dump($a);
}

Since you can't change the signature of array_shift you can also use an intermediate variable:

$inter = get_arr();
$el = array_shift($inter);

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Sometimes this issue comes because the java.version which you have mentioned in POM.xml is not the one installed in your machine.

<properties>
    <java.version>1.7</java.version>
</properties>

Ensure you exactly mention the same version in your pom.xml as the jdk and jre version present in your machine.

How to use sed to remove all double quotes within a file

Additional comment. Yes this works:

    sed 's/\"//g' infile.txt  > outfile.txt

(however with batch gnu sed, will just print to screen)

In batch scripting (GNU SED), this was needed:

    sed 's/\x22//g' infile.txt  > outfile.txt

iOS change navigation bar title font and color

Anyone needs a Swift 3 version. redColor() has changed to just red.

self.navigationController?.navigationBar.titleTextAttributes =
        [NSForegroundColorAttributeName: UIColor.red,
         NSFontAttributeName: UIFont(name: "{your-font-name}", size: 21)!]

Obtain smallest value from array in Javascript?

Possibly an easier way?

Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.

justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5

Use sort.

justPrices.sort();

It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.

justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9

You can then easily grab by the first index.

justPrices[0]

I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

There are several other posts about this now and they all point to enabling TLS 1.2. Anything less is unsafe.

You can do this in .NET 3.5 with a patch.
You can do this in .NET 4.0 and 4.5 with a single line of code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0

In .NET 4.6, it automatically uses TLS 1.2.

See here for more details: .NET support for TLS

HTML5 image icon to input placeholder

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

input#search {
    background-image: url(bg.jpg);
    background-repeat: no-repeat;
    text-indent: 20px;
}

HTML:

<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />

Javascript:

function hideIcon(self) {
    self.style.backgroundImage = 'none';
}

September 25h, 2013

I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active pseudo-class.

#search:active { background-image: none; }

Heck, using CSS3 you can make it fade away!

http://jsfiddle.net/2tTxE/


November 5th, 2013

Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!

            Chrome  Firefox     IE      Opera   Safari
:before     (yes)   1.0         8.0     4       4.0
::before    (yes)   1.5         9.0     7       4.0

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

How to force IE10 to render page in IE9 document mode

I haven't seen this done before, but this is how it was done for emulating IE 8/7 when using IE 9:

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

If not, then try this one:

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

Add those to your header with the other meta tags. This should force IE10 to render as IE9.

Another option you could do (assuming you are using PHP) is add this to your .htaccess file:

Header set X-UA-Compatible "IE=9"

This will perform the action universally, rather than having to worry about adding the meta tag to all of your headers.

HTML 5 input type="number" element for floating point numbers on Chrome

Try this

_x000D_
_x000D_
<input onkeypress='return event.charCode >= 48 && _x000D_
                          event.charCode <= 57 || _x000D_
                          event.charCode == 46'>
_x000D_
_x000D_
_x000D_

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

Hide vertical scrollbar in <select> element

I know this thread is somewhat old, but there are a lot of really hacky answers on here, so I'd like to provide something that is a lot simpler and a lot cleaner:

select {
    overflow-y: auto;
}

As you can see in this fiddle, this solution provides you with flexibility if you don't know the exact number of select options you are going to have. It hides the scrollbar in the case that you don't need it without hiding possible extra option elements in the other case. Don't do all this hacky overlapping div stuff. It just makes for unreadable markup.

Array.sort() doesn't sort numbers correctly

The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:

var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });

C# catch a stack overflow exception

It's impossible, and for a good reason (for one, think about all those catch(Exception){} around).

If you want to continue execution after stack overflow, run dangerous code in a different AppDomain. CLR policies can be set to terminate current AppDomain on overflow without affecting original domain.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Because
$.ajax({type: "POST" - calls OPTIONS
$.post( - Calls POST

Both are different. Postman calls "POST" properly, but when we call it, it will be "OPTIONS".

For C# web services - Web API

Please add the following code in your web.config file under <system.webServer> tag. This will work:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

Please make sure you are not doing any mistake in the Ajax call

jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);
    },
    error: function () {
        console.log("error");
    }
});

Note: If you are looking for downloading content from a third-party website then this will not help you. You can try the following code, but not JavaScript.

System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");

How to read from a file or STDIN in Bash?

Code ${1:-/dev/stdin} will just understand first argument, so, how about this.

ARGS='$*'
if [ -z "$*" ]; then
  ARGS='-'
fi
eval "cat -- $ARGS" | while read line
do
   echo "$line"
done

Python 3.1.1 string to hex

You've already got some good answers, but I thought you might be interested in a bit of the background too.

Firstly you're missing the quotes. It should be:

"hello".encode("hex")

Secondly this codec hasn't been ported to Python 3.1. See here. It seems that they haven't yet decided whether or not these codecs should be included in Python 3 or implemented in a different way.

If you look at the diff file attached to that bug you can see the proposed method of implementing it:

import binascii
output = binascii.b2a_hex(input)

Moment js date time comparison

It is important that your datetime is in the correct ISO format when using any of the momentjs queries: isBefore, isAfter, isSameOrBefore, isSameOrAfter, isBetween

So instead of 2014-03-24T01:14:000, your datetime should be either:

2014-03-24T01:14:00 or 2014-03-24T01:14:00.000Z

otherwise you may receive the following deprecation warning and the condition will evaluate to false:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

_x000D_
_x000D_
// https://momentjs.com/docs/#/query/_x000D_
_x000D_
const dateIsAfter = moment('2014-03-24T01:15:00.000Z').isAfter(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsSame = moment('2014-03-24T01:15:00.000Z').isSame(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsBefore = moment('2014-03-24T01:15:00.000Z').isBefore(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
console.log(`Date is After: ${dateIsAfter}`);_x000D_
console.log(`Date is Same: ${dateIsSame}`);_x000D_
console.log(`Date is Before: ${dateIsBefore}`);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"_x000D_
></script>
_x000D_
_x000D_
_x000D_

Python append() vs. + operator on lists, why do these give different results?

Python lists are heterogeneous that is the elements in the same list can be any type of object. The expression: c.append(c) appends the object c what ever it may be to the list. In the case it makes the list itself a member of the list.

The expression c += c adds two lists together and assigns the result to the variable c. The overloaded + operator is defined on lists to create a new list whose contents are the elements in the first list and the elements in the second list.

So these are really just different expressions used to do different things by design.

Fatal error: unexpectedly found nil while unwrapping an Optional values

fatal error: unexpectedly found nil while unwrapping an Optional value

  1. Check the IBOutlet collection , because this error will have chance to unconnected uielement object usage.

:) hopes it will help for some struggled people .

What does the "no version information available" error from linux dynamic linker mean?

How are you compiling your app? What compiler flags?

In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.

How do I view events fired on an element in Chrome DevTools?

Visual Event is a nice little bookmarklet that you can use to view an element's event handlers. On online demo can be viewed here.

What is the point of WORKDIR on Dockerfile?

Be careful where you set WORKDIR because it can affect the continuous integration flow. For example, setting it to /home/circleci/project will cause error something like .ssh or whatever is the remote circleci is doing at setup time.

HTML select form with option to enter custom value

Using one of the above solutions ( @mickmackusa ), I made a working prototype in React 16.8+ using Hooks.

https://codesandbox.io/s/heuristic-dewdney-0h2y2

I hope it helps someone.

Converting a String to DateTime

Do you want it fast?

Let's say you have a date with format yyMMdd.

The fastest way to convert it that I found is:

var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000, 
(s[2] - '0') * 10 + s[3] - '0', 
(s[4] - '0') * 10 + s[5] - '0')

Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.

This method takes about 10% of the time required by:

var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);

how to show only even or odd rows in sql server 2008?

for SQL > odd:

select * from id in(select id from employee where id%2=1)

for SQL > Even:

select * from id in(select id from employee where id%2=0).....f5

How do I set proxy for chrome in python webdriver?

from selenium import webdriver

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)

chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")

comparing 2 strings alphabetically for sorting purposes

Just remember that string comparison like "x" > "X" is case-sensitive

"aa" < "ab" //true
"aa" < "Ab" //false

You can use .toLowerCase() to compare without case sensitivity.

How to get featured image of a product in woocommerce

This should do the trick:

<?php
    $product_meta = get_post_meta($post_id);
    echo wp_get_attachment_image( $product_meta['_thumbnail_id'][0], 'full' );
?>

You can change the parameters according to your needs.

Posting array from form

When you post that data, it is stored as an array in $_POST.

You could optionally do something like:

<input name="arrayname[item1]">
<input name="arrayname[item2]">
<input name="arrayname[item3]">

Then:

$item1 = $_POST['arrayname']['item1'];
$item2 = $_POST['arrayname']['item2'];
$item3 = $_POST['arrayname']['item3'];

But I fail to see the point.

How to remove all the punctuation in a string? (Python)

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

How to print without newline or space?

Note: The title of this question used to be something like "How to printf in python?"

Since people may come here looking for it based on the title, Python also supports printf-style substitution:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

And, you can handily multiply string values:

>>> print "." * 10
..........

Operator overloading in Java

Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.

We can take +(plus) for example:

int a = 2 + 4;
string = "hello" + "world";

Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.

Excel VBA to Export Selected Sheets to PDF

this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)

' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir

Sub luxation2()
    Dim Filename As String
    Filename = "temp201"



Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"


    ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False

End Sub

IndentationError: unexpected unindent WHY?

This error could actually be in the code preceding where the error is reported. See the For example, if you have a syntax error as below, you'll get the indentation error. The syntax error is actually next to the "except" because it should contain a ":" right after it.

try:
    #do something
except
    print 'error/exception'


def printError(e):
    print e

If you change "except" above to "except:", the error will go away.

Good luck.

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

UIView bottom border?

Swift 4

If you need a really adaptive solution (for all screen sizes), then this is it:

/**
* Extends UIView with shortcut methods
*
* @author Alexander Volkov
* @version 1.0
*/
extension UIView {

    /// Adds bottom border to the view with given side margins
    ///
    /// - Parameters:
    ///   - color: the border color
    ///   - margins: the left and right margin
    ///   - borderLineSize: the size of the border
    func addBottomBorder(color: UIColor = UIColor.red, margins: CGFloat = 0, borderLineSize: CGFloat = 1) {
        let border = UIView()
        border.backgroundColor = color
        border.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(border)
        border.addConstraint(NSLayoutConstraint(item: border,
                                                attribute: .height,
                                                relatedBy: .equal,
                                                toItem: nil,
                                                attribute: .height,
                                                multiplier: 1, constant: borderLineSize))
        self.addConstraint(NSLayoutConstraint(item: border,
                                              attribute: .bottom,
                                              relatedBy: .equal,
                                              toItem: self,
                                              attribute: .bottom,
                                              multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: border,
                                              attribute: .leading,
                                              relatedBy: .equal,
                                              toItem: self,
                                              attribute: .leading,
                                              multiplier: 1, constant: margins))
        self.addConstraint(NSLayoutConstraint(item: border,
                                              attribute: .trailing,
                                              relatedBy: .equal,
                                              toItem: self,
                                              attribute: .trailing,
                                              multiplier: 1, constant: margins))
    }
}

What is JSONP, and why was it created?

TL;DR

JSONP is an old trick invented to bypass the security restriction that forbids us to get JSON data that is in a different website (a different origin1) than the one we are navigating in.

The trick works by using a <script> tag that asks for the JSON from that place, e.g.: { "user":"Smith" }, but wrapped in a function, the actual JSONP ("JSON with Padding"):

peopleDataJSONP({"user":"Smith"})

Receiving it in this form enables us to use the data within our peopleDataJSONP function. JSONP is a bad practice and not needed anymore, don't use it (read below).


The problem

Say we want to use on ourweb.com some JSON data (or any raw data really) hosted at anotherweb.com. If we were to use GET request (think XMLHttpRequest, or fetch call, $.ajax, etc.), our browser would tell us it's not allowed with this ugly error:

Chrome CORS console error

How to get the data we want? Well, <script> tags are not subjected to this whole server (origin1) restriction! That's why we can load a library like jQuery or Google Maps from any server, such as a CDN, without any errors.

Here's the important point: if you think about it, those libraries are actual, runnable JS code (usually a massive function with all the logic inside). But raw data? JSON data is not code. There's nothing to run; it's just plain text.

Therefore, there's no way to handle or manipulate our precious data. The browser will download the data pointed at by our <script> tag and when processing it'll rightfully complain:

wtf is this {"user":"Smith"} crap we loaded? It's not code. I can't compute, syntax error!


The JSONP hack

The old/hacky way to utilize that data? If we could make plain text somehow runnable, we could grab it on runtime. So we need anotherweb.com to send it with some logic, so when it's loaded, your code in the browser will be able to use said data. We need two things: 1) to get the data in a way that it can be run, and 2) write some code in the client so that when the data runs, this code is called and we get to use the data.

For 1) we ask the foreign server to send us the JSON data inside a JS function. The data itself is set up as that function's input. It looks like this:

peopleDataJSONP({"user":"Smith"})

which makes it JS code our browser will parse and run without complaining! Exactly like it does with the jQuery library. To receive the data like that, the client "asks" the JSONP-friendly server for it, usually done like this:

<script src="https://anotherweb.com/api/data-from-people.json?myCallback=peopleDataJSONP"></script>

As per 2), since our browser will receive the JSONP with that function name, we need a function with the same name in our code, like this:

function peopleDataJSONP(data){
  alert(data.user); // "Smith"
}

The browser will download the JSONP and run it, which calls our function, where the argument data will be the JSON data from anotherweb.com. We can now do with our data whatever we want to.


Don't use JSONP, use CORS

JSONP is a cross-site hack with a few downsides:

  • We can only perform GET requests
  • Since it's a GET request triggered by a simple script tag, we don't get helpful errors or progress info
  • There are also some security concerns, like running in your client JS code that could be changed to a malicious payload
  • It only solves the problem with JSON data, but Same-Origin security policy applies to other data (WebFonts, images/video drawn with drawImage()...)
  • It's not very elegant nor readable.

The takeaway is that there's no need to use it nowadays.

You should read about CORS here, but the gist of it is:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.



  1. origin is defined by 3 things: protocol, port, and host. So, for example, https://web.com is a different origin than http://web.com (different protocol) and https://web.com:8081 (different port) and obviously https://thatotherweb.net (different host)

Get TimeZone offset value from TimeZone without TimeZone name

With Java 8, you can achieve this by following code.

    TimeZone tz = TimeZone.getDefault();
    String offsetId = tz.toZoneId().getRules().getStandardOffset(Instant.now()).getId();

and the offsetId will be something like +01:00

Please notice the function getStandardOffset need a Instant as parameter. It is the specific time point, at which you want to check the offset of given timezone, as timezone's offset may varies during time. For the reason of some areas have Daylight Saving Time.

I think it is the reason why @Tomasz Nurkiewicz recommand not to store offset in signed hour format directly, but to check the offset each time you need it.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

Got this from a network filter (LuLu on macOS) blocking traffic to/from Docker-related processes.

Regular expression search replace in Sublime Text 2

Here is a visual presentation of the approved answer.

enter image description here

Looping Over Result Sets in MySQL

Something like this should do the trick (However, read after the snippet for more info)

CREATE PROCEDURE GetFilteredData()
BEGIN
  DECLARE bDone INT;

  DECLARE var1 CHAR(16);    -- or approriate type
  DECLARE Var2 INT;
  DECLARE Var3 VARCHAR(50);

  DECLARE curs CURSOR FOR  SELECT something FROM somewhere WHERE some stuff;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;

  DROP TEMPORARY TABLE IF EXISTS tblResults;
  CREATE TEMPORARY TABLE IF NOT EXISTS tblResults  (
    --Fld1 type,
    --Fld2 type,
    --...
  );

  OPEN curs;

  SET bDone = 0;
  REPEAT
    FETCH curs INTO var1,, b;

    IF whatever_filtering_desired
       -- here for whatever_transformation_may_be_desired
       INSERT INTO tblResults VALUES (var1, var2, var3 ...);
    END IF;
  UNTIL bDone END REPEAT;

  CLOSE curs;
  SELECT * FROM tblResults;
END

A few things to consider...

Concerning the snippet above:

  • may want to pass part of the query to the Stored Procedure, maybe particularly the search criteria, to make it more generic.
  • If this method is to be called by multiple sessions etc. may want to pass a Session ID of sort to create a unique temporary table name (actually unnecessary concern since different sessions do not share the same temporary file namespace; see comment by Gruber, below)
  • A few parts such as the variable declarations, the SELECT query etc. need to be properly specified

More generally: trying to avoid needing a cursor.

I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.

Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.

Switch on Enum in Java

Article on Programming.Guide: Switch on enum


enum MyEnum { CONST_ONE, CONST_TWO }

class Test {
        public static void main(String[] args) {
            MyEnum e = MyEnum.CONST_ONE;

            switch (e) {
                case CONST_ONE: System.out.println(1); break;
                case CONST_TWO: System.out.println(2); break;
            }
        }
    }

Switches for strings are implemented in Java 7.

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

ADD and COPY both have same functionality of copying files and directories from source to destination but ADD has extra of file extraction and URL file extraction functionality. The best practice is to use COPY in only copy operation only avoid ADD is many areas. The link will explain it with some simple examples difference between COPY and ADD in dockerfile

Pandas: Looking up the list of sheets in an excel file

This is the fastest way I have found, inspired by @divingTobi's answer. All The answers based on xlrd, openpyxl or pandas are slow for me, as they all load the whole file first.

from zipfile import ZipFile
from bs4 import BeautifulSoup  # you also need to install "lxml" for the XML parser

with ZipFile(file) as zipped_file:
    summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]

How to sparsely checkout only one single file from a git repository?

Now we can! As this is the first result on google, I thought I'd update this to the latest standing. With the advent of git 1.7.9.5, we have the git archive command which will allow you to retrieve a single file from a remote host.

git archive --remote=git://git.foo.com/project.git HEAD:path/in/repo filename | tar -x

See answer in full here https://stackoverflow.com/a/5324532/290784

ORA-01843 not a valid month- Comparing Dates

In a comment to one of the answers you mention that to_date with a format doesn't help. In another comment you explain that the table is accessed via DBLINK.

So obviously the other system contains an invalid date that Oracle cannot accept. Fix this in the other dbms (or whatever you dblink to) and your query will work.

Having said this, I agree with the others: always use to_date with a format to convert a string literal to a date. Also never use only two digits for a year. For example '23/04/49' means 2049 in your system (format RR), but it confuses the reader (as you see from the answers suggesting a format with YY).

Run a php app using tomcat?

  1. Make sure you have php installed on your server
  2. Find the latest release of php-java-bridge off of sourceforge
  3. From the exploded directory on Sourceforge, download php-servlet.jar and JavaBridge.jar
  4. Place those jar files into webapp/WEB-INF/lib folder of your project
  5. Edit webapp/WEB-INF/web.xml to look like:

ok

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
   <filter>
      <filter-name>PhpCGIFilter</filter-name>
      <filter-class>php.java.servlet.PhpCGIFilter</filter-class>
   </filter>
   <filter-mapping>
      <filter-name>PhpCGIFilter</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
   <!-- the following adds the JSR223 listener. Remove it if you don't want to use the JSR223 API -->
   <listener>
      <listener-class>php.java.servlet.ContextLoaderListener</listener-class>
   </listener>
   <!-- the back end for external (console, Apache/IIS-) PHP scripts; remove it if you don't need this -->
   <servlet>
      <servlet-name>PhpJavaServlet</servlet-name>
      <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
   </servlet>
   <!-- runs PHP scripts in this web app; remove it if you don't need this -->
   <servlet>
      <servlet-name>PhpCGIServlet</servlet-name>
      <servlet-class>php.java.servlet.fastcgi.FastCGIServlet</servlet-class>
      <load-on-startup>0</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>PhpJavaServlet</servlet-name>
      <url-pattern>*.phpjavabridge</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
      <servlet-name>PhpCGIServlet</servlet-name>
      <url-pattern>*.php</url-pattern>
   </servlet-mapping>
</web-app>

You may have other content inside this file, just make sure you have added everything between the web-app tag.

  1. Add your php files to the webapp directory

You can do other special things with this as well. You cal learn more about it here: http://php-java-bridge.sourceforge.net/pjb/how_it_works.php

JAVA_HOME directory in Linux

Did you set your JAVA_HOME

  • Korn and bash shells:export JAVA_HOME=jdk-install-dir
  • Bourne shell:JAVA_HOME=jdk-install-dir;export JAVA_HOME
  • C shell:setenv JAVA_HOME jdk-install-dir

MySQL how to join tables on two fields

SELECT * 
FROM t1
JOIN t2 USING (id, date)

perhaps you'll need to use INNEER JOIN or where t2.id is not null if you want results only matching both conditions

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the formatter specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s).

Angular: Cannot Get /

I had the same error caused by build errors. I ran ng build in the directory of my application which helped me correct my errors

Changing width property of a :before css selector using JQuery

As Boltclock states in his answer to Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, and thus you can't select and manipulate them with jQuery.

Might just be best to set the style with jQuery instead of using the pseudo CSS selector.

How to convert signed to unsigned integer in python

Since version 3.2 :

def toSigned(n, byte_count): 
  return int.from_bytes(n.to_bytes(byte_count, 'little'), 'little', signed=True)

output :

In [8]: toSigned(5, 1)                                                                                                                                                                                                                                                                                                     
Out[8]: 5

In [9]: toSigned(0xff, 1)                                                                                                                                                                                                                                                                                                  
Out[9]: -1

Check if a variable exists in a list in Bash

An alternative solution inspired by the accepted response, but that uses an inverted logic:

MODE="${1}"

echo "<${MODE}>"
[[ "${MODE}" =~ ^(preview|live|both)$ ]] && echo "OK" || echo "Uh?"

Here, the input ($MODE) must be one of the options in the regular expression ('preview', 'live', or 'both'), contrary to matching the whole options list to the user input. Of course, you do not expect the regular expression to change.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

One line if-condition-assignment

In one line:

if someBoolValue: num1 = 20

But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.

if someBoolValue:
    num1 = 20

(Equally, camel caps should be avoided. So rather use some_bool_value.)

Note that an in-line expression some_value if predicate without an else part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.

How can I set the 'backend' in matplotlib in Python?

The errors you posted are unrelated. The first one is due to you selecting a backend that is not meant for interactive use, i.e. agg. You can still use (and should use) those for the generation of plots in scripts that don't require user interaction.

If you want an interactive lab-environment, as in Matlab/Pylab, you'd obviously import a backend supporting gui usage, such as Qt4Agg (needs Qt and AGG), GTKAgg (GTK an AGG) or WXAgg (wxWidgets and Agg).

I'd start by trying to use WXAgg, apart from that it really depends on how you installed Python and matplotlib (source, package etc.)

How do I get the difference between two Dates in JavaScript?

Below code will return the days left from today to futures date.

Dependencies: jQuery and MomentJs.

var getDaysLeft = function (date) {
  var today = new Date();
  var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));
  var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24);   
  return daysLeft;
};

getDaysLeft('YYYY-MM-DD');

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

Invert "if" statement to reduce nesting

As others have mentioned, there shouldn't be a performance hit, but there are other considerations. Aside from those valid concerns, this also can open you up to gotchas in some circumstances. Suppose you were dealing with a double instead:

public void myfunction(double exampleParam){
    if(exampleParam > 0){
        //Body will *not* be executed if Double.IsNan(exampleParam)
    }
}

Contrast that with the seemingly equivalent inversion:

public void myfunction(double exampleParam){
    if(exampleParam <= 0)
        return;
    //Body *will* be executed if Double.IsNan(exampleParam)
}

So in certain circumstances what appears to be a a correctly inverted if might not be.

GridLayout (not GridView) how to stretch all children evenly

UPDATE: Weights are supported as of API 21. See PaulT's answer for more details. END UPDATE There are limitations when using the GridLayout, the following quote is taken from the documentation.

"GridLayout does not provide support for the principle of weight, as defined in weight. In general, it is not therefore possible to configure a GridLayout to distribute excess space in non-trivial proportions between multiple rows or columns ... For complete control over excess space distribution in a row or column; use a LinearLayout subview to hold the components in the associated cell group."

Here is a small example that uses LinearLayout subviews. (I used Space Views that takes up unused area and pushes the buttons into desired position.)

<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="1"
>
    <TextView
        android:text="2x2 button grid"
        android:textSize="32dip"
        android:layout_gravity="center_horizontal" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="Button 2" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
    >
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 3" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="Button 4" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>
</GridLayout>

How to fix a Div to top of page with CSS only

You can also use flexbox, but you'd have to add a parent div that covers div#top and div#term-defs. So the HTML looks like this:

_x000D_
_x000D_
    #content {_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
        display: flex;_x000D_
        flex-direction: column;_x000D_
    }_x000D_
_x000D_
    #term-defs {_x000D_
        flex-grow: 1;_x000D_
        overflow: auto;_x000D_
    } 
_x000D_
    <body>_x000D_
        <div id="content">_x000D_
            <div id="top">_x000D_
                <a href="#A">A</a> |_x000D_
                <a href="#B">B</a> |_x000D_
                <a href="#Z">Z</a>_x000D_
            </div>_x000D_
    _x000D_
            <div id="term-defs">_x000D_
                <dl>_x000D_
                    <span id="A"></span>_x000D_
                    <dt>foo</dt>_x000D_
                    <dd>This is the sound made by a fool</dd>_x000D_
                    <!-- and so on ... -->_x000D_
                </dl>_x000D_
            </div>_x000D_
        </div>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

flex-grow ensures that the div's size is equal to the remaining size.

You could do the same without flexbox, but it would be more complicated to work out the height of #term-defs (you'd have to know the height of #top and use calc(100% - 999px) or set the height of #term-defs directly).
With flexbox dynamic sizes of the divs are possible.

One difference is that the scrollbar only appears on the term-defs div.

select2 onchange event only works once

This is due because of the items id being the same. On change fires only if a different item id is detected on select.

So you have 2 options: First is to make sure that each items have a unique id when retrieving datas from ajax.

Second is to trigger a rand number at formatSelection for the selected item.

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

.

formatSelection: function(item) {item.id =getRandomInt(1,200)}

What are the differences between NP, NP-Complete and NP-Hard?

I've been looking around and seeing many long explanations. Here is a small chart that may be useful to summarise:

Notice how difficulty increases top to bottom: any NP can be reduced to NP-Complete, and any NP-Complete can be reduced to NP-Hard, all in P (polynomial) time.

If you can solve a more difficult class of problem in P time, that will mean you found how to solve all easier problems in P time (for example, proving P = NP, if you figure out how to solve any NP-Complete problem in P time).

____________________________________________________________
| Problem Type | Verifiable in P time | Solvable in P time | Increasing Difficulty
___________________________________________________________|           |
| P            |        Yes           |        Yes         |           |
| NP           |        Yes           |     Yes or No *    |           |
| NP-Complete  |        Yes           |      Unknown       |           |
| NP-Hard      |     Yes or No **     |      Unknown ***   |           |
____________________________________________________________           V

Notes on Yes or No entries:

  • * An NP problem that is also P is solvable in P time.
  • ** An NP-Hard problem that is also NP-Complete is verifiable in P time.
  • *** NP-Complete problems (all of which form a subset of NP-hard) might be. The rest of NP hard is not.

I also found this diagram quite useful in seeing how all these types correspond to each other (pay more attention to the left half of the diagram).

WiX tricks and tips

Using the Msi Diagnostic logging to get detailed failure Information

msiexec /i Package.msi /l*v c:\Package.log

Where

Package.msi
is the name of your package and
c:\Package.log
is where you want the output of the log

Msi Error Codes

Wix Intro Video
Oh and Random Wix intro video featuring "Mr. WiX" Rob Mensching is "conceptual big picture" helpful.

Running a CMD or BAT in silent mode

I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)

That should answer your question.

Here it is:


From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

See the question for the full invis.vbs script:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
                                                         ^
                             means "invisible window" ---| 

Update after Tammen's feedback:

If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.

What does %~dp0 mean, and how does it work?

(First, I'd like to recommend this useful reference site for batch: http://ss64.com/nt/)

Then just another useful explanation: http://htipe.wordpress.com/2008/10/09/the-dp0-variable/

The %~dp0 Variable

The %~dp0 (that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.

The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.

If you follow the percent character (%) with a tilde character (~), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. The d modifier expands to the drive letter and the p modifier expands to the path of the parameter.

Example: Let’s say you have a directory on C: called bat_files, and in that directory is a file called example.bat. In this case, %~dp0 (combining the d and p modifiers) will expand to C:\bat_files\.

Check out this Microsoft article for a full explanation.

Also, check out this forum thread.

And a more clear reference from here:

  • %CmdCmdLine% will return the entire command line as passed to CMD.EXE

  • %* will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)

  • %~dn will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)

  • %~pn will return the directory of %n if %n is a valid path or file name (no UNC)

  • %~nn will return the file name only of %n if %n is a valid file name

  • %~xn will return the file extension only of %n if %n is a valid file name

  • %~fn will return the fully qualified path of %n if %n is a valid file name or directory

ADD 1

Just found some good reference for the mysterious ~ tilde operator.

The %~ string is called percent tilde operator. You can find it in situations like: %~0.

The :~ string is called colon tilde operator. You can find it like %SOME_VAR:~0,-1%.

ADD 2 - 1:12 PM 7/6/2018

%1-%9 refer to the command line args. If they are not valid path values, %~dp1 - %~dp9 will all expand to the same value as %~dp0. But if they are valid path values, they will expand to their own driver/path value.

For example: (batch.bat)

@echo off
@echo ~dp0= %~dp0
@echo ~dp1= %~dp1
@echo ~dp2= %~dp2
@echo on

Run 1:

D:\Workbench>batch arg1 arg2

~dp0= D:\Workbench\
~dp1= D:\Workbench\
~dp2= D:\Workbench\

Run 2:

D:\Workbench>batch c:\123\a.exe e:\abc\b.exe

~dp0= D:\Workbench\
~dp1= c:\123\
~dp2= e:\abc\

How can I change the width and height of slides on Slick Carousel?

I initialised the slider with one of the properties as

variableWidth: true

then i could set the width of the slides to anything i wanted in CSS with:

.slick-slide {
    width: 200px;
}

html button to send email

@user544079

Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:

<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">

Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):

<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">

How to simplify a null-safe compareTo() implementation?

See the bottom of this answer for updated (2013) solution using Guava.


This is what I ultimately went with. It turned out we already had a utility method for null-safe String comparison, so the simplest solution was to make use of that. (It's a big codebase; easy to miss this kind of thing :)

public int compareTo(Metadata other) {
    int result = StringUtils.compare(this.getName(), other.getName(), true);
    if (result != 0) {
        return result;
    }
    return StringUtils.compare(this.getValue(), other.getValue(), true);
}

This is how the helper is defined (it's overloaded so that you can also define whether nulls come first or last, if you want):

public static int compare(String s1, String s2, boolean ignoreCase) { ... }

So this is essentially the same as Eddie's answer (although I wouldn't call a static helper method a comparator) and that of uzhin too.

Anyway, in general, I would have strongly favoured Patrick's solution, as I think it's a good practice to use established libraries whenever possible. (Know and use the libraries as Josh Bloch says.) But in this case that would not have yielded the cleanest, simplest code.

Edit (2009): Apache Commons Collections version

Actually, here's a way to make the solution based on Apache Commons NullComparator simpler. Combine it with the case-insensitive Comparator provided in String class:

public static final Comparator<String> NULL_SAFE_COMPARATOR 
    = new NullComparator(String.CASE_INSENSITIVE_ORDER);

@Override
public int compareTo(Metadata other) {
    int result = NULL_SAFE_COMPARATOR.compare(this.name, other.name);
    if (result != 0) {
        return result;
    }
    return NULL_SAFE_COMPARATOR.compare(this.value, other.value);
}

Now this is pretty elegant, I think. (Just one small issue remains: the Commons NullComparator doesn't support generics, so there's an unchecked assignment.)

Update (2013): Guava version

Nearly 5 years later, here's how I'd tackle my original question. If coding in Java, I would (of course) be using Guava. (And quite certainly not Apache Commons.)

Put this constant somewhere, e.g. in "StringUtils" class:

public static final Ordering<String> CASE_INSENSITIVE_NULL_SAFE_ORDER =
    Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast(); // or nullsFirst()

Then, in public class Metadata implements Comparable<Metadata>:

@Override
public int compareTo(Metadata other) {
    int result = CASE_INSENSITIVE_NULL_SAFE_ORDER.compare(this.name, other.name);
    if (result != 0) {
        return result;
    }
    return CASE_INSENSITIVE_NULL_SAFE_ORDER.compare(this.value, other.value);
}    

Of course, this is nearly identical to the Apache Commons version (both use JDK's CASE_INSENSITIVE_ORDER), the use of nullsLast() being the only Guava-specific thing. This version is preferable simply because Guava is preferable, as a dependency, to Commons Collections. (As everyone agrees.)

If you were wondering about Ordering, note that it implements Comparator. It's pretty handy especially for more complex sorting needs, allowing you for example to chain several Orderings using compound(). Read Ordering Explained for more!

How to add/update an attribute to an HTML element using JavaScript?

Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

$('#element').attr( 'title', 'foo' );

How can I create a link to a local file on a locally-run web page?

Janky at best

<a href="file://///server/folders/x/x/filename.ext">right click </a></td>

and then right click, select "copy location" option, and then paste into url.

How to get a single value from FormGroup

Another option:

this.form.value['nameOfControl']

How to read a file without newlines?

my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":
        print(line[:-1])
    else:
        print(line)
my_file.close() 

How to change the text color of first select option

For Option 1 used as the placeholder:

select:invalid { color:grey; }

All other options:

select:valid { color:black; }

File name without extension name VBA

Simple but works well for me

FileName = ActiveWorkbook.Name 
If InStr(FileName, ".") > 0 Then 
   FileName = Left(FileName, InStr(FileName, ".") - 1) 
End If

How to simulate a real mouse click using java?

Well I had the same exact requirement, and Robot class is perfectly fine for me. It works on windows 7 and XP (tried java 6 & 7).

public static void click(int x, int y) throws AWTException{
    Robot bot = new Robot();
    bot.mouseMove(x, y);    
    bot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
    bot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}

May be you could share the name of the program that is rejecting your click?

What does <value optimized out> mean in gdb?

It means you compiled with e.g. gcc -O3 and the gcc optimiser found that some of your variables were redundant in some way that allowed them to be optimised away. In this particular case you appear to have three variables a, b, c with the same value and presumably they can all be aliassed to a single variable. Compile with optimisation disabled, e.g. gcc -O0, if you want to see such variables (this is generally a good idea for debug builds in any case).

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

How can I remove punctuation from input text in Java?

You can use following regular expression construct

Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

inputString.replaceAll("\\p{Punct}", "");

Role/Purpose of ContextLoaderListener in Spring?

ContextLoaderListener is optional. Just to make a point here: you can boot up a Spring application without ever configuring ContextLoaderListener, just a basic minimum web.xml with DispatcherServlet.

Here is what it would look like:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="
        http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    id="WebApp_ID" 
    version="2.5">
  <display-name>Some Minimal Webapp</display-name>
  <welcome-file-list>   
    <welcome-file>index.jsp</welcome-file>    
  </welcome-file-list>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

Create a file called dispatcher-servlet.xml and store it under WEB-INF. Since we mentioned index.jsp in welcome list, add this file under WEB-INF.

dispatcher-servlet.xml

In the dispatcher-servlet.xml define your beans:

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd     
        http://www.springframework.org/schema/context     
        http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="bean1">
      ...
    </bean>
    <bean id="bean2">
      ...
    </bean>         

    <context:component-scan base-package="com.example" />
    <!-- Import your other configuration files too -->
    <import resource="other-configs.xml"/>
    <import resource="some-other-config.xml"/>

    <!-- View Resolver -->
    <bean 
        id="viewResolver" 
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
      <property 
          name="viewClass" 
          value="org.springframework.web.servlet.view.JstlView" />
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
    </bean>
</beans>

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

What is secret key for JWT based authentication and how to generate it?

What is the secret key

The secret key is combined with the header and the payload to create a unique hash. You are only able to verify this hash if you have the secret key.

How to generate the key

You can choose a good, long password. Or you can generate it from a site like this.

Example (but don't use this one now):

8Zz5tw0Ionm3XPZZfN0NOml3z9FMfmpgXwovR9fp6ryDIoGRM8EPHAB6iHsc0fb

Android: combining text & image on a Button or ImageButton

<Button
     android:id="@+id/groups_button_bg"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Groups"
     android:drawableTop="@drawable/[image]" />


android:drawableLeft
android:drawableRight
android:drawableBottom
android:drawableTop

http://www.mokasocial.com/2010/04/create-a-button-with-an-image-and-text-android/

How to use andWhere and orWhere in Doctrine?

One thing missing here: if you have a varying number of elements that you want to put together to something like

WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')

and dont want to assemble a DQL-String yourself, you can use the orX mentioned above like this:

$patterns = ['abc', 'def'];
$orStatements = $qb->expr()->orX();
foreach ($patterns as $pattern) {
    $orStatements->add(
        $qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%'))
    );
}
$qb->andWhere($orStatements);

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

font-family: 'Open Sans'; font-weight: 600; important to change to a different font-family

Convert JSON to DataTable

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Move to next item using Java 8 foreach loop in stream

The lambda you are passing to forEach() is evaluated for each element received from the stream. The iteration itself is not visible from within the scope of the lambda, so you cannot continue it as if forEach() were a C preprocessor macro. Instead, you can conditionally skip the rest of the statements in it.

How to Install Font Awesome in Laravel Mix

How to Install Font Awesome 5 in Laravel 5.3 - 5.6 (The Right Way)

Build your webpack.mix.js configuration.

mix.setResourceRoot("../");

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

Install the latest free version of Font Awesome via a package manager like npm.

npm install @fortawesome/fontawesome-free

This dependency entry should now be in your package.json.

// Font Awesome
"dependencies": {
    "@fortawesome/fontawesome-free": "^5.15.2",

In your main SCSS file /resources/assets/sass/app.scss, import one or more styles.

@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/brands';

Compile your assets and produce a minified, production-ready build.

npm run production

Finally, reference your generated CSS file in your Blade template/layout.

<link type="text/css" rel="stylesheet" href="{{ mix('css/app.css') }}">

How to Install Font Awesome 5 with Laravel Mix 6 in Laravel 8 (The Right Way)

https://gist.github.com/karlhillx/89368bfa6a447307cbffc59f4e10b621

Steps to upload an iPhone application to the AppStore

Check that your singing identity IN YOUR TARGET properties is correct. This one over-rides what you have in your project properties.

Also: I dunno if this is true - but I wasn't getting emails detailing my binary rejections when I did the "ready for binary upload" from a PC - but I DID get an email when I did this on the MAC

HashMap: One Key, multiple Values

It sounds like you're looking for a multimap. Guava has various Multimap implementations, usually created via the Multimaps class.

I would suggest that using that implementation is likely to be simpler than rolling your own, working out what the API should look like, carefully checking for an existing list when adding a value etc. If your situation has a particular aversion to third party libraries it may be worth doing that, but otherwise Guava is a fabulous library which will probably help you with other code too :)

Correctly Parsing JSON in Swift 3

Updated the isConnectToNetwork-Function afterwards, thanks to this post.

I wrote an extra method for it:

import SystemConfiguration

func loadingJSON(_ link:String, postString:String, completionHandler: @escaping (_ JSONObject: AnyObject) -> ()) {

    if(isConnectedToNetwork() == false){
        completionHandler("-1" as AnyObject)
        return
    }

    let request = NSMutableURLRequest(url: URL(string: link)!)
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
        guard error == nil && data != nil else { // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 { // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }
        //JSON successfull
        do {
            let parseJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
            DispatchQueue.main.async(execute: {
                completionHandler(parseJSON as AnyObject)
            });
        } catch let error as NSError {
            print("Failed to load: \(error.localizedDescription)")
        }
    }
    task.resume()
}

func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    let ret = (isReachable && !needsConnection)

    return ret
}

So now you can easily call this in your app wherever you want

loadingJSON("yourDomain.com/login.php", postString:"email=\(userEmail!)&password=\(password!)") { parseJSON in

    if(String(describing: parseJSON) == "-1"){
        print("No Internet")
    } else {

    if let loginSuccessfull = parseJSON["loginSuccessfull"] as? Bool {
        //... do stuff
    }
}

How can I calculate the difference between two ArrayLists?

In Java, you can use the Collection interface's removeAll method.

// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
    add("apple");
    add("orange");
}};

Collection secondList = new ArrayList() {{
    add("apple");
    add("orange");
    add("banana");
    add("strawberry");
}};

// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);

// Remove all elements in firstList from secondList
secondList.removeAll(firstList);

// Show the "after" list
System.out.println("Result: " + secondList);

The above code will produce the following output:

First List: [apple, orange]
Second List: [apple, orange, banana, strawberry]
Result: [banana, strawberry]

SQL Server : fetching records between two dates?

You need to be more explicit and add the start and end times as well, down to the milliseconds:

select * 
from xxx 
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'

The database can very well interpret '2012-10-27' as '2012-10-27 00:00:00.000'.

How do I use WPF bindings with RelativeSource?

I didn't read every answer, but I just want to add this information in case of relative source command binding of a button.

When you use a relative source with Mode=FindAncestor, the binding must be like:

Command="{Binding Path=DataContext.CommandProperty, RelativeSource={...}}"

If you don't add DataContext in your path, at execution time it can't retrieve the property.

Show/hide 'div' using JavaScript

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

android studio 0.4.2: Gradle project sync failed error

I had same problem but finally I could solve it forever
Steps:

  1. Delete gradle and .gradle folders from your project folder.
  2. In Android Studio: Open your project then: File -> settings -> compiler -> gradle: enable offline mode
    Note: In relatively newer Android Studios, Offline mode has been moved to gradle setting. enter image description here
  3. Close your project: File -> close project
  4. Connect to the Internet and open your project again then let Android Studio downloads what it wants

If success then :)
else

  1. If you encounter gradle project sync failed again please follow these steps:
  2. Download the latest gradle package from this directory
  3. Extract it and put it somewhere (for example f:\gradle-1.10)
  4. Go to your Android Studio and load your project then open File->Settings->gradle, in this page click on Use local gradle distribution
  5. Type your gradle folder address there
    enter image description here

Congratulation you are done!

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.