Programs & Examples On #Codesynthesis

Code Synthesis is a systems software development company with a focus on automated object persistence, domain-specific languages (DSL) and their mappings, compiler design, code generation, and source-to-source translation.

Mongod complains that there is no /data/db folder

Create the folder.

sudo mkdir -p /data/db/

Give yourself permission to the folder.

sudo chown `id -u` /data/db

Then you can run mongod without sudo. Works on OSX Yosemite

Get the previous month's first and last day dates in c#

I use this simple one-liner:

public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
    return date.AddDays(-date.Day);
}

Be aware, that it retains the time.

How to change string into QString?

Alternative way:

std::string s = "This is an STL string";
QString qs = QString::fromAscii(s.data(), s.size());

This has the advantage of not using .c_str() which might cause the std::string to copy itself in case there is no place to add the '\0' at the end.

Python Pandas: Get index of rows which column matches certain value

I extended this question that is how to gets the row, columnand value of all matches value?

here is solution:

import pandas as pd
import numpy as np


def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
    nda_values = df_data.values
    tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
    return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]


if __name__ == '__main__':
    test_datas = [['cat', 'dog', ''],
                  ['goldfish', '', 'kitten'],
                  ['Puppy', 'hamster', 'mouse']
                  ]
    df_data = pd.DataFrame(test_datas)
    print(df_data)
    result_list = search_coordinate(df_data, {'dog', 'Puppy'})
    print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
    [print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]

Output:

          0        1       2
0       cat      dog        
1  goldfish           kitten
2     Puppy  hamster   mouse


row  col        name
0    1           dog
2    0         Puppy

Center an item with position: relative

Another option is to create an extra wrapper to center the element vertically.

_x000D_
_x000D_
#container{_x000D_
  border:solid 1px #33aaff;_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
}_x000D_
_x000D_
#helper{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:50%;_x000D_
  border:dotted 1px #ff55aa;_x000D_
}_x000D_
_x000D_
#centered{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:-50%;_x000D_
  border:solid 1px #ff55aa;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="helper">_x000D_
    <div id="centered"></div>_x000D_
  </div>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Git Pull vs Git Rebase

In a nutshell :

-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record

-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

This simply means that either tree, tree[otu], or tree[otu][0] evaluates to None, and as such is not subscriptable. Most likely tree[otu] or tree[otu][0]. Track it down with some simple debugging like this:

def Ancestors (otu,tree):
    try:
        tree[otu][0][0]
    except TypeError:
        print otu, tre[otu]
        raise
    #etc...

or pdb

Pure CSS scroll animation

And for webkit enabled browsers I've had good results with:

.myElement {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth; // Added in from answer from Felix
    overflow-x: scroll;
}

This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!

Hope that helps,

Ed

Removing an element from an Array (Java)

You could use the ArrayUtils API to remove it in a "nice looking way". It implements many operations (remove, find, add, contains,etc) on Arrays.
Take a look. It has made my life simpler.

How to make a dropdown readonly using jquery?

Easiest option for me was to make select as readonly and add:

onmousedown="return false" onkeydown="return false"

You don't need to write any extra logic. No hidden inputs or disabled and then re-enabled on form submit.

How do I encrypt and decrypt a string in python?

You can do this easily by using the library cryptocode. Here is how you install:

pip install cryptocode

Encrypting a message (example code):

import cryptocode

encoded = cryptocode.encrypt("mystring","mypassword")
## And then to decode it:
decoded = cryptocode.decrypt(encoded, "mypassword")

Documentation can be found here

npm not working - "read ECONNRESET"

In case this helps anyone who was in my situation: I recently installed Fiddler, which (unbeknownst to me) added a network proxy through 127.0.0.1:8866. I went into my Ubuntu network settings, clicked into the "Network Proxy" settings, and disabled it, and then all was back to normal.

So in general, check to make sure you haven't got a network proxy set up due to a side-effect of something else you were doing.

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

How to handle anchor hash linking in AngularJS

My solution with ng-route was this simple directive:

   app.directive('scrollto',
       function ($anchorScroll,$location) {
            return {
                link: function (scope, element, attrs) {
                    element.click(function (e) {
                        e.preventDefault();
                        $location.hash(attrs["scrollto"]);
                        $anchorScroll();
                    });
                }
            };
    })

The html is looking like:

<a href="" scrollTo="yourid">link</a>

Mock HttpContext.Current in Test Init Method

Below Test Init will also do the job.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

Check to ensure you are running npm install from the proper directory.

(The package.json file could be one extra directory down, for example.)

How to get MAC address of client using PHP?

//Simple & effective way to get client mac address
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');

// Capture the output into a variable

    $mycom=ob_get_contents();

// Clean (erase) the output buffer

    ob_clean();

$findme = "Physical";
//Search the "Physical" | Find the position of Physical text
$pmac = strpos($mycom, $findme);

// Get Physical Address
$mac=substr($mycom,($pmac+36),17);
//Display Mac Address
echo $mac;

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

I had a error when i was installing many plugins So the error 100 showed including the location of the last plugin that i installed C:\wamp\www\mysite\wp-content\plugins\"..." so i deleted this plugin folder on the C: drive then everything was back to normal.I think i have to limit the amount of plug-in i install or have activated .good luck i hope it helps

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

input[type='text'] CSS selector does not apply to default-type text inputs?

try this

 input[type='text']
 {
   background:red !important;
 }

C/C++ maximum stack size of program

I am not sure what you mean by doing a depth first search on a rectangular array, but I assume you know what you are doing.

If the stack limit is a problem you should be able to convert your recursive solution into an iterative solution that pushes intermediate values onto a stack which is allocated from the heap.

How to trim a file extension from a String in JavaScript?

If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:

theName = thePath.split("/").slice(-1).join().split(".").shift();

the result will be theName == "filename";

To try it write the following command into the console window of your chrome debugger: window.location.pathname.split("/").slice(-1).join().split(".").shift()

If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):

theName = theNameWithExt.split(".").shift();

the result will be theName == "filename", the same as above;

Notes:

  1. The first one is a little bit slower cause performes more operations; but works in both cases, in other words it can extract the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.
  2. Both solutions work for both local and server files;

But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.

working snippet 1: the complete path

_x000D_
_x000D_
var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";_x000D_
theName = thePath.split("/").slice(-1).join().split(".").shift();_x000D_
alert(theName);
_x000D_
  
_x000D_
_x000D_
_x000D_

working snippet 2: the file name with extension

_x000D_
_x000D_
var theNameWithExt = "filename.jpg";_x000D_
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();_x000D_
alert(theName);
_x000D_
  
_x000D_
_x000D_
_x000D_

working snippet 2: the file name with double extension

_x000D_
_x000D_
var theNameWithExt = "filename.tar.gz";_x000D_
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();_x000D_
alert(theName);
_x000D_
  
_x000D_
_x000D_
_x000D_

Switch case with conditions

function date_conversion(start_date){
    var formattedDate = new Date(start_date);
    var d = formattedDate.getDate();
    var m =  formattedDate.getMonth();
    var month;
    m += 1;  // JavaScript months are 0-11
    switch (m) {
        case 1: {
            month="Jan";
            break;
        }
        case 2: {
            month="Feb";
            break;
        }
        case 3: {
            month="Mar";
            break;
        }
        case 4: {
            month="Apr";
            break;
        }
        case 5: {
            month="May";
            break;
        }
        case 6: {
            month="Jun";
            break;
        }
        case 7: {
            month="Jul";
            break;
        }
        case 8: {
            month="Aug";
            break;
        }
        case 9: {
            month="Sep";
            break;
        }
        case 10: {
            month="Oct";
            break;
        }
        case 11: {
            month="Nov";
            break;
        }
        case 12: {
            month="Dec";
            break;
        }
    }
    var y = formattedDate.getFullYear();
    var now_date=d + "-" + month + "-" + y;
    return now_date;
}

Convert ndarray from float64 to integer

While astype is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr in the following examples:

>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1.,  2.,  3.,  4.])

The int* functions from NumPy

>>> np.int64(arr)
array([1, 2, 3, 4])

>>> np.int_(arr)
array([1, 2, 3, 4])

The NumPy *array functions themselves:

>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])

The astype method (that was already mentioned but for completeness sake):

>>> arr.astype(int)
array([1, 2, 3, 4])

Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32 or np.int64.

How do I turn off Unicode in a VC++ project?

None of the above solutions worked for me. But

#include <Windows.h>

worked fine.

How to update SQLAlchemy row entry?

I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model

def update_state(chat_id, state):
    try:
        value = Users.query.filter(Users.chat_id == str(chat_id)).first()
        value.state = str(state)
        db.session.flush()
        db.session.commit()
        #db.session.close()
    except:
        print('Error in def update_state')

Why use db.session.flush()? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?

How to send Basic Auth with axios

Hi you can do this in the following way

var username = '';
var password = ''

const token = `${username}:${password}`;
const encodedToken = Buffer.from(token).toString('base64');
const session_url = 'http://api_address/api/session_endpoint';

var config = {
  method: 'get',
  url: session_url,
  headers: { 'Authorization': 'Basic '+ encodedToken }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

"date(): It is not safe to rely on the system's timezone settings..."

A simple method for two time zone.

<?php 
$date = new DateTime("2012-07-05 16:43:21", new DateTimeZone('Europe/Paris')); 

date_default_timezone_set('America/New_York'); 

echo date("Y-m-d h:iA", $date->format('U')); 

// 2012-07-05 10:43AM 
?>

How the single threaded non blocking IO model works in Node.js

The function c.query() has two argument

c.query("Fetch Data", "Post-Processing of Data")

The operation "Fetch Data" in this case is a DB-Query, now this may be handled by Node.js by spawning off a worker thread and giving it this task of performing the DB-Query. (Remember Node.js can create thread internally). This enables the function to return instantaneously without any delay

The second argument "Post-Processing of Data" is a callback function, the node framework registers this callback and is called by the event loop.

Thus the statement c.query (paramenter1, parameter2) will return instantaneously, enabling node to cater for another request.

P.S: I have just started to understand node, actually I wanted to write this as comment to @Philip but since didn't have enough reputation points so wrote it as an answer.

How to ALTER multiple columns at once in SQL Server

Thanks to Evan's code sample, I was able to modify it more and get it more specific to tables starting with, specific column names AND handle specifics for constraints too. I ran that code and then copied the [CODE] column and executed it without issue.

USE [Table_Name]
GO
SELECT
     TABLE_CATALOG
    ,TABLE_SCHEMA
    ,TABLE_NAME
    ,COLUMN_NAME
    ,DATA_TYPE
    ,'ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] DROP CONSTRAINT [DEFAULT_'+TABLE_NAME+'_'+COLUMN_NAME+']; 
ALTER TABLE  ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ALTER COLUMN ['+COLUMN_NAME+'] datetime2 (7) NOT NULL 
ALTER TABLE  ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ADD CONSTRAINT [DEFAULT_'+TABLE_NAME+'_'+COLUMN_NAME+'] DEFAULT (''3/6/2018 6:47:23 PM'') FOR ['+COLUMN_NAME+']; 
GO' AS '[CODE]'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'form_%' AND TABLE_SCHEMA = 'dbo'
 AND (COLUMN_NAME = 'FormInserted' OR COLUMN_NAME = 'FormUpdated')
 AND DATA_TYPE = 'datetime'

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

CORS: credentials mode is 'include'

Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

On the Angular side required adding option flag withCredentials: true for Cookie transport:

constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

Get Unix timestamp with C++

As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:

#include <chrono>

//...

using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.

Best way to display data via JSON using jQuery

JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.

Failed to connect to mailserver at "localhost" port 25

First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.

How do I get rid of the b-prefix in a string in python?

You need to decode it to convert it to a string. Check the answer here about bytes literal in python3.

In [1]: b'I posted a new photo to Facebook'.decode('utf-8')
Out[1]: 'I posted a new photo to Facebook'

How to resize a VirtualBox vmdk file


VirtualBox for Windows

Resizing your disk file while preserving your virtual machine settings!


Step 1 - Resize the disk file

Start cmd.exe

cd to Oracle VM VirtualBox's dir (on 64-bit systems: "C:\Program Files\Oracle\VirtualBox\")

Run these commands (as above):

VBoxManage clonehd "C:\path\to\source.vmdk" "C:\path_to\cloned.vdi" --format vdi
VBoxManage modifyhd "C:\path\to\cloned.vdi" --resize 51200

Windows explorer and "copy address as text" via the address bar should help you get the path you need.

On windows system, The VirtaulBox VM directory underneath your user may contain an XML formatted database file of settings you've configured for your VM. Rename this file, with a .bak extension (it has a .vbox extension). Rename the original .vmdk file with a .bak extension as well to avoid another error. You can now safetly perform the third step without the error message to convert the machine back to .vmdk format, or the "duplicate disk" error.

VBoxManage clonehd "C:\path_to\cloned.vdi" "C:\path_to\source.vmdk" --format vmdk

You will be presented with a UID token. Copy this token by drag-highlighting it from the Windows Command Interpetor window and using the Ctrl+C keyboard shortcut.

Open the .vbox.bak file in a text editor such as Notepad++. You'll be presented with an XML-like database file. Look for these lines:

<VirtualBox xmlns="http://www.virtualbox.org/" version="1.16-windows">
  <Machine uuid="{some uid}" name="source disk name" OSType="the_vbox_OS" snapshotFolder="Snapshots" lastStateChange="2043-03-23T00:54:18Z">
    <MediaRegistry>
      <HardDisks>
        <HardDisk uuid="{some uid}" location="C:\path_to\source.vmdk" ...

On the line <HardDisk uuid="{some uid}" location="C:\path_to\source.vmdk" ..., delete the old UID token between the brackets and paste the one you copied from the command window. Make sure that you leave the brackets in place!

Save this file, and exit your text editor. Rename the .vbox.bak file to give it back its expected extension of .vbox.


Step 2 - Remove the junk

It is now safe to remove the .bak files remaining in the directory. What remains is a resized .vmdk with an updated .vbox database while with your previously preserved VirtualBox Manager settings.


Step 3 - Resize the disk's partition to fill the free space

You can now start the VirtualBox VM Manager and execute your VM, using the appropriate tools for the operating system to fill the new free space.

For Windows VMs, use diskpart from the command prompt booted from the Windows Recovery Consule (recovery partition) to SELECT DISK 1, LIST PARTITION and gather the partition number of your C:\ drive, then SELECT PARTITION #. You can use the EXTEND SIZE=mb to resize the Windows C:\ drive to the appropriate value. Make sure you leave room for the recovery and boot partitions! It's safe to subtract 4096 MB from your new virtual disk size to get this value, because of shadow copy and windows recovery files.

For Linux VMs, a live .ISO of gparted you can boot with the VM's disk file can be found at: http://gparted.org/ It will get you straight into a graphical user interface-based gparted-gtk, from where you can fill your free space.

For PPC / Mac VMs, Disk Utility from the Finder will asisst you in filling the free space, but you may want to consider the gparted Linux option, as currently the only method of which to boot MacOSX in VirtualBox is hackintosh, and you cannot extend your volume while booted into MacOSX. You may also want to seek out tweaking the VM's settings temporarily for gparted, to get it to boot. MacOSX partitions are recognized by gparted as HFS - "Heaping File System" partitions.


Step 4 - Cat Photos

Because the internet. ;) You're finished. Enjoy your new resized virtual .vmdk disk image with VirtualBox for Windows!

.NET DateTime to SqlDateTime Conversion

on my quest to do this with entitie, i stumbled over here, just hitting back to post what i've found out...

when using EF4, "a sql's" datetime column can be filled from .NET's DateTime using BitConverter.

EntitieObj.thetime = BitConverter.GetBytes(DateTime.Now.ToBinary());

also Fakrudeen's link brought me further... thank you.

How to change identity column values programmatically?

Firstly the setting of IDENTITY_INSERT on or off for that matter will not work for what you require (it is used for inserting new values, such as plugging gaps).

Doing the operation through the GUI just creates a temporary table, copies all the data across to a new table without an identity field, and renames the table.

How to use SearchView in Toolbar Android

Integrating SearchView with RecyclerView

1) Add SearchView Item in Menu

SearchView can be added as actionView in menu using

app:useActionClass = "android.support.v7.widget.SearchView" .

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
    android:id="@+id/searchBar"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    />
</menu>

2) Implement SearchView.OnQueryTextListener in your Activity

SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.

YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

   public boolean onQueryTextSubmit(String query)

   public boolean onQueryTextChange(String newText) 

}

3) Set up SerchView Hint text, listener etc

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.searchBar);

    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search People");
    searchView.setOnQueryTextListener(this);
    searchView.setIconified(false);

    return true;
}

4) Implement SearchView.OnQueryTextListener

This is how you can implement abstract methods of the listener.

@Override
public boolean onQueryTextSubmit(String query) {

    // This method can be used when a query is submitted eg. creating search history using SQLite DB

    Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    adapter.filter(newText);
    return true;
}

5) Write a filter method in your RecyclerView Adapter.

You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.

public void filter(String queryText)
{
    list.clear();

    if(queryText.isEmpty())
    {
        list.addAll(copyList);
    }
    else
    {

        for(String name: copyList)
        {
            if(name.toLowerCase().contains(queryText.toLowerCase()))
            {
                list.add(name);
            }
        }

    }

    notifyDataSetChanged();
}

Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App

nginx: send all requests to a single html page

Using just try_files didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.

The Nginx docs had some additional details:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

So I ended up using the following:

root /var/www/mysite;

location / {
    try_files $uri /base.html;
}

location = /base.html {
    expires 30s;
}

How to add jQuery in JS file

You can create a master page base without included js and jquery files. Put a content place holder in master page base in head section, then create a nested master page that inherits from this master page base. Now put your includes in a asp:content in nested master page, finally create a content page from this nested master page

Example:

//in master page base    

<%@  master language="C#" autoeventwireup="true" inherits="MasterPage" codebehind="MasterPage.master.cs" %>
<html>
<head id="Head1" runat="server">
    <asp:ContentPlaceHolder runat="server" ID="cphChildHead">
        <!-- Nested Master Page include Codes will sit Here -->
    </asp:ContentPlaceHolder>
</head>
<body>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
    <!-- some code here -->
</body>
</html>

//in nested master page :
<%@  master language="C#" masterpagefile="~/MasterPage.master" autoeventwireup="true"
    codebehind="MasterPageLib.master.cs" inherits="sampleNameSpace" %>
<asp:Content ID="headcontent" ContentPlaceHolderID="cphChildHead" runat="server">
    <!-- includes will set here a nested master page -->
    <link href="../CSS/pwt-datepicker.css" rel="stylesheet" type="text/css" />

    <script src="../js/jquery-1.9.0.min.js" type="text/javascript"></script>

    <!-- other includes ;) -->
</asp:Content>
<asp:Content ID="bodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ContentPlaceHolder ID="cphChildBody" runat="server" EnableViewState="true">
        <!-- Content page code will sit Here -->
    </asp:ContentPlaceHolder>
</asp:Content>

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Commenting in a Bash script inside a multiline command

As DigitalRoss pointed out, the trailing backslash is not necessary when the line woud end in |. And you can put comments on a line following a |:

 cat ${MYSQLDUMP} |         # Output MYSQLDUMP file
 sed '1d' |                 # skip the top line
 tr ",;" "\n" | 
 sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' |
 sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' |
 sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' |
 tr "\n" "," |
 sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' |   # hate phone numbers
 sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}

Pipe output and capture exit status in Bash

Base on @brian-s-wilson 's answer; this bash helper function:

pipestatus() {
  local S=("${PIPESTATUS[@]}")

  if test -n "$*"
  then test "$*" = "${S[*]}"
  else ! [[ "${S[@]}" =~ [^0\ ] ]]
  fi
}

used thus:

1: get_bad_things must succeed, but it should produce no output; but we want to see output that it does produce

get_bad_things | grep '^'
pipeinfo 0 1 || return

2: all pipeline must succeed

thing | something -q | thingy
pipeinfo || return

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Here's a project that combines the best parts (pros) of both redux-saga and redux-thunk: you can handle all side-effects on sagas while getting a promise by dispatching the corresponding action: https://github.com/diegohaz/redux-saga-thunk

class MyComponent extends React.Component {
  componentWillMount() {
    // `doSomething` dispatches an action which is handled by some saga
    this.props.doSomething().then((detail) => {
      console.log('Yaay!', detail)
    }).catch((error) => {
      console.log('Oops!', error)
    })
  }
}

Can someone explain the dollar sign in Javascript?

My answer is here lacks technomalogical sophistication to the extent it even employs words like "technomalogical" which are one of those words which aren't actually in the dictionary but have infrequent usage such as the word "gullible" which also cannot be found in the dictionary either.

All that aside: here's me simple answer to a simple question in a simple way to answer a question like this one which is very complicated to ask and the simple wishy washy answer to the wishy washy question like this is thus:

The $('#ident') thing says "document.getElementById('ident').

The $('.classname') thing says "document.getElementByClass('classname').

Yes I know there is no getElementByClass but thats kind of what people are saying when they use the $ symbol like that which is a jQuery syntax. Now you know the answer, I bet you are still lost for how to ask the question. Well now you dont have to learn jQuery just to understand jQuery babel a bit right? Give me a +10 please!

How to detect when cancel is clicked on file input?

A lot of people keep suggesting the change event... even though OP specified that this doesn't work in the question:

CLICKING CANCEL DOES NOT SELECT A FILE AND THUS WILL NOT TRIGGER A CHANGE TO FILE INPUT!!!

all the code most people are suggesting will NOT run when cancel is clicked.

After a lot of experimentation based on suggestions from people who actually read OP's question, I've come up with this class to wrap the functionality of the file input and added two custom events:

  • choose: The user has chosen a file (still triggers if they select the same file again).
  • cancel: The user has clicked cancel or otherwise closed the file dialog with no selection.

I've also added redundancy (listen to multiple events to try and determine if cancel was pressed). Might not always respond right away but should at least guarantee that a cancel event is registered when the user re-engages the page.

Finally I noticed that events are not always guaranteed to happen in the same order (especially when the dialog closing triggers them all at nearly the same instant). This class waits for 100ms to make sure that the change event has fired before it checks for a success flag.

Uses ES6 class so probably won't work for anything before that FYI, though you could probably edit it if you wanna waste your time making it work on IE .

The Class:

class FileManager {
    // Keep important properties from being overwritten
    constructor() {
        Object.defineProperties(this, {
            // The file input element (hidden)
            _fileInput: {
                value: document.createElement('input'),
                writeable: false,
                enumerable: false,
                configurable: false
            },
            // Flag to denote if a file was chosen
            _chooseSuccess: {
                value: false,
                writable: true,
            },
            // Keeps events from mult-firing
            // Don't want to consume just incase!
            _eventFiredOnce: {
                value: false,
                writable: true,
            },
            // Called BEFORE dialog is shown
            _chooseStart_handler: {
                value: (event) => {
                    // Choose might happen, assume it won't
                    this._chooseSuccess = false;

                    // Allow a single fire
                    this._eventFiredOnce = false;

                    // Reset value so repeat files also trigger a change/choose
                    this._fileInput.value = '';



                    /* File chooser is semi-modal and will stall events while it's opened */
                    /* Beware, some code can still run while the dialog is opened! */

                    // Window will usually focus on dialog close
                    // If it works this is best becuase the event will trigger as soon as the dialog is closed
                    // Even the user has moved the dialog off of the browser window is should still refocus
                    window.addEventListener('focus', this._chooseEnd_handler);

                    // This will always fire when the mouse first enters the body
                    // A good redundancy but will not fire immeditely if the cance button is not...
                    // in window when clicked
                    document.body.addEventListener('mouseenter', this._chooseEnd_handler);

                    // Again almost a guarantee that this will fire but it will not do so...
                    // imediately if the dialog is out of window!
                    window.addEventListener('mousemove', this._chooseEnd_handler);
                },
                writeable: false,
                enumerable: false,
                configurable: false
            },
            _chooseEnd_handler: {
                // Focus event may beat change event
                // Wait 1/10th of a second to make sure change registers!
                value: (event) => {
                    // queue one event to fire
                    if (this._eventFiredOnce)
                        return;

                    // Mark event as fired once
                    this._eventFiredOnce = true;
                    // double call prevents 'this' context swap, IHT!
                    setTimeout((event) => {
                        this._timeout_handler(event);
                    }, 100);
                },
                writeable: false,
                enumerable: false,
                configurable: false
            },
            _choose_handler: {
                value: (event) => {
                    // A file was chosen by the user
                    // Set flag
                    this._chooseSuccess = true;
                    // End the choose
                    this._chooseEnd_handler(event);
                },
                writeable: false,
                enumerable: false,
                configurable: false
            },
            _timeout_handler: {
                value: (event) => {
                    if (!this._chooseSuccess) {
                        // Choose process done, no file selected
                        // Fire cancel event on input
                        this._fileInput.dispatchEvent(new Event('cancel'));
                    } else {
                        // Choose process done, file was selected
                        // Fire chosen event on input
                        this._fileInput.dispatchEvent(new Event('choose'));
                    }

                    // remove listeners or cancel will keep firing
                    window.removeEventListener('focus', this._chooseEnd_handler);
                    document.body.removeEventListener('mouseenter', this._chooseEnd_handler);
                    window.removeEventListener('mousemove', this._chooseEnd_handler);
                },
                writeable: false,
                enumerable: false,
                configurable: false
            },
            addEventListener: {
                value: (type, handle) => {
                    this._fileInput.addEventListener(type, handle);
                },
                writeable: false,
                enumerable: false,
                configurable: false
            },
            removeEventListener: {
                value: (type, handle) => {
                    this._fileInput.removeEventListener(type, handle);
                },
                writeable: false,
                enumerable: false,
                configurable: false
            },
            // Note: Shadow clicks must be called from a user input event stack!
            openFile: {
                value: () => {
                    // Trigger custom pre-click event
                    this._chooseStart_handler();

                    // Show file dialog
                    this._fileInput.click();
                    // ^^^ Code will still run after this part (non halting)
                    // Events will not trigger though until the dialog is closed
                }
            }
        });
        this._fileInput.type = 'file';
        this._fileInput.addEventListener('change', this._choose_handler);
    }

    // Get all files
    get files() {
        return this._input.files;
    }

    // Get input element (reccomended to keep hidden);
    get domElement(){
        return this._fileInput;
    }

    // Get specific file
    getFile(index) {
        return index === undefined ? this._fileInput.files[0] : this._fileInput.files[index];
    }

    // Set multi-select
    set multiSelect(value) {
        let val = value ? 'multiple' : '';
        this._fileInput.setAttribute('multiple', val);
    }

    // Get multi-select
    get multiSelect() {
        return this._fileInput.multiple === 'multiple' ? true : false;
    }
}

Usage Example:

// Instantiate
let fm = new FileManager();

// Bind to something that triggers a user input event (buttons are good)
let btn = document.getElementById('btn');

// Call openFile on intance to show the dialog to the user
btn.addEventListener('click', (event) => {
  fm.openFile();
});

// Fires if the user selects a file and clicks the 'okay' button
fm.addEventListener('choose', (event) => {
  console.log('file chosen: ' + fm.getFile(0).name);
});

// Fires if the user clicks 'cancel' or closes the file dialog
fm.addEventListener('cancel', (event) => {
  console.log('File choose has been canceled!');
});

Might be very late but I think this is a decent solution that covers most of the crippling edge cases. I'll be using this solution myself so I might come back with a git repo eventually after I play with it and refine it more.

How to set java_home on Windows 7?

This is the official solution for setting the Java environment from www.java.com - here.

There are solutions for Windows 7, Windows Vista, Windows XP, Linux/Solaris and other shells.


Example

Windows 7

  1. Select Computer from the Start menu
  2. Choose System Properties from the context menu
  3. Click Advanced system settings -> Advanced tab
  4. Click on Environment Variables, under System Variables, find PATH, and click on it.
  5. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  6. Reopen Command prompt window, and run your Java code.

Where can I find the Java SDK in Linux after installing it?

This depends a bit from your package system ... if the java command works, you can type readlink -f $(which java) to find the location of the java command. On the OpenSUSE system I'm on now it returns /usr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/bin/java (but this is not a system which uses apt-get).


On Ubuntu, it looks like it is in /usr/lib/jvm/java-6-openjdk/ for OpenJDK, and in some other subdirectory of /usr/lib/jvm/ for Suns JDK (and other implementations as well, I think).

Debian is the same.


For any given package you can determine what files it installs and where it installs them by querying dpkg. For example for the package 'openjdk-6-jdk': dpkg -L openjdk-6-jdk

How can I use jQuery to move a div across the screen

You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

To read up on this, check out this thread (from my very first Stackoverflow post no less)!

Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

Drawing an image from a data URL to a canvas

You might wanna clear the old Image before setting a new Image.

You also need to update the Canvas size for a new Image.

This is how I am doing in my project:

    // on image load update Canvas Image 
    this.image.onload = () => {

      // Clear Old Image and Reset Bounds
      canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.canvas.height = this.image.height;
      this.canvas.width = this.image.width;

      // Redraw Image
      canvasContext.drawImage(
        this.image,
        0,
        0,
        this.image.width,
        this.image.height
      );
    };

How to clear cache in Yarn?

Run yarn cache clean.


Run yarn help cache in your bash, and you will see:

Usage: yarn cache [ls|clean] [flags]

Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executing

Visit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.

what is the most efficient way of counting occurrences in pandas?

I think df['word'].value_counts() should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count should be much slower than max. Both take some time to avoid missing values. (Compare with size.)

In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.

Need to find a max of three numbers in java

It would help if you provided the error you are seeing. Look at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html and you will see that max only returns the max between two numbers, so likely you code is not even compiling.

Solve all your compilation errors first.

Then your homework will consist of finding the max of three numbers by comparing the first two together, and comparing that max result with the third value. You should have enough to find your answer now.

Your branch is ahead of 'origin/master' by 3 commits

This happened to me once after I merged a pull request on Bitbucket.

I just had to do:

git fetch

My problem was solved. I hope this helps!!!

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

phpMyAdmin - The MySQL Extension is Missing

I just add

apt-get install php5-mysqlnd

This will ask to overwrite mysql.so from "php5-mysql".

This work for me.

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

Using "If cell contains #N/A" as a formula condition.

A possible alternative approach in Excel 2010 or later versions:

AGGREGATE(6,6,A1,B1)

In AGGREGATE function the first 6 indicates PRODUCT operation and the second 6 denotes "ignore errors"

[untested]

Finding multiple occurrences of a string within a string in Python

This version should be linear in length of the string, and should be fine as long as the sequences aren't too repetitive (in which case you can replace the recursion with a while loop).

def find_all(st, substr, start_pos=0, accum=[]):
    ix = st.find(substr, start_pos)
    if ix == -1:
        return accum
    return find_all(st, substr, start_pos=ix + 1, accum=accum + [ix])

bstpierre's list comprehension is a good solution for short sequences, but looks to have quadratic complexity and never finished on a long text I was using.

findall_lc = lambda txt, substr: [n for n in xrange(len(txt))
                                   if txt.find(substr, n) == n]

For a random string of non-trivial length, the two functions give the same result:

import random, string; random.seed(0)
s = ''.join([random.choice(string.ascii_lowercase) for _ in range(100000)])

>>> find_all(s, 'th') == findall_lc(s, 'th')
True
>>> findall_lc(s, 'th')[:4]
[564, 818, 1872, 2470]

But the quadratic version is about 300 times slower

%timeit find_all(s, 'th')
1000 loops, best of 3: 282 µs per loop

%timeit findall_lc(s, 'th')    
10 loops, best of 3: 92.3 ms per loop

How do I "break" out of an if statement?

I don't know your test conditions, but a good old switch could work

switch(colour)
{
  case red:
  {
    switch(car)
    { 
      case hyundai: 
      {
        break;
      }
      :
    }
    break;
  }
  :
}

Set up adb on Mac OS X

If you are using ZSH and have Android Studio 1.3: 1. Open .zshrc file (Located in your home directory, file is hidden so make sure you can see hidden files) 2. Add this line at the end: alias adb="/Users/kamil/Library/Android/sdk/platform-tools/adb" 3. Quit terminal 4. Open terminal and type in adb devices 5. If it worked it will give you list of all connected devices

Editable text to string

If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString().

How do I install Python OpenCV through Conda?

I have summarized my now fully working solution, OpenCV-Python - How to install OpenCV-Python package to Anaconda (Windows). Nevertheless I've copied and pasted the important bits to this post.


At the time of writing I was using Windows 8.1, 64-bit machine, Anaconda/ Python 2.x. (see notes below - this works also for Windows 10, and likely Python 3.x too).

  • NOTE 1: as mentioned mentioned by @great_raisin (thank you) in comment section however, this solution appears to also work for Windows 10.

  • NOTE 2: this will probably work for Anaconda/Python 3.x too. If you are using Windows 10 and Anaconda/Python 3.x, and this solution works, please add a comment below. Thanks! (Update: noting from comment "Working on Windows 10")

  • NOTE 3: depending on whether you are using Python 2.x or 3.x, just adjust the print statement accordingly in code snippets. i.e. in Python 3.x it would be print("hello"), and in Python 2.x it would be print "hello".

TL;DR

To use OpenCV fully with Anaconda (and Spyder IDE), we need to:

  1. Download the OpenCV package from the official OpenCV site
  2. Copy and paste the cv2.pyd to the Anaconda site-packages directory.
  3. Set user environmental variables so that Anaconda knows where to find the FFMPEG utility.
  4. Do some testing to confirm OpenCV and FFMPEG are now working.

(Read on for the detail instructions...)

Prerequisite

Install Anaconda

Anaconda is essentially a nicely packaged Python IDE that is shipped with tons of useful packages, such as NumPy, Pandas, IPython Notebook, etc. It seems to be recommended everywhere in the scientific community. Check out Anaconda to get it installed.

Install OpenCV-Python to Anaconda

Cautious Note: I originally tried out installing the binstar.org OpenCV package, as suggested. That method however does not include the FFMPEG codec - i.e. you may be able to use OpenCV, but you won't be able to process videos.

The following instruction works for me is inspired by this OpenCV YouTube video. So far I have got it working on both my desktop and laptop, both 64-bit machines and Windows 8.1.

Download OpenCV Package

Firstly, go to the official OpenCV site to download the complete OpenCV package. Pick a version you like (2.x or 3.x). I am on Python 2.x and OpenCV 3.x - mainly because this is how the OpenCV-Python Tutorials are setup/based on.

In my case, I've extracted the package (essentially a folder) straight to my C drive (C:\opencv).

Copy and Paste the cv2.pyd file

The Anaconda Site-packages directory (e.g. C:\Users\Johnny\Anaconda\Lib\site-packages in my case) contains the Python packages that you may import. Our goal is to copy and paste the cv2.pyd file to this directory (so that we can use the import cv2 in our Python codes.).

To do this, copy the cv2.pyd file...

From this OpenCV directory (the beginning part might be slightly different on your machine). For Python 3.x, I guess, just change the 2.x to 3.x accordingly.

# Python 2.7 and 32-bit machine:
C:\opencv\build\python\2.7\x84

# Python 2.7 and 64-bit machine:
C:\opencv\build\python\2.7\x64

To this Anaconda directory (the beginning part might be slightly different on your machine):

C:\Users\Johnny\Anaconda\Lib\site-packages

After performing this step we shall now be able to use import cv2 in Python code. BUT, we still need to do a little bit more work to get FFMPEG (video codec) to work (to enable us to do things like processing videos).

Set Environmental Variables

Right-click on "My Computer" (or "This PC" on Windows 8.1) ? left-click Properties ? left-click "Advanced" tab ? left-click "Environment Variables..." button.

Add a new User Variable to point to the OpenCV (either x86 for 32-bit system or x64 for 64-bit system). I am currently on a 64-bit machine.

| 32-bit or 64 bit machine? | Variable     | Value                                |
|---------------------------|--------------|--------------------------------------|
| 32-bit                    | `OPENCV_DIR` | `C:\opencv\build\x86\vc12`           |
| 64-bit                    | `OPENCV_DIR` | `C:\opencv\build\x64\vc12`           |

Append %OPENCV_DIR%\bin to the User Variable PATH.

For example, my PATH user variable looks like this...

Before:

C:\Users\Johnny\Anaconda;C:\Users\Johnny\Anaconda\Scripts

After:

C:\Users\Johnny\Anaconda;C:\Users\Johnny\Anaconda\Scripts;%OPENCV_DIR%\bin

This is it we are done! FFMPEG is ready to be used!

Test to confirm

We need to test whether we can now do these in Anaconda (via Spyder IDE):

  • Import OpenCV package
  • Use the FFMPEG utility (to read/write/process videos)

Test 1: Can we import OpenCV?

To confirm that Anaconda is now able to import the OpenCV-Python package (namely, cv2), issue these in the IPython console:

import cv2
print cv2.__version__

If the package cv2 is imported OK with no errors, and the cv2 version is printed out, then we are all good! Here is a snapshot:

import-cv2-ok-in-anaconda-python-2.png
(source: mathalope.co.uk)

Test 2: Can we Use the FFMPEG codec?

Place a sample input_video.mp4 video file in a directory. We want to test whether we can:

  • read this .mp4 video file, and
  • write out a new video file (can be .avi or .mp4 etc.)

To do this we need to have a test Python code, call it test.py. Place it in the same directory as the sample input_video.mp4 file.

This is what test.py may look like (I've listed out both newer and older version codes here - do let us know which one works / not work for you!).

(Newer version...)

import cv2
cap = cv2.VideoCapture("input_video.mp4")
print cap.isOpened()   # True = read video successfully. False - fail to read video.

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter("output_video.avi", fourcc, 20.0, (640, 360))
print out.isOpened()  # True = write out video successfully. False - fail to write out video.

cap.release()
out.release()

(Or the older version...)

import cv2
cv2.VideoCapture("input_video.mp4")
print cv2.isOpened()   # True = read video successfully. False - fail to read video.

fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter("output_video.avi",fourcc, 20.0, (640,360))
print out.isOpened()  # True = write out video successfully. False - fail to write out video.

cap.release()
out.release()

This test is VERY IMPORTANT. If you'd like to process video files, you'd need to ensure that Anaconda / Spyder IDE can use the FFMPEG (video codec). It took me days to have got it working. But I hope it would take you much less time! :)

Note: One more very important tip when using the Anaconda Spyder IDE. Make sure you check the current working directory (CWD)!!!

Conclusion

To use OpenCV fully with Anaconda (and Spyder IDE), we need to:

  1. Download the OpenCV package from the official OpenCV site
  2. Copy and paste the cv2.pyd to the Anaconda site-packages directory.
  3. Set user environmental variables so that Anaconda knows where to find the FFMPEG utility.
  4. Do some testing to confirm OpenCV and FFMPEG are now working.

Good luck!

JUnit Testing Exceptions

If your constructor is similar to this one:

public Example(String example) {
    if (example == null) {
        throw new NullPointerException();
    }
    //do fun things with valid example here
}

Then, when you run this JUnit test you will get a green bar:

@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
    Example example = new Example(null);
}

What is the meaning of polyfills in HTML5?

A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers, e.g., to support canvas (an HTML5 feature) in older browsers.

It's sort of an HTML5 technique, since it is used in conjunction with HTML5, but it's not part of HTML5, and you can have polyfills without having HTML5 (for example, to support CSS3 techniques you want).

Here's a good post:

http://remysharp.com/2010/10/08/what-is-a-polyfill/

Here's a comprehensive list of Polyfills and Shims:

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

Reading a file character by character in C

the file is being opened and not closed for each call to the function also

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

How can I catch a ctrl-c event?

signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

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

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}

How do I embed PHP code in JavaScript?

We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.

However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

Create an ArrayList of unique values

Just Override the boolean equals() method of custom object. Say you have an ArrayList with custom field f1, f2, ... override

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof CustomObject)) return false;

    CustomObject object = (CustomObject) o;

    if (!f1.equals(object.dob)) return false;
    if (!f2.equals(object.fullName)) return false;
    ...
    return true;
}

and check using ArrayList instance's contains() method. That's it.

fs.writeFile in a promise, asynchronous-synchronous stuff

Because fs.writefile is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:

return new Promise(function(resolve, reject) {
    fs.writeFile("<filename.type>", data, '<file-encoding>', function(err) {
        if (err) reject(err);
        else resolve(data);
    });
});

So in your code you would use it like so right after your call to .then():

 .then(function(results) {
    return new Promise(function(resolve, reject) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
               if (err) reject(err);
               else resolve(data);
            });
    });
  }).then(function(results) {
       console.log("results here: " + results)
  }).catch(function(err) {
       console.log("error here: " + err);
  });

Priority queue in .Net

Here is the another implementation from NGenerics team:

NGenerics PriorityQueue

Print time in a batch file (milliseconds)

%time% should work, provided enough time has elapsed between calls:

@echo OFF

@echo %time%
ping -n 1 -w 1 127.0.0.1 1>nul
@echo %time%

On my system I get the following output:

6:46:13.50
6:46:13.60

Get month and year from date cells Excel

You could right click on those cells, go to format, select custom, then type mm yyyy.

How to create an 2D ArrayList in java?

The best way is to use a List within a List:

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

What is a regular expression which will match a valid domain name without a subdomain?

^((localhost)|((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,253})$

Thank you @mkyong for the basis for my answer. I've modified it to support longer acceptable labels.

Also, "localhost" is technically a valid domain name. I will modify this answer to accommodate internationalized domain names.

I'm getting Key error in python

A KeyError generally means the key doesn't exist. So, are you sure the path key exists?

From the official python docs:

exception KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

For example:

>>> mydict = {'a':'1','b':'2'}
>>> mydict['a']
'1'
>>> mydict['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'
>>>

So, try to print the content of meta_entry and check whether path exists or not.

>>> mydict = {'a':'1','b':'2'}
>>> print mydict
{'a': '1', 'b': '2'}

Or, you can do:

>>> 'a' in mydict
True
>>> 'c' in mydict
False

What is the best IDE for C Development / Why use Emacs over an IDE?

I've moved from a terminal text-editor+make environment to Eclipse for most of my projects. Spanning from C and C++, to Java and Python to name few languages I am currently working with.

The reason was simply productivity. I could not afford spending time and effort on keeping all projects "in my head" as other things got more important.

There are benefits of using the "hardcore" approach (terminal) - such as that you have a much thinner layer between yourself and the code which allows you to be a bit more productive when you're all "inside" the project and everything is on the top of your head. But I don't think it is possible to defend that way of working just for it's own sake when your mind is needed elsewhere.

Usually when you work with command line tools you will frequently have to solve a lot of boilerplate problems that will keep you from being productive. You will need to know the tools in detail to fully leverage their potentials. Also maintaining a project will take a lot more effort. Refactoring will lead to updates in make-files, etc.

To summarize: If you only work on one or two projects, preferably full-time without too much distractions, "terminal based coding" can be more productive than a full blown IDE. However, if you need to spend your thinking energy on something more important an IDE is definitely the way to go in order to keep productivity.

Make your choice accordingly.

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

Get folder up one level

You can try

echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..'); 

How do I execute a PowerShell script automatically using Windows task scheduler?

Create the scheduled task and set the action to:

Program/Script: Powershell.exe

Arguments: -File "C:\Users\MyUser\Documents\ThisisMyFile.ps1"

How do I prompt for Yes/No/Cancel input in a Linux shell script?

The easiest way to achieve this with the least number of lines is as follows:

read -p "<Your Friendly Message here> : y/n/cancel" CONDITION;

if [ "$CONDITION" == "y" ]; then
   # do something here!
fi

The if is just an example: it is up to you how to handle this variable.

Convert a PHP object to an associative array

Here is some code:

function object_to_array($data) {
    if ((! is_array($data)) and (! is_object($data)))
        return 'xxx'; // $data;

    $result = array();

    $data = (array) $data;
    foreach ($data as $key => $value) {
        if (is_object($value))
            $value = (array) $value;
        if (is_array($value))
            $result[$key] = object_to_array($value);
        else
            $result[$key] = $value;
    }
    return $result;
}

How to convert string to Title Case in Python?

def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d

Declaring and initializing arrays in C

It is not possible to assign values to an array all at once after initialization. The best alternative would be to use a loop.

for(i=0;i<N;i++)
{
     array[i] = i;
}

You can hard code and assign values like --array[0] = 1 and so on.

Memcpy can also be used if you have the data stored in an array already.

Eclipse will not start and I haven't changed anything

Read my answer if recently you have been using a VPN connection.

Today I had the same exact issue and learned how to fix it without removing any plugins. So I thought maybe I would share my own experience.

My issue definitely had something to do with Spring Framework

I was using a VPN connection over my internet connection. Once I disconnected my VPN, everything instantly turned right.

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

The number of method references in a .dex file cannot exceed 64k API 17

add this to avoid multidex issue for react native or any android project

android {

defaultConfig {
    ...

    // Enabling multidex support.
    multiDexEnabled true
}

}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'  //with support libraries
  //implementation 'androidx.multidex:multidex:2.0.1'  //with androidx libraries

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

In Java, how do you determine if a thread is running?

Thought to write a code to demonstrate the isAlive() , getState() methods, this example monitors a thread still it terminates(dies).

package Threads;

import java.util.concurrent.TimeUnit;

public class ThreadRunning {


    static class MyRunnable implements Runnable {

        private void method1() {

            for(int i=0;i<3;i++){
                try{
                    TimeUnit.SECONDS.sleep(1);
                }catch(InterruptedException ex){}
                method2();
            }
            System.out.println("Existing Method1");
        }

        private void method2() {

            for(int i=0;i<2;i++){
                try{
                    TimeUnit.SECONDS.sleep(1);
                }catch(InterruptedException ex){}
                method3();
            }
            System.out.println("Existing Method2");
        }

        private void method3() {

            for(int i=0;i<1;i++){
                try{
                    TimeUnit.SECONDS.sleep(1);
                }catch(InterruptedException ex){}

            }
            System.out.println("Existing Method3");
        }

        public void run(){
            method1();
        }
    }


    public static void main(String[] args) {

        MyRunnable runMe=new MyRunnable();

        Thread aThread=new Thread(runMe,"Thread A");

        aThread.start();

        monitorThread(aThread);

    }

    public static void monitorThread(Thread monitorMe) {

        while(monitorMe.isAlive())
         {
         try{   
           StackTraceElement[] threadStacktrace=monitorMe.getStackTrace();

           System.out.println(monitorMe.getName() +" is Alive and it's state ="+monitorMe.getState()+" ||  Execution is in method : ("+threadStacktrace[0].getClassName()+"::"+threadStacktrace[0].getMethodName()+") @line"+threadStacktrace[0].getLineNumber());  

               TimeUnit.MILLISECONDS.sleep(700);
           }catch(Exception ex){}
    /* since threadStacktrace may be empty upon reference since Thread A may be terminated after the monitorMe.getStackTrace(); call*/
         }
        System.out.println(monitorMe.getName()+" is dead and its state ="+monitorMe.getState());
    }


}

React - Component Full Screen (with height 100%)

I had the same issue displaying my side navigation panel height to 100%.

My steps to fix it was to:

In the index.css file ------

.html {
   height: 100%;
}
.body {
   height:100%;
}

In the sidePanel.css (this was giving me issues):

.side-panel {
   height: 100%;
   position: fixed; <--- this is what made the difference and scaled to 100% correctly
}

Other attributes were taken out for clarity, but I think the issue lies with scaling the height to 100% in nested containers like how you are trying to scale height in your nested containers. The parent classes height will need to be applied the 100%. - What i'm curious about is why fixed: position corrects the scale and fails without it; this is something i'll learn eventually with some more practice.

I've been working with react for a week now and i'm a novice to web developing, but I wanted to share a fix that I discovered with scaling height to 100%; I hope this helps you or anyone who has a similar issue. Good luck!

Check if instance is of a type

The different answers here have two different meanings.

If you want to check whether an instance is of an exact type then

if (c.GetType() == typeof(TForm))

is the way to go.

If you want to know whether c is an instance of TForm or a subclass then use is/as:

if (c is TForm)

or

TForm form = c as TForm;
if (form != null)

It's worth being clear in your mind about which of these behaviour you actually want.

How do I find my host and username on mysql?

The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html

If MySql is running on the same computer as your webserver, you can just use "localhost" as the host

Linux command: How to 'find' only text files?

I do it this way: 1) since there're too many files (~30k) to search thru, I generate the text file list daily for use via crontab using below command:

find /to/src/folder -type f -exec file {} \; | grep text | cut -d: -f1 > ~/.src_list &

2) create a function in .bashrc:

findex() {
    cat ~/.src_list | xargs grep "$*" 2>/dev/null
}

Then I can use below command to do the search:

findex "needle text"

HTH:)

Swift add icon/image in UITextField

Swift 5

Similar to @Markus, but in Swift 5:

emailTextField.leftViewMode = UITextField.ViewMode.always
emailTextField.leftViewMode = .always

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Mounting multiple volumes on a docker container?

You can have Read only or Read and Write only on the volume

docker -v /on/my/host/1:/on/the/container/1:ro \

docker -v /on/my/host/2:/on/the/container/2:rw \

Spring Boot: How can I set the logging level with application.properties?

You can do that using your application.properties.

logging.level.=ERROR -> Sets the root logging level to error
...
logging.level.=DEBUG -> Sets the root logging level to DEBUG

logging.file=${java.io.tmpdir}/myapp.log -> Sets the absolute log file path to TMPDIR/myapp.log

A sane default set of application.properties regarding logging using profiles would be: application.properties:

spring.application.name=<your app name here>
logging.level.=ERROR
logging.file=${java.io.tmpdir}/${spring.application.name}.log

application-dev.properties:

logging.level.=DEBUG
logging.file=

When you develop inside your favourite IDE you just add a -Dspring.profiles.active=dev as VM argument to the run/debug configuration of your app.

This will give you error only logging in production and debug logging during development WITHOUT writing the output to a log file. This will improve the performance during development ( and save SSD drives some hours of operation ;) ).

Center image horizontally within a div

Put an equal pixel padding for left and right:

<div id="artiststhumbnail" style="padding-left:ypx;padding-right:ypx">

What's the difference between tilde(~) and caret(^) in package.json?

Not an answer, per se, but an observation that seems to have been overlooked.

The description for carat ranges:

see: https://github.com/npm/node-semver#caret-ranges-123-025-004

Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple.

Means that ^10.2.3 matches 10.2.3 <= v < 20.0.0

I don't think that's what they meant. Pulling in versions 11.x.x through 19.x.x will break your code.

I think they meant left most non-zero number field. There is nothing in SemVer that requires number-fields to be single-digit.

how do I use an enum value on a switch statement in C++

i had a similar issue using enum with switch cases later i resolved it on my own....below is the corrected code, perhaps this might help.

     //Menu Chooser Programe using enum
     #include<iostream>
     using namespace std;
     int main()
     {
        enum level{Novice=1, Easy, Medium, Hard};
        level diffLevel=Novice;
        int i;
        cout<<"\nenter a level: ";
        cin>>i;
        switch(i)
        {
        case Novice: cout<<"\nyou picked Novice\n"; break;
        case Easy: cout<<"\nyou picked Easy\n"; break;
        case Medium: cout<<"\nyou picked Medium\n"; break;
        case Hard: cout<<"\nyou picked Hard\n"; break;
        default: cout<<"\nwrong input!!!\n"; break;
        }
        return 0;
     }

Best method to download image from url in Android

you can use below function to download image from url.

private Bitmap getImage(String imageUrl, int desiredWidth, int desiredHeight)
    {   
           private Bitmap image = null;
           int inSampleSize = 0;


            BitmapFactory.Options options = new BitmapFactory.Options();

            options.inJustDecodeBounds = true;

            options.inSampleSize = inSampleSize;

            try
            {
                URL url = new URL(imageUrl);

                HttpURLConnection connection = (HttpURLConnection)url.openConnection();

                InputStream stream = connection.getInputStream();

                image = BitmapFactory.decodeStream(stream, null, options);

                int imageWidth = options.outWidth;

                int imageHeight = options.outHeight;

                if(imageWidth > desiredWidth || imageHeight > desiredHeight)
                {   
                    System.out.println("imageWidth:"+imageWidth+", imageHeight:"+imageHeight);

                    inSampleSize = inSampleSize + 2;

                    getImage(imageUrl);
                }
                else
                {   
                    options.inJustDecodeBounds = false;

                    connection = (HttpURLConnection)url.openConnection();

                    stream = connection.getInputStream();

                    image = BitmapFactory.decodeStream(stream, null, options);

                    return image;
                }
            }

            catch(Exception e)
            {
                Log.e("getImage", e.toString());
            }

        return image;
    }

See complete explanation here

JavaScript associative array to JSON

There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.

Add 'x' number of hours to date

I use following function to convert normal date-time value to mysql datetime format.

private function ampmtosql($ampmdate) {
            if($ampmdate == '')
                return '';
            $ampm = substr(trim(($ampmdate)), -2);
            $datetimesql = substr(trim(($ampmdate)), 0, -3);
            if ($ampm == 'pm') {
                $hours = substr(trim($datetimesql), -5, 2);
                if($hours != '12')
                    $datetimesql = date('Y-m-d H:i',strtotime('+12 hour',strtotime($datetimesql)));
            }
            elseif ($ampm == 'am') {
                $hours = substr(trim($datetimesql), -5, 2);
                if($hours == '12')
                    $datetimesql = date('Y-m-d H:i',strtotime('-12 hour',strtotime($datetimesql)));
            }
            return $datetimesql;
        }

It converts datetime values like,

2015-06-04 09:55 AM -> 2015-06-04 09:55
2015-06-04 03:55 PM -> 2015-06-04 15:55
2015-06-04 12:30 AM -> 2015-06-04 00:55

Hope this will help someone.

Determine number of pages in a PDF file

I have used pdflib for this.

    p = new pdflib();

    /* Open the input PDF */
    indoc = p.open_pdi_document("myTestFile.pdf", "");
    pageCount = (int) p.pcos_get_number(indoc, "length:pages");

Rails: Get Client IP address

Get client ip using command:

request.remote_ip

PostgreSQL DISTINCT ON with different ORDER BY

You can also done this by using group by clause

   SELECT purchases.address_id, purchases.* FROM "purchases"
    WHERE "purchases"."product_id" = 1 GROUP BY address_id,
purchases.purchased_at ORDER purchases.purchased_at DESC

Force the origin to start at 0

xlim and ylim don't cut it here. You need to use expand_limits, scale_x_continuous, and scale_y_continuous. Try:

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for

enter image description here

p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))

enter image description here

You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5 and y = 5.

PHP UML Generator

Well to be honest, first and foremost you shouldn't generate UML model from code, but code from UML model ;).

Even if you are in a rare situation, when you need to do this reverse engineering, it is generally suggested that you do it by hand or at least tidy-up the diagrams, as auto-generated UML has really poor visual (=information) value most of the time.

If you just need to generate the diagrams, it's probably a good thing to ask yourself why exactly? Who is the intended audience and what is the goal? What does the auto-generated diagram have to offer, what code doesn't?

Basicly I accept only one answer to that question. It just got too big and incomprehensible.

Which again is a reason to start with UML in the first place, as opposed to start coding ;) It's called analysis and it's on decline, because every second guy in business thinks it's a bit too expensive and not really necessary.

When do you use POST and when do you use GET?

There is nothing you can't do per-se. The point is that you're not supposed to modify the server state on an HTTP GET. HTTP proxies assume that since HTTP GET does not modify the state then whether a user invokes HTTP GET one time or 1000 times makes no difference. Using this information they assume it is safe to return a cached version of the first HTTP GET. If you break the HTTP specification you risk breaking HTTP client and proxies in the wild. Don't do it :)

How can we programmatically detect which iOS version is device running on?

[[UIDevice currentDevice] systemVersion];

or check the version like

You can get the below Macros from here.

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(IOS_VERSION_3_2_0))      
{

        UIImageView *background = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cs_lines_back.png"]] autorelease];
        theTableView.backgroundView = background;

}

Hope this helps

How do I check when a UITextField changes?

Swift 4

textField.addTarget(self, action: #selector(textIsChanging), for: UIControlEvents.editingChanged)

@objc func textIsChanging(_ textField:UITextField) {

 print ("TextField is changing")

}

If you want to make a change once the user has typed in completely (It will be called once user dismiss keyboard or press enter).

textField.addTarget(self, action: #selector(textDidChange), for: UIControlEvents.editingDidEnd)

 @objc func textDidChange(_ textField:UITextField) {

       print ("TextField did changed") 
 }

How to convert JSONObjects to JSONArray?

Even shorter and with json-functions:

JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());

Setting DEBUG = False causes 500 Error

I ran into this issue. Turns out I was including in the template, using the static template tag, a file that did not exist anymore. A look in the logs showed me the problem.

I guess this is just one of many possible reasons for this kind of error.

Moral of the story: always log errors and always check logs.

How to prevent XSS with HTML/PHP?

The best way to protect your input it's use htmlentities function. Example:

htmlentities($target, ENT_QUOTES, 'UTF-8');

You can get more information here.

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

The named ones are all raster graphics, but beside that don't forget the more and more important vectorgraphics. There are compressed and uncompressed types (in a more or less way), but they're all lossless. Most important are:

setting y-axis limit in matplotlib

One thing you can do is to set your axis range by yourself by using matplotlib.pyplot.axis.

matplotlib.pyplot.axis

from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])

0,10 is for x axis range. 0,20 is for y axis range.

or you can also use matplotlib.pyplot.xlim or matplotlib.pyplot.ylim

matplotlib.pyplot.ylim

plt.ylim(-2, 2)
plt.xlim(0,10)

CSS vertical-align: text-bottom;

Sometimes you can play with padding and margin top, add line-height, etc.

See fiddle.

Style and text forked from @aspirinemaga

.parent
{
    width:300px;
    line-height:30px;
    border:1px solid red;
    padding-top:20px;
}

How do I reference a cell range from one worksheet to another using excel formulas?

If these worksheets reside in the same workbook, a simple solution would be to name the range, and have the formula refer to the named range. To name a range, select it, right click, and provide it with a meaningful name with Workbook scope.

For example =Sheet1!$A$1:$F$1 could be named: theNamedRange. Then your formula on Sheet2! could refer to it in your formula like this: =SUM(theNamedRange).

Incidentally, it is not clear from your question how you meant to use the range. If you put what you had in a formula (e.g., =SUM(Sheet1!A1:F1)) it will work, you simply need to insert that range argument in a formula. Excel does not resolve the range reference without a related formula because it does not know what you want to do with it.

Of the two methods, I find the named range convention is easier to work with.

How can I access Google Sheet spreadsheets only with Javascript?

I have created a simple javascript library that retrieves google spreadsheet data (if they are published) via the JSON api:

https://github.com/mikeymckay/google-spreadsheet-javascript

You can see it in action here:

http://mikeymckay.github.com/google-spreadsheet-javascript/sample.html

Sequence contains more than one element

SingleOrDefault method throws an Exception if there is more than one element in the sequence.

Apparently, your query in GetCustomer is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.

onChange and onSelect in DropDownList

hmm. why don't you use onClick()

<select id="mySelect" onChange="enable();">
   <option onClick="disable();">No</option>
   <option onClick="enable();">Yes</option>
</select>

How to run a cron job on every Monday, Wednesday and Friday?

This is how I configure it on my server:

0  19  *  *  1,3,5 root bash /home/divo/data/support_files/support_files_inc_backup.sh

The above command will run my script at 19:00 on Monday, Wednesday, and Friday.

NB: For cron entries for day of the week (dow)

0 = Sunday
1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday

Chrome disable SSL checking for sites?

In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.

I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?

Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,

There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.

The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).

Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

Python dictionary get multiple values

If you have pandas installed you can turn it into a series with the keys as the index. So something like

import pandas as pd

s = pd.Series(my_dict)

s[['key1', 'key3', 'key2']]

How can I create an editable combo box in HTML/Javascript?

Here is a script for that: Demo, Source

Or another one which works slightly differently: link removed (site no longer exists)

node.js: cannot find module 'request'

if some module you cant find, try with Static URI, for example:

var Mustache = require("/media/fabio/Datos/Express/2_required_a_module/node_modules/mustache/mustache.js");

This example, run on Ubuntu Gnome 16.04 of 64 bits, node -v: v4.2.6, npm: 3.5.2 Refer to: Blog of Ben Nadel

Converting Select results into Insert script - SQL Server

I found this SMSMS Boost addon, which is free and does exactly this among other things. You can right click on the results and select Script data as.

Example of Mockito's argumentCaptor

The steps in order to make a full check are:

Prepare the captor :

ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);

verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.

verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());

Get the argument passed to collaborator

SomeArgumentClass someArgument = messageCaptor.getValue();

someArgument can be used for assertions

Index of Currently Selected Row in DataGridView

Try it:

int rc=dgvDataRc.CurrentCell.RowIndex;** //for find the row index number
MessageBox.Show("Current Row Index is = " + rc.ToString());

I hope it will help you.

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I got this error too.

The problem turned out to be simply that I had to manually create the full directory structure for the file locations of the MDF & LDF files.

Shame on SQL-Server for not properly reporting the missing directory!

How to check heap usage of a running JVM from the command line?

All procedure at once. Based on @Till Schäfer answer.

In KB...

jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10]); printf("%.2f KB\n",sum)}'

In MB...

jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10])/1024; printf("%.2f MB\n",sum)}'

"Awk sum" reference:

 a[1] - S0C
 a[2] - S1C
 a[3] - S0U
 a[4] - S1U
 a[5] - EC
 a[6] - EU
 a[7] - OC
 a[8] - OU
 a[9] - PC
a[10] - PU
a[11] - YGC
a[12] - YGCT
a[13] - FGC
a[14] - FGCT
a[15] - GCT

Used for "Awk sum":

a[3] -- (S0U) Survivor space 0 utilization (KB).
a[4] -- (S1U) Survivor space 1 utilization (KB).
a[6] -- (EU) Eden space utilization (KB).
a[8] -- (OU) Old space utilization (KB).
a[10] - (PU) Permanent space utilization (KB).

[Ref.: https://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html ]

Thanks!

NOTE: Works to OpenJDK!

FURTHER QUESTION: Wrong information?

If you check memory usage with the ps command, you will see that the java process consumes much more...

ps -eo size,pid,user,command --sort -size | egrep -i "*/bin/java *" | egrep -v grep | awk '{ hr=$1/1024 ; printf("%.2f MB ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | cut -d "" -f2 | cut -d "-" -f1

UPDATE (2021-02-16):

According to the reference below (and @Till Schäfer comment) "ps can show total reserved memory from OS" (adapted) and "jstat can show used space of heap and stack" (adapted). So, we see a difference between what is pointed out by the ps command and the jstat command.

According to our understanding, the most "realistic" information would be the ps output since we will have an effective response of how much of the system's memory is compromised. The command jstat serves for a more detailed analysis regarding the java performance in the consumption of reserved memory from OS.

[Ref.: http://www.openkb.info/2014/06/how-to-check-java-memory-usage.html ]

Reference excel worksheet by name?

The best way is to create a variable of type Worksheet, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet.

This will help you avoid bugs that will eventually show up when your program grows in size.

For example something like Range("A1:C10").Sort Key1:=Range("A2") is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")... and find out that it still doesn't work.

Here is the correct way:

Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

Encountered this issue in chrome. Resolved by cleaning up related cookies. Note that you don't have to cleanup ALL your cookies.

TCP: can two different sockets share a port?

A connected socket is assigned to a new (dedicated) port

That's a common intuition, but it's incorrect. A connected socket is not assigned to a new/dedicated port. The only actual constraint that the TCP stack must satisfy is that the tuple of (local_address, local_port, remote_address, remote_port) must be unique for each socket connection. Thus the server can have many TCP sockets using the same local port, as long as each of the sockets on the port is connected to a different remote location.

See the "Socket Pair" paragraph at: http://books.google.com/books?id=ptSC4LpwGA0C&lpg=PA52&dq=socket%20pair%20tuple&pg=PA52#v=onepage&q=socket%20pair%20tuple&f=false

Unable to allocate array with shape and data type

I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.

With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.

You can check which version you have by entering the interpreter. I, with a 64-bit version, now have: Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)], where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".

Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.

Sources :

How to select records from last 24 hours using SQL?

Hello i now it past a lot of time from the original post but i got a similar problem and i want to share.

I got a datetime field with this format YYYY-MM-DD hh:mm:ss, and i want to access a whole day, so here is my solution.

The function DATE(), in MySQL: Extract the date part of a date or datetime expression.

SELECT * FROM `your_table` WHERE DATE(`your_datatime_field`)='2017-10-09'

with this i get all the row register in this day.

I hope its help anyone.

How to disable input conditionally in vue.js

This will also work

<input type="text" id="name" class="form-control" name="name"  v-model="form.name" :disabled="!validated">

How to set an image's width and height without stretching it?

If using flexbox is a valid option for you (don't need to suport old browsers), check my other answer here (which is possibly a duplicate of this one):

Basically you'd need to wrap your img tag in a div and your css would look like this:

.img__container {
    display: flex;
    padding: 15px 12px;
    box-sizing: border-box;
    width: 400px; height: 200px;

    img {
        margin: auto;
        max-width: 100%;
        max-height: 100%;
    }
}

How to show all privileges from a user in oracle?

You can use below code to get all the privileges list from all users.

select * from dba_sys_privs 

How to autowire RestTemplate using annotations

@Autowired
private RestOperations restTemplate;

You can only autowire interfaces with implementations.

How to change 1 char in the string?

Strings are immutable, meaning you can't change a character. Instead, you create new strings.

What you are asking can be done several ways. The most appropriate solution will vary depending on the nature of the changes you are making to the original string. Are you changing only one character? Do you need to insert/delete/append?

Here are a couple ways to create a new string from an existing string, but having a different first character:

str = 'M' + str.Remove(0, 1);

str = 'M' + str.Substring(1);

Above, the new string is assigned to the original variable, str.

I'd like to add that the answers from others demonstrating StringBuilder are also very appropriate. I wouldn't instantiate a StringBuilder to change one character, but if many changes are needed StringBuilder is a better solution than my examples which create a temporary new string in the process. StringBuilder provides a mutable object that allows many changes and/or append operations. Once you are done making changes, an immutable string is created from the StringBuilder with the .ToString() method. You can continue to make changes on the StringBuilder object and create more new strings, as needed, using .ToString().

Android - How to get application name? (Not package name)

If you need only the application name, not the package name, then just write this code.

 String app_name = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();

How do I add a resources folder to my Java project in Eclipse

To answer your question posted in the title of this topic...

Step 1--> Right Click on Java Project, Select the option "Properties" Step 1--> Right Click on Java Project, Select the option "Properties"

Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder" Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"

Step 3--> Click the option "Create New Folder..." available at the bottom of the window Click the option "Create New Folder..." available at the bottom of the window

Step 4--> Enter the name of the new folder as "resources" and then click "Finish" Enter the name of the new folder as "resources" and then click "Finish"

Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"

Final Step --> Now you should be able to see the new folder "resources" under your java project
Now you should be able to see the new folder "resources" under your java project

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

how to fix java.lang.IndexOutOfBoundsException

lstpp is empty. You cant access the first element of an empty list.

In general, you can check if size > index.

In your case, you need to check if lstpp is empty. (you can use !lstpp.isEmpty())

mysqldump Error 1045 Access denied despite correct passwords etc

I had the problem that there were views that had a bad "DEFINER", which is the user that defined the view. The DEFINER used in the view had been removed some time ago as being "root from some random workstation".

Check whether there might be a problem by running:

USE information_schema; 
SELECT DEFINER, SECURITY_TYPE FROM views;

I modified the DEFINER (actually, set the DEFINER to root@localhost and the SQL SECURITY value to INVOKER so the view is executed with the permissions of the invoking user instead of the defining user, which actually makes more sense) using ALTER VIEW.

This is tricky as you have to construct the appropriate ALTER VIEW statement from information_schema.views, so check:

PHP convert XML to JSON

if you XML is a soap file, you can use this:

$xmlStr = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xmlStr);
$xml = new SimpleXMLElement($xmlStr);
return json_encode($xml);

How to process a file in PowerShell line-by-line as a stream

If you want to use straight PowerShell check out the below code.

$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
    Write-Host $line
}

Static vs class functions/variables in Swift classes?

Testing in Swift 4 shows performance difference in simulator. I made a class with "class func" and struct with "static func" and ran them in test.

static func is:

  • 20% faster without compiler optimization
  • 38% faster when optimization -whole-module-optimization is enabled.

However, running the same code on iPhone 7 under iOS 10.3 shows exactly the same performance.

Here is sample project in Swift 4 for Xcode 9 if you like to test yourself https://github.com/protyagov/StructVsClassPerformance

How to check the extension of a filename in a bash script?

I guess that '$PATH_TO_SOMEWHERE'is something like '<directory>/*'.

In this case, I would change the code to:

find <directory> -maxdepth 1 -type d -exec ... \;
find <directory> -maxdepth 1 -type f -name "*.txt" -exec ... \;

If you want to do something more complicated with the directory and text file names, you could:

find <directory> -maxdepth 1 -type d | while read dir; do echo $dir; ...; done
find <directory> -maxdepth 1 -type f -name "*.txt" | while read txtfile; do echo $txtfile; ...; done

If you have spaces in your file names, you could:

find <directory> -maxdepth 1 -type d | xargs ...
find <directory> -maxdepth 1 -type f -name "*.txt" | xargs ...

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

Try to disable SELinux by this command /usr/sbin/setenforce 0. In my case it solved the problem.

Android: how to create Switch case from this?

You can do this:

@Override
protected Dialog onCreateDialog(int id) {
    String messageDialog;
    String valueOK;
    String valueCancel;
    String titleDialog;
    switch (id) {

    case id:
        titleDialog = itemTitle;
        messageDialog = itemDescription
        valueOK = "OK";            
        return new AlertDialog.Builder(HomeView.this).setTitle(titleDialog).setPositiveButton(valueOK, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Log.d(this.getClass().getName(), "AlertItem");
            }
        }).setMessage(messageDialog).create(); 

and then call to

showDialog(numbreOfItem);

How to check for null in a single statement in scala?

Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach is the preferred way of doing it, I like to use an AnyRef pimp that allows me to write:

getObject ifNotNull ( QueueManager.add(_) )

I find it reads better.

And, in a more general way, I sometimes write

val returnVal = getObject ifNotNull { obj =>
  returnSomethingFrom(obj)
} otherwise {
  returnSomethingElse
}

... replacing ifNotNull with ifSome if I'm dealing with an Option. I find it clearer than first wrapping in an option and then pattern-matching it.

(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0/Otherwise1 classes.)

Open file dialog box in JavaScript

I dont't know why nobody has pointed this out but here's is a way of doing it without any Javascript and it's also compatible with any browser.


EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.


<label>
  Open file dialog
  <input type="file" style="position: fixed; top: -100em">
</label>

If you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">

multiple conditions for JavaScript .includes() method

How about ['hello', 'hi', 'howdy'].includes(str)?

Creating a LinkedList class from scratch

How have I created a linkedlist like this. How does this work? This is all a linked list is. An item with a link to the next item in the list. As long as you keep a reference to the item at the beginning of the list, you can traverse the whole thing using each subsequent reference to the next value.

To append, all you need to do is find the end of the list, and make the next item the value you want appended, so if this has non-null next, you would have to call append on the next item until you find the end of the list.

this.next.Append(word);

Creating PHP class instance with a string

Lets say ClassOne is defined as:

public class ClassOne
{
    protected $arg1;
    protected $arg2;

    //Contructor
    public function __construct($arg1, $arg2)
    {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
    }

    public function echoArgOne
    {
        echo $this->arg1;
    }

}

Using PHP Reflection;

$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);

Create a new Instance:

$instance = $class->newInstanceArgs(["Banana", "Apple")]);

Call a method:

$instance->echoArgOne();
//prints "Banana"

Use a variable as a method:

$method = "echoArgOne";
$instance->$method();

//prints "Banana"

Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)

For..In loops in JavaScript - key value pairs

You can use a 'for in' loop for this:

for (var key in bar) {
     var value = bar[key];
}

How to remove trailing whitespaces with sed?

To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):

sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"

How to remove foreign key constraint in sql server?

ALTER TABLE table
DROP FOREIGN KEY fk_key

EDIT: didn't notice you were using sql-server, my bad

ALTER TABLE table
DROP CONSTRAINT fk_key

npm - how to show the latest version of a package

The npm view <pkg> version prints the last version by release date. That might very well be an hotfix release for a older stable branch at times.

The solution is to list all versions and fetch the last one by version number

$ npm view <pkg> versions --json | jq -r '.[-1]'

Or with awk instead of jq:

$ npm view <pkg> --json  | awk '/"$/{print gensub("[ \"]", "", "G")}'

Declaring an unsigned int in Java

There are good answers here, but I don’t see any demonstrations of bitwise operations. Like Visser (the currently accepted answer) says, Java signs integers by default (Java 8 has unsigned integers, but I have never used them). Without further ado, let‘s do it...

RFC 868 Example

What happens if you need to write an unsigned integer to IO? Practical example is when you want to output the time according to RFC 868. This requires a 32-bit, big-endian, unsigned integer that encodes the number of seconds since 12:00 A.M. January 1, 1900. How would you encode this?

Make your own unsigned 32-bit integer like this:

Declare a byte array of 4 bytes (32 bits)

Byte my32BitUnsignedInteger[] = new Byte[4] // represents the time (s)

This initializes the array, see Are byte arrays initialised to zero in Java?. Now you have to fill each byte in the array with information in the big-endian order (or little-endian if you want to wreck havoc). Assuming you have a long containing the time (long integers are 64 bits long in Java) called secondsSince1900 (Which only utilizes the first 32 bits worth, and you‘ve handled the fact that Date references 12:00 A.M. January 1, 1970), then you can use the logical AND to extract bits from it and shift those bits into positions (digits) that will not be ignored when coersed into a Byte, and in big-endian order.

my32BitUnsignedInteger[0] = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24); // first byte of array contains highest significant bits, then shift these extracted FF bits to first two positions in preparation for coersion to Byte (which only adopts the first 8 bits)
my32BitUnsignedInteger[1] = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
my32BitUnsignedInteger[2] = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
my32BitUnsignedInteger[3] = (byte) ((secondsSince1900 & 0x00000000000000FFL); // no shift needed

Our my32BitUnsignedInteger is now equivalent to an unsigned 32-bit, big-endian integer that adheres to the RCF 868 standard. Yes, the long datatype is signed, but we ignored that fact, because we assumed that the secondsSince1900 only used the lower 32 bits). Because of coersing the long into a byte, all bits higher than 2^7 (first two digits in hex) will be ignored.

Source referenced: Java Network Programming, 4th Edition.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.

Thanks

How to test Spring Data repositories?

tl;dr

To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.

Details

We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.

  • We create and cache CriteriaQuery instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.
  • We verify manually defined queries by asking the EntityManager to create a Query instance for those (which effectively triggers query syntax validation).
  • We inspect the Metamodel for meta-data about the domain types handled to prepare is-new checks etc.

All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).

If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:

  • entity mappings
  • query semantics (syntax is verified on each bootstrap attempt anyway).

Integration tests

This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.

Testing custom implementations

Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager -> CriteriaBuilder, CriteriaQuery etc.) so that you end up with mocks returning mocks and so on.

Can someone explain Microsoft Unity?

Unity is just an IoC "container". Google StructureMap and try it out instead. A bit easier to grok, I think, when the IoC stuff is new to you.

Basically, if you understand IoC then you understand that what you're doing is inverting the control for when an object gets created.

Without IoC:

public class MyClass
{
   IMyService _myService; 

   public MyClass()
   {
      _myService = new SomeConcreteService();    
   }
}

With IoC container:

public class MyClass
{
   IMyService _myService; 

   public MyClass(IMyService myService)
   {
      _myService = myService;    
   }
}

Without IoC, your class that relies on the IMyService has to new-up a concrete version of the service to use. And that is bad for a number of reasons (you've coupled your class to a specific concrete version of the IMyService, you can't unit test it easily, you can't change it easily, etc.)

With an IoC container you "configure" the container to resolve those dependencies for you. So with a constructor-based injection scheme, you just pass the interface to the IMyService dependency into the constructor. When you create the MyClass with your container, your container will resolve the IMyService dependency for you.

Using StructureMap, configuring the container looks like this:

StructureMapConfiguration.ForRequestedType<MyClass>().TheDefaultIsConcreteType<MyClass>();
StructureMapConfiguration.ForRequestedType<IMyService>().TheDefaultIsConcreteType<SomeConcreteService>();

So what you've done is told the container, "When someone requests the IMyService, give them a copy of the SomeConcreteService." And you've also specified that when someone asks for a MyClass, they get a concrete MyClass.

That's all an IoC container really does. They can do more, but that's the thrust of it - they resolve dependencies for you, so you don't have to (and you don't have to use the "new" keyword throughout your code).

Final step: when you create your MyClass, you would do this:

var myClass = ObjectFactory.GetInstance<MyClass>();

Hope that helps. Feel free to e-mail me.

MySQL skip first 10 results

OFFSET is what you are looking for.

SELECT * FROM table LIMIT 10 OFFSET 10

How to stop VBA code running?

Add another button called "CancelButton" that sets a flag, and then check for that flag.

If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

I had the exact same problem while trying to setup a Gitlab pipeline executed by a Docker runner installed on a Raspberry Pi 4

Using nload to follow bandwidth usage within Docker runner container while pipeline was cloning the repo i saw the network usage dropped down to a few bytes per seconds..

After a some deeper investigations i figured out that the Raspberry temperature was too high and the network card start to dysfunction above 50° Celsius.

Adding a fan to my Raspberry solved the issue.

Pyspark: display a spark data frame in a table format

Let's say we have the following Spark DataFrame:

df = sqlContext.createDataFrame(
    [
        (1, "Mark", "Brown"), 
        (2, "Tom", "Anderson"), 
        (3, "Joshua", "Peterson")
    ], 
    ('id', 'firstName', 'lastName')
)

There are typically three different ways you can use to print the content of the dataframe:

Print Spark DataFrame

The most common way is to use show() function:

>>> df.show()
+---+---------+--------+
| id|firstName|lastName|
+---+---------+--------+
|  1|     Mark|   Brown|
|  2|      Tom|Anderson|
|  3|   Joshua|Peterson|
+---+---------+--------+

Print Spark DataFrame vertically

Say that you have a fairly large number of columns and your dataframe doesn't fit in the screen. You can print the rows vertically - For example, the following command will print the top two rows, vertically, without any truncation.

>>> df.show(n=2, truncate=False, vertical=True)
-RECORD 0-------------
 id        | 1        
 firstName | Mark     
 lastName  | Brown    
-RECORD 1-------------
 id        | 2        
 firstName | Tom      
 lastName  | Anderson 
only showing top 2 rows

Convert to Pandas and print Pandas DataFrame

Alternatively, you can convert your Spark DataFrame into a Pandas DataFrame using .toPandas() and finally print() it.

>>> df_pd = df.toPandas()
>>> print(df_pd)
   id firstName  lastName
0   1      Mark     Brown
1   2       Tom  Anderson
2   3    Joshua  Peterson

Note that this is not recommended when you have to deal with fairly large dataframes, as Pandas needs to load all the data into memory. If this is the case, the following configuration will help when converting a large spark dataframe to a pandas one:

spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")

For more details you can refer to my blog post Speeding up the conversion between PySpark and Pandas DataFrames

C#: Assign same value to multiple variables in single statement

It's as simple as:

num1 = num2 = 5;

When using an object property instead of variable, it is interesting to know that the get accessor of the intermediate value is not called. Only the set accessor is invoked for all property accessed in the assignation sequence.

Take for example a class that write to the console everytime the get and set accessor are invoked.

static void Main(string[] args)
{
    var accessorSource = new AccessorTest(5);
    var accessor1 = new AccessorTest();
    var accessor2 = new AccessorTest();

    accessor1.Value = accessor2.Value = accessorSource.Value;

    Console.ReadLine();
}

public class AccessorTest
{
    public AccessorTest(int value = default(int))
    {
        _Value = value;
    }

    private int _Value;

    public int Value
    {
        get
        {
            Console.WriteLine("AccessorTest.Value.get {0}", _Value);
            return _Value;
        }
        set
        {
            Console.WriteLine("AccessorTest.Value.set {0}", value);
            _Value = value;
        }
    }
}

This will output

AccessorTest.Value.get 5
AccessorTest.Value.set 5
AccessorTest.Value.set 5

Meaning that the compiler will assign the value to all properties and it will not re-read the value every time it is assigned.

How to write both h1 and h2 in the same line?

<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />

Hope this helps!

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

You can't remove hidden without also removing system.

You want:

cd mydir
attrib -H -S /D /S

That will remove the hidden and system attributes from all the files/folders inside of your current directory.

How to Copy Text to Clip Board in Android?

For copy any text in Android:

            TextView text = findViewById(R.id.text_id);
            ImageView icons = findViewById(R.id.copy_icon);

            icons.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText("text whatever you want", text.getText().toString());
                    clipboardManager.setPrimaryClip(clipData);

                    Toast.makeText(context, "Text Copied", Toast.LENGTH_SHORT).show();
                }
            });

SQL Server - Convert date field to UTC

The following should work as it calculates difference between DATE and UTCDATE for the server you are running and uses that offset to calculate the UTC equivalent of any date you pass to it. In my example, I am trying to convert UTC equivalent for '1-nov-2012 06:00' in Adelaide, Australia where UTC offset is -630 minutes, which when added to any date will result in UTC equivalent of any local date.

select DATEADD(MINUTE, DATEDIFF(MINUTE, GETDATE(), GETUTCDATE()), '1-nov-2012 06:00')

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

nginx error connect to php5-fpm.sock failed (13: Permission denied)

After upgrading from Ubuntu 14.04 lts to Ubuntu 16.04 lts I found a yet another reason for this error that I haven't seen before.

During the upgrading process I had somehow lost my php5-fpm executable altogether. All the config files were intact and it took me a while to realize that service php5-fpm start didn't really start a process, as it did not show any errors.

My moment of awakening was when I noticed that there were no socket file in /var/run/php5-fpm.sock, as there should be, nor did netstat -an show processes listening on the port that I tried as an alternative while trying to solve this problem. Since the file /usr/sbin/php5-fpm was also non-existing, I was finally on the right track.

In order to solve this problem I upgraded php from version 5.5 to 7.0. apt-get install php-fpm did the trick as a side effect. After that and installing other necessary packages everything was back to normal.


This upgrading solution may have problems of its own, however. Since php has evolved quite a bit, it's possible that the software will break in unimaginable ways. So, even though I did go down that path, you may want to keep the version you're fond of just for a while longer.

Luckily, there seems to be a neat way for that, as described on The Customize Windows site:

add-apt-repository ppa:ondrej/php
apt-get purge php5-common
apt-get update
apt-get install php5.6

Neater solution as it might be, I didn't try that. I expect the next couple of days will tell me whether I should have.

How do I stop a program when an exception is raised in Python?

As far as I know, if an exception is not caught by your script, it will be interrupted.

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

How to access session variables from any class in ASP.NET?

(Updated for completeness)
You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...


I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

Bootstrap alert in a fixed floating div at the top of page

I think the issue is that you need to wrap your div in a container and/or row.

This should achieve a similar look as what you are looking for:

<div class="container">
    <div class="row" id="error-container">
         <div class="span12">  
             <div class="alert alert-error">
                <button type="button" class="close" data-dismiss="alert">×</button>
                 test error message
             </div>
         </div>
    </div>
</div>

CSS:

#error-container {
     margin-top:10px;
     position: fixed;
}

Bootply demo

Adding a new array element to a JSON object

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

Stylesheet not updating

I had a similar problem, made all the more infuriating by simply being very SLOW to update. I couldn't get my changes to take effect while working on the site to save my life (trying all manner of clearing my browser cache and cookies), but if I came back to the site later in the day or opened another browser, there they were.

I also solved the problem by disabling the Supercacher software at my host's cpanel (Siteground). You can also use the "flush" button for individual directories to test if that's it before disabling.

Qt. get part of QString

Use the left function:

QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "

Also have a look at mid() if you want more control.