Programs & Examples On #Svd

Singular Value Decomposition (SVD) is a factorization of a real or complex matrix, with many useful applications in signal processing and statistics.

Google Chrome forcing download of "f.txt" file

FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

The count method of NSArray returns an NSUInteger, and on the 64-bit OS X platform

  • NSUInteger is defined as unsigned long, and
  • unsigned long is a 64-bit unsigned integer.
  • int is a 32-bit integer.

So int is a "smaller" datatype than NSUInteger, therefore the compiler warning.

See also NSUInteger in the "Foundation Data Types Reference":

When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.

To fix that compiler warning, you can either declare the local count variable as

NSUInteger count;

or (if you are sure that your array will never contain more than 2^31-1 elements!), add an explicit cast:

int count = (int)[myColors count];

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

Import CSV file into SQL Server

Here's how I would solve it:

  1. Just Save your CSV File as a XLS Sheet in excel(By Doing so, you wouldn't have to worry about delimitiers. Excel's spreadsheet format will be read as a table and imported directly into a SQL Table)

  2. Import the File Using SSIS

  3. Write a Custom Script in the import manager to omit/modify the data you're looking for.(Or run a master script to scrutinize the data you're looking to remove)

Good Luck.

How to remove first and last character of a string?

It's easy, You need to find index of [ and ] then substring. (Here [ is always at start and ] is at end) ,

String loginToken = "[wdsd34svdf]";
System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) );

How to retrieve an Oracle directory path?

select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

how to stop a running script in Matlab

MATLAB doesn't respond to Ctrl-C while executing a mex implemented function such as svd. Also when MATLAB is allocating big chunk of memory it doesn't respond. A good practice is to always run your functions for small amount of data, and when all test passes run it for actual scale. When time is an issue, you would want to analyze how much time each segment of code runs as well as their rough time complexity.

How to export specific request to file using postman?

To do that you need to leverage the "Collections" feature of Postman. This link could help you: https://learning.getpostman.com/docs/postman/collections/creating_collections/

Here is the way to do it:

  • Create a collection (within tab "Collections")
  • Execute your request
  • Add the request to a collection
  • Share your collection as a file

Clearing state es6 React

This is how I handle it:

class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this._initState = {
        a: 1,
        b: 2
      }
    this.state = this._initState;
  }

  _resetState(){
     this.setState(this._initState);
   }
}

Update: Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.

Endless loop in C/C++

In an ultimate act of boredom, I actually wrote a few versions of these loops and compiled it with GCC on my mac mini.

the while(1){} and for(;;) {} produced same assembly results while the do{} while(1); produced similar but a different assembly code

heres the one for while/for loop

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    movl    $0, -4(%rbp)
LBB0_1:                                 ## =>This Inner Loop Header: Depth=1
    jmp LBB0_1
    .cfi_endproc

and the do while loop

        .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    movl    $0, -4(%rbp)
LBB0_1:                                 ## =>This Inner Loop Header: Depth=1
    jmp LBB0_2
LBB0_2:                                 ##   in Loop: Header=BB0_1 Depth=1
    movb    $1, %al
    testb   $1, %al
    jne LBB0_1
    jmp LBB0_3
LBB0_3:
    movl    $0, %eax
    popq    %rbp
    ret
    .cfi_endproc

Laravel Eloquent - Get one Row

Try with it

$color = \App\Color::take(1)->first();

git remote add with other SSH port

Best answer doesn't work for me. I needed ssh:// from the beggining.

# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git

Equal height rows in CSS Grid Layout

Short Answer

If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:

  • Set the container to grid-auto-rows: 1fr

How it works

Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow property in flexbox.

If you set all rows in a grid container to 1fr, let's say like this:

grid-auto-rows: 1fr;

... then all rows will be equal height.

It doesn't really make sense off-the-bat because fr is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.

Except, buried deep in the grid spec is this little nugget:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.

The height of each row is determined by the tallest (max-content) grid item.

The maximum height of those rows becomes the length of 1fr.

That's how 1fr creates equal height rows in a grid container.


Why flexbox isn't an option

As noted in the question, equal height rows are not possible with flexbox.

Flex items can be equal height on the same row, but not across multiple rows.

This behavior is defined in the flexbox spec:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

Java System.out.print formatting

Are you sure that you want "055" as opposed to "55"? Some programs interpret a leading zero as meaning octal, so that it would read 055 as (decimal) 45 instead of (decimal) 55.

That should just mean dropping the '0' (zero-fill) flag.

e.g., change System.out.printf("%03d ", x); to the simpler System.out.printf("%3d ", x);

Oracle 12c Installation failed to access the temporary location

Install it from CMD using the command

setup.exe -ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"

Reference

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

Data binding in React

To be short, in React, there's no two-way data-binding.

So when you want to implement that feature, try define a state, and write like this, listening events, update the state, and React renders for you:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    return (
      <input type="text" value={this.state.value} onChange={this.handleChange} />
    );
  }
}

Details here https://facebook.github.io/react/docs/forms.html

UPDATE 2020

Note:

LinkedStateMixin is deprecated as of React v15. The recommendation is to explicitly set the value and change handler, instead of using LinkedStateMixin.

above update from React official site . Use below code if you are running under v15 of React else don't.

There are actually people wanting to write with two-way binding, but React does not work in that way. If you do want to write like that, you have to use an addon for React, like this:

var WithLink = React.createClass({
  mixins: [LinkedStateMixin],
  getInitialState: function() {
    return {message: 'Hello!'};
  },
  render: function() {
    return <input type="text" valueLink={this.linkState('message')} />;
  }
});

Details here https://facebook.github.io/react/docs/two-way-binding-helpers.html

For refs, it's just a solution that allow developers to reach the DOM in methods of a component, see here https://facebook.github.io/react/docs/refs-and-the-dom.html

Presto SQL - Converting a date string to date format

If your string is in ISO 8601 format, you can also use from_iso8601_timestamp

How to get a parent element to appear above child

Fortunately a solution exists. You must add a wrapper for parent and change z-index of this wrapper for example 10, and set z-index for child to -1:

_x000D_
_x000D_
.parent {_x000D_
    position: relative;_x000D_
    width: 750px;_x000D_
    height: 7150px;_x000D_
    background: red;_x000D_
    border: solid 1px #000;_x000D_
    z-index: initial;_x000D_
}_x000D_
_x000D_
.child {_x000D_
    position: relative;_x000D_
    background-color: blue;_x000D_
    z-index: -1;_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
    position: relative;_x000D_
    background: green;_x000D_
    z-index: 10;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="parent">parent parent_x000D_
        <div class="child">child child child</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Random number from a range in a Bash Script

You can get the random number through urandom

head -200 /dev/urandom | cksum

Output:

3310670062 52870

To retrieve the one part of the above number.

head -200 /dev/urandom | cksum | cut -f1 -d " "

Then the output is

3310670062

To meet your requirement,

head -200 /dev/urandom |cksum | cut -f1 -d " " | awk '{print $1%63000+2001}'

React / JSX Dynamic Component Name

I used a bit different Approach, as we always know our actual components so i thought to apply switch case. Also total no of component were around 7-8 in my case.

getSubComponent(name) {
    let customProps = {
       "prop1" :"",
       "prop2":"",
       "prop3":"",
       "prop4":""
    }

    switch (name) {
      case "Component1": return <Component1 {...this.props} {...customProps} />
      case "Component2": return <Component2 {...this.props} {...customProps} />
      case "component3": return <component3 {...this.props} {...customProps} />

    }
  }

selecting rows with id from another table

SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'

Bootstrap 3 and Youtube in Modal

Ok. I found a solution.

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                    </button>
                    <h3 class="modal-title" id="modal-login-label">Capital Get It</h3>
                    <p>Log in:</p>
                </div>

                <div class="modal-body">

                    <h4>Youtube stuff</h4>



             <iframe src="//www.youtube.com/embed/lAU0yCDKWb4" allowfullscreen="" frameborder="0" height="315" width="100%"></iframe>       
             </div>


                </div>

            </div>
        </div>
    </div>

How to make the tab character 4 spaces instead of 8 spaces in nano?

Command-line flag

From man nano:

-T cols (--tabsize=cols)
    Set the size (width) of a tab to cols columns.
    The value of cols must be greater than 0. The default value is 8.
-E (--tabstospaces)
    Convert typed tabs to spaces.

For example, to set the tab size to 4, replace tabs with spaces, and edit the file "foo.txt", you would run the command:

nano -ET4 foo.txt

Config file

From man nanorc:

set tabsize n
    Use a tab size of n columns. The value of n must be greater than 0.
    The default value is 8.
set/unset tabstospaces
    Convert typed tabs to spaces.

Edit your ~/.nanorc file (create it if it does not exist), and add those commands to it. For example:

set tabsize 4
set tabstospaces

Nano will use these settings by default whenever it is launched, but command-line flags will override them.

Object comparison in JavaScript

Certainly not the only way - you could prototype a method (against Object here but I certainly wouldn't suggest using Object for live code) to replicate C#/Java style comparison methods.

Edit, since a general example seems to be expected:

Object.prototype.equals = function(x)
{
    for(p in this)
    {
        switch(typeof(this[p]))
        {
            case 'object':
                if (!this[p].equals(x[p])) { return false }; break;
            case 'function':
                if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
            default:
                if (this[p] != x[p]) { return false; }
        }
    }

    for(p in x)
    {
        if(typeof(this[p])=='undefined') {return false;}
    }

    return true;
}

Note that testing methods with toString() is absolutely not good enough but a method which would be acceptable is very hard because of the problem of whitespace having meaning or not, never mind synonym methods and methods producing the same result with different implementations. And the problems of prototyping against Object in general.

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Text that shows an underline on hover

You just need to specify text-decoration: underline; with pseudo-class :hover.

HTML

<span class="underline-on-hover">Hello world</span>

CSS

.underline-on-hover:hover {
    text-decoration: underline;
}

I have whipped up a working Code Pen Demo.

How to check for valid email address?

The Python standard library comes with an e-mail parsing function: email.utils.parseaddr().

It returns a two-tuple containing the real name and the actual address parts of the e-mail:

>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')

>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')

>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')

And if the parsing is unsuccessful, it returns a two-tuple of empty strings:

>>> parseaddr('[invalid!email]')
('', '')

An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:

>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')

>>> parseaddr('invalid-email')
('', 'invalid-email')

So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.

However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:

>>> '@' in parseaddr("invalid-email")[1]
False

If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX servers:

>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NXDOMAIN

You can catch both NoAnswer and NXDOMAIN by catching dns.exception.DNSException.

And Yes, foo@[email protected] is a syntactically valid address. Only the last @ should be considered for detecting where the domain part starts.

The correct way to read a data file into an array

There is the easiest method, using File::Slurp module:

use File::Slurp;
my @lines = read_file("filename", chomp => 1); # will chomp() each line

If you need some validation for each line you can use grep in front of read_file.

For example, filter lines which contain only integers:

my @lines = grep { /^\d+$/ } read_file("filename", chomp => 1);

How can I use onItemSelected in Android?

If you don't want to implement the listener, you can set it up like this directly where you want it (call on your spinner after your adapter has been set):

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        Toast.makeText(parent.getContext(), "Spinner item 1!", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(parent.getContext(), "Spinner item 2!", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(parent.getContext(), "Spinner item 3!", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

How to remove the default arrow icon from a dropdown list (select element)?

Works for all browsers and all versions:

JS

jQuery(document).ready(function () {    
    var widthOfSelect = $("#first").width();
    widthOfSelect = widthOfSelect - 13;
    //alert(widthOfSelect);
    jQuery('#first').wrap("<div id='sss' style='width: "+widthOfSelect+"px; overflow: hidden; border-right: #000 1px solid;' width=20></div>");
});

HTML

<select class="first" id="first">
  <option>option1</option>
  <option>option2</option>
  <option>option3</option>
</select>

How to prepend a string to a column value in MySQL?

Many string update functions in MySQL seems to be working like this: If one argument is null, then concatenation or other functions return null too. So, to update a field with null value, first set it to a non-null value, such as ''

For example:

update table set field='' where field is null;
update table set field=concat(field,' append');

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

SQL Logic Operator Precedence: And and Or

  1. Arithmetic operators
  2. Concatenation operator
  3. Comparison conditions
  4. IS [NOT] NULL, LIKE, [NOT] IN
  5. [NOT] BETWEEN
  6. Not equal to
  7. NOT logical condition
  8. AND logical condition
  9. OR logical condition

You can use parentheses to override rules of precedence.

node.js: read a text file into an array. (Each line an item in the array.)

js:

var array = fs.readFileSync('file.txt', 'utf8').split('\n');

ts:

var array = fs.readFileSync('file.txt', 'utf8').toString().split('\n');

JavaScript calculate the day of the year (1 - 366)

Well, if I understand you correctly, you want 366 on a leap year, 365 otherwise, right? A year is a leap year if it's evenly divisible by 4 but not by 100 unless it's also divisible by 400:

function daysInYear(year) {
    if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
        // Leap year
        return 366;
    } else {
        // Not a leap year
        return 365;
    }
}

Edit after update:

In that case, I don't think there's a built-in method; you'll need to do this:

function daysInFebruary(year) {
    if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
        // Leap year
        return 29;
    } else {
        // Not a leap year
        return 28;
    }
}

function dateToDay(date) {
    var feb = daysInFebruary(date.getFullYear());
    var aggregateMonths = [0, // January
                           31, // February
                           31 + feb, // March
                           31 + feb + 31, // April
                           31 + feb + 31 + 30, // May
                           31 + feb + 31 + 30 + 31, // June
                           31 + feb + 31 + 30 + 31 + 30, // July
                           31 + feb + 31 + 30 + 31 + 30 + 31, // August
                           31 + feb + 31 + 30 + 31 + 30 + 31 + 31, // September
                           31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30, // October
                           31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, // November
                           31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, // December
                         ];
    return aggregateMonths[date.getMonth()] + date.getDate();
}

(Yes, I actually did that without copying or pasting. If there's an easy way I'll be mad)

Launch Android application without main Activity and start Service on launching application

You said you didn't want to use a translucent Activity, but that seems to be the best way to do this:

  1. In your Manifest, set the Activity theme to Theme.Translucent.NoTitleBar.
  2. Don't bother with a layout for your Activity, and don't call setContentView().
  3. In your Activity's onCreate(), start your Service with startService().
  4. Exit the Activity with finish() once you've started the Service.

In other words, your Activity doesn't have to be visible; it can simply make sure your Service is running and then exit, which sounds like what you want.

I would highly recommend showing at least a Toast notification indicating to the user that you are launching the Service, or that it is already running. It is very bad user experience to have a launcher icon that appears to do nothing when you press it.

Unity Scripts edited in Visual studio don't provide autocomplete

This page helped me fix the issue.

Fix for Unity disconnected from Visual Studio

enter image description here

In the Unity Editor, select the Edit > Preferences menu..

Select the External Tools tab on the left.

Select unity version from drop down list on the right

Click regenerate Files

You Done

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

How to ping multiple servers and return IP address and Hostnames using batch script?

Try this

$servers = Get-Content test.txt

$reg=""

foreach ($server in $servers) 

{

$reg=$reg+$server+"`t"+([System.Net.Dns]::GetHostAddresses($server) | foreach {echo $_.IPAddressToString})+"`n"

 }
$reg >reg.csv

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

Have you tried using cat to combine the files?

cat 10MB.pdf 10MB.pdf > 20MB.pdf

That should result in a 20MB file.

MySQL date format DD/MM/YYYY select query?

Use:

SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y") AS 'NAME'
SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y %H:%i:%s") AS 'NAME'

Reference: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

Length of a JavaScript object

_x000D_
_x000D_
   let myobject= {}
    let isempty =  !!Object.values(myobject);
    console.log(isempty);
_x000D_
_x000D_
_x000D_

How to connect to MongoDB in Windows?

For this error, if you are using windows 7 or windows server 2008 R2, the problem could be that you have to install a microsoft hotfix.

Refer to this link: https://support.microsoft.com/en-us/kb/2731284

PHP Warning: Invalid argument supplied for foreach()

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}

cancelling a handler.postdelayed process

In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use

handler.removeCallbacksAndMessages(null);

As per documentation,

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

How do I upload a file with the JS fetch API?

The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using

data.append('fileData', {
  uri : pickerResponse.uri,
  type: pickerResponse.type,
  name: pickerResponse.fileName
 });

Fetch seems to recognize that format and send the file where the uri is pointing.

New to MongoDB Can not run command mongo

create folder structure data/db in the working directory and then starting up mongodb using "mongod --dbpath data/db" works just fine

How do you get/set media volume (not ringtone volume) in Android?

The following code will set the media stream volume to max:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
    audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
    AudioManager.FLAG_SHOW_UI);

Check whether a variable is a string in Ruby

You can do:

foo.instance_of?(String)

And the more general:

foo.kind_of?(String)

How to grep recursively, but only in files with certain extensions?

Should write "-exec grep " for each "-o -name "

find . -name '*.h' -exec grep -Hn "CP_Image" {} \; -o -name '*.cpp' -exec grep -Hn "CP_Image" {} \;

Or group them by ( )

find . \( -name '*.h' -o -name '*.cpp' \) -exec grep -Hn "CP_Image" {} \;

option '-Hn' show the file name and line.

When should we implement Serializable interface?

The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:

There is no reason to use Java serialization in any new system you write

Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.


Why Java serialization is flawed

Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.

  • It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
  • It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
  • Testing interoperability of different versions of the serialized form is very difficult.
  • Handling of immutable objects is troublesome.

What to do instead

Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.

How to get the text of the selected value of a dropdown list?

$("#select_id").find("option:selected").text();

It is helpful if your control is on Server side. In .NET it looks like:

$('#<%= dropdownID.ClientID %>').find("option:selected").text();

Simultaneously merge multiple data.frames in a list

Here is a generic wrapper which can be used to convert a binary function to multi-parameters function. The benefit of this solution is that it is very generic and can be applied to any binary functions. You just need to do it once and then you can apply it any where.

To demo the idea, I use simple recursion to implement. It can be of course implemented with more elegant way that benefits from R's good support for functional paradigm.

fold_left <- function(f) {
return(function(...) {
    args <- list(...)
    return(function(...){
    iter <- function(result,rest) {
        if (length(rest) == 0) {
            return(result)
        } else {
            return(iter(f(result, rest[[1]], ...), rest[-1]))
        }
    }
    return(iter(args[[1]], args[-1]))
    })
})}

Then you can simply wrap any binary functions with it and call with positional parameters (usually data.frames) in the first parentheses and named parameters in the second parentheses (such as by = or suffix =). If no named parameters, leave second parentheses empty.

merge_all <- fold_left(merge)
merge_all(df1, df2, df3, df4, df5)(by.x = c("var1", "var2"), by.y = c("var1", "var2"))

left_join_all <- fold_left(left_join)
left_join_all(df1, df2, df3, df4, df5)(c("var1", "var2"))
left_join_all(df1, df2, df3, df4, df5)()

Array definition in XML?

Once I've seen such an interesting construction:

<Ids xmlns:id="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <id:int>1787</id:int>
</Ids>

Generate ER Diagram from existing MySQL database, created for CakePHP

Use MySQL Workbench. create SQL dump file of your database

Follow below steps:

  1. Click File->Import->Reverse Engineer MySQL Create Script
  2. Click Browse and select your SQL create script.
  3. Make Sure "Place Imported Objects on a diagram" is checked.
  4. Click Execute Button.
  5. You are done.

Capitalize the first letter of string in AngularJs

I like the answer from @TrampGuy

CSS is always (well, not always) a better choice, so: text-transform: capitalize; is certainly the way to go.

But what if your content is all uppercase to begin with? If you try text-transform: capitalize; on content like "FOO BAR" you'll still get "FOO BAR" in your display. To get around that issue you could put the text-transform: capitalize; in your css, but also lowercase your string, so:

<ul>
  <li class="capitalize">{{ foo.awesome_property | lowercase }}</li>
</ul>

where we are using @TrampGuy's capitalize class:

.capitalize {
  text-transform: capitalize;
}

So, pretending that foo.awsome_property would normally print "FOO BAR", it will now print the desired "Foo Bar".

How to add a new line in textarea element?

You might want to use \n instead of /n.

Remove last specific character in a string c#

Try string.Remove();

string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);

How to call a function in shell Scripting?

Summary:

  • Define functions before using them.
  • Once defined, treat them as commands.

Consider this script, called funcdemo:

#!/bin/bash

[ $# = 0 ] && exhort "write nastygram"

exhort(){
    echo "Please, please do not forget to $*"
}

[ $# != 0 ] && exhort "write begging letter"

In use:

$ funcdemo
./funcdemo: line 3: exhort: command not found
$ funcdemo 1
Please, please do not forget to write begging letter
$

Note the potential for a missing function to lie undiscovered for a long time (think 'by a customer at the most critical wrong moment'). It only matters whether the function exists when it is executed, the same as it only matters whether any other command exists when you try to execute it. Indeed, until it goes to execute the command, the shell neither knows nor cares whether it is an external command or a function.

How to calculate DATE Difference in PostgreSQL?

Your calculation is correct for DATE types, but if your values are timestamps, you should probably use EXTRACT (or DATE_PART) to be sure to get only the difference in full days;

EXTRACT(DAY FROM MAX(joindate)-MIN(joindate)) AS DateDifference

An SQLfiddle to test with. Note the timestamp difference being 1 second less than 2 full days.

Turning multiple lines into one comma separated line

xargs -a your_file | sed 's/ /,/g'

This is a shorter way.

How do I escape spaces in path for scp copy in Linux?

works

scp localhost:"f/a\ b\ c" .

scp localhost:'f/a\ b\ c' .

does not work

scp localhost:'f/a b c' .

The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails

To see this in action, start a shell with the -vx options ie bash -vx and it will display the interpolated version of the command as it runs it.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

In case anyone in the future had this problem, I'm using a Mac and just had to install the Command Line Tools using 'xcode-select --install'

How can I express that two values are not equal to eachother?

Just put a '!' in front of the boolean expression

Create an application setup in visual studio 2013

Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.

visual-studio-installer-projects-extension

LaTeX table too wide. How to make it fit?

You can use these options as well, either use \footnotesize or \tiny. This would really help in fitting big tables.

\begin{table}[htbp]
\footnotesize
\caption{Information on making the table size small}
\label{table:table1}
\begin{tabular}{ll}
    \toprule
    S.No       & HMD           \\
    \midrule
    1          & HTC Vive \\
    2          & HTC Vive Pro   \\
    \bottomrule
\end{tabular}
\end{table}

Why doesn't the Scanner class have a nextChar method?

The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. Source

You can use (char) System.in.read();.

sh: 0: getcwd() failed: No such file or directory on cited drive

This error is usually caused by running a command from a directory that no longer exist.

Try changing your directory and re-run the command.

Where does Android app package gets installed on phone

The package it-self is located under /data/app/com.company.appname-xxx.apk.

/data/app/com.company.appname is only a directory created to store files like native libs, cache, ecc...

You can retrieve the package installation path with the Context.getPackageCodePath() function call.

Spring MVC 4: "application/json" Content Type is not being set correctly

When I upgraded to Spring 4 I needed to update the jackson dependencies as follows:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.1</version>
    </dependency>        

Getting absolute URLs using ASP.NET Core

You can get the url like this:

Request.Headers["Referer"]

Explanation

The Request.UrlReferer will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).

As for using Request.ServerVariables, per MSDN:

Request.ServerVariables Collection

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Request.Headers Property

Gets a collection of HTTP headers.

I guess I don't understand why you would prefer the Request.ServerVariables over Request.Headers, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.

So the best solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.

AngularJS dynamic routing

As of AngularJS 1.1.3, you can now do exactly what you want using the new catch-all parameter.

https://github.com/angular/angular.js/commit/7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5

From the commit:

This allows routeProvider to accept parameters that matches substrings even when they contain slashes if they are prefixed with an asterisk instead of a colon. For example, routes like edit/color/:color/largecode/*largecode will match with something like this http://appdomain.com/edit/color/brown/largecode/code/with/slashs.

I have tested it out myself (using 1.1.5) and it works great. Just keep in mind that each new URL will reload your controller, so to keep any kind of state, you may need to use a custom service.

Give all permissions to a user on a PostgreSQL database

All commands must be executed while connected to the right database in the right database cluster. Make sure of it.

The user needs access to the database, obviously:

GRANT CONNECT ON DATABASE my_db TO my_user;

And (at least) the USAGE privilege on the schema:

GRANT USAGE ON SCHEMA public TO my_user;

Or grant USAGE on all custom schemas:

DO
$$
BEGIN
   -- RAISE NOTICE '%', (  -- use instead of EXECUTE to see generated commands
   EXECUTE (
   SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
   FROM   pg_namespace
   WHERE  nspname <> 'information_schema' -- exclude information schema and ...
   AND    nspname NOT LIKE 'pg\_%'        -- ... system schemas
   );
END
$$;

Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;

For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).

There are some other objects, the manual for GRANT has the complete list as of Postgres 12:

privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)

But the rest is rarely needed. More details:

Consider upgrading to a current version.

Have Excel formulas that return 0, make the result blank

You can create your own user defined functions in a module within Excel such as (from memory, so may need some debugging, and the syntax may vary among Excel versions as well):

Public Function ZeroToBlank (x As Integer) As String
    If x = 0 then
        ZeroToBlank = ""
    Else
        ZeroToBlank = CStr(x)
    End If
End Function

You can then simply insert =ZeroToBlank (Index (a,b,c)) into your cell.

There's a nice tutorial on just this subject here.

The basic steps are:

  • Open the VB editor within Excel by using Tools -> Macro -> Visual Basic Editor.
  • Create a new module with Insert -> Module.
  • Enter the above function into that module.
  • In the cells where you want to call that function, enter the formula
         =ZeroToBlank (<<whatever>>)
    where <<whatever>> is the value you wish to use blank for if it's zero.
  • Note that this function returns a string so, if you want it to look like a number, you may want to right justify the cells.

Note that there may be minor variations depending on which version of Excel you have. My version of Excel is 2002 which admittedly is pretty old, but it still does everything I need of it.

How to launch an EXE from Web page (asp.net)

if the applications are C#, you can use ClickOnce deployment, which is a good option if you can't guarentee the user will have the app, however you'll have to re-build the apps with deployment options and grab some boilerplate code from each project.

You can also use Javascript.

Or you can register an application to handle a new web protocol you can define. This could also be an "app selection" protocol, so each time an app is clicked it would link to a page on your new protocol, all handling of this protocol is then passed to your "selection app" which uses arguments to find and launch an app on the clients PC.

HTH

Center image in table td in CSS

This fixed issues for me:

<style>
.super-centered {
    position:absolute; 
    width:100%;
    height:100%;
    text-align:center; 
    vertical-align:middle;
    z-index: 9999;
}
</style>

<table class="super-centered"><tr><td style="width:100%;height:100%;" align="center"     valign="middle" > 
<img alt="Loading ..." src="/ALHTheme/themes/html/ALHTheme/images/loading.gif">
</td></tr></table>

Error CS2001: Source file '.cs' could not be found

They are likely still referenced by the project file. Make sure they are deleted using the Solution Explorer in Visual Studio - it should show them as being missing (with an exclamation mark).

subtract time from date - moment js

I use moment.js http://momentjs.com/

var start = moment(StartTimeString).toDate().getTime();
var end = moment(EndTimeString).toDate().getTime();
var timespan = end - start;
var duration = moment(timespan);
var output = duration.format("YYYY-MM-DDTHH:mm:ss");

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

executing shell command in background from script

For example you have a start program named run.sh to start it working at background do the following command line. ./run.sh &>/dev/null &

How to iterate over each string in a list of strings and operate on it's elements

c=0
words = ['challa','reddy','challa']

for idx, word in enumerate(words):
    if idx==0:
        firstword=word
        print(firstword)
    elif idx == len(words)-1:
        lastword=word
        print(lastword)
        if firstword==lastword:
            c=c+1
            print(c)

compare two files in UNIX

There are 3 basic commands to compare files in unix:

  1. cmp : This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response. syntax:$cmp file1 file2.

  2. comm : This command is used to find out the records available in one but not in another

  3. diff

Detect browser or tab closing

For similar tasks, you can use sessionStorage to store data locally until the browser tab is closed.

The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).(W3Schools)

This is my pen.

<div id="Notice">
    <span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
    $("#Notice").click(function() {
     //set sessionStorage on click
        sessionStorage.setItem("dismissNotice", "Hello");
        $("#Notice").remove();
    });
    if (sessionStorage.getItem("dismissNotice"))
    //When sessionStorage is set Do stuff...
        $("#Notice").remove();
</script>

grep --ignore-case --only

I'd suggest that the -i means it does match "ABC", but the difference is in the output. -i doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.

The output of echo "ABC" | grep -i abc is ABC, the -o shows output matching "abc" so nothing shows:

Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

That true,Mustafa....its working..its point to two layout

  1. setContentView(R.layout.your_layout)
  2. v23(your_layout).

You should take Button both activity layout...
solve this problem successfully

Can we locate a user via user's phone number in Android?

Yess, possible with conditions:

If you have your app installed in the user phone and a server app communicating with this app, and there at last one of location service providers activated in the user phone, and some horrible android permissions!

In most of android phones there 3 location providers that can give exact location (GPS_PROVIDER 1m) or estimated (NETWORK_PROVIDER around 2-20m) and PASSIVE_PROVIDER (more in LocationManager official documentation).

1* App sends SMS to user's phone

Yess, can be server app or you create an android app if you want something automated, so you can do it manually by sending SMS from your default SMS app! I use Kannel: Open Source WAP and SMS Gateway and here (lot of APIs to send SMS )

2* App receives SMS at user's phone from the SMS sender

Yess, you can get all received SMS, and you can filter them by sender phone number! and do some actions when your specified sms received, basic tuto here (i do some actions according to the content of my SMS)

3* App gets location coordinates of the user's phone

Yess, you can get actual user coordinates easily if one of location providers is activated, so you can get last known location when the user have activated one of location providers, if those disabled or the phone don't have GPS hardware you can use Open Cell Id api to get the nearest cell coordinates(10m-10Km) or Loc8 api but those not available in all around the world, and some apps use IP location apis to get the country, city and province, here the simplest way to get current user location.

4* App sends location coordinates to the SMS sender via SMS

Yess, you can get sender phone number and send user location, immediately when SMS received or at specified times in the day.

(Those 4 yesses for you :) )

Viber and other apps that access to users locations, identify there users by there phone numbers by obligating them to send SMS to the server app to create an account and activate the free service (Ex:VOIP) , and lunch a service that can:

  • Listen for location changes (GPS, Network or Cell Id)
  • Send user location periodically(Ex: each 2 hours) or when user position changed!
  • Stock user locations in file and create a map based on daily locations
  • Receive SMS and update user location
  • Receive server app commend and update user location
  • Send events when user go inside or outside of a defined circle
  • Listen for what user say and record it or open live voip call :s
  • Maybe anything you think or u want to do :) !

And your application users must accept all of that when installing it, of corse i don't gonna install apps like this because i read permissions before installing :) and permissions maybe something like that:

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
<uses-permission android:name="android.permission.INTERNET" />
<-- and more if you wanna more -->

The final user will accept for something like that (those permissions of an android app u asked about):

This app has access to these permissions:

Your accounts -create accounts and set passwords -find accounts on the device -add or remove accounts -use accounts on the device -read Google service configuration

Your location -approximate location (network-based) -precise location (GPS and network-based)

Your messages -receive text messages (SMS) -send SMS messages -edit your text messages (SMS or MMS) -read your text messages (SMS or MMS)

Network communication -receive data from Internet -full network access -view Wi-Fi connections -view network connections -change network connectivity

Phone calls -read phone status and identity -directly call phone numbers

Storage -modify or delete the contents of your USB storage

Your applications information -retrieve running apps -close other apps -run at startup

Bluetooth -pair with Bluetooth devices -access Bluetooth settings

Camera -take pictures and videos

Other Application UI -draw over other apps

Microphone -record audio

Lock screen -disable your screen lock

Your social information -read your contacts -modify your contacts -read call log -write call log -read your social stream -write to your social stream

Development tools -read sensitive log data

System tools -modify system settings -send sticky broadcast -test access to protected storage

Affects battery -control vibration -prevent device from sleeping

Audio settings -change your audio settings

Sync Settings -read sync settings -toggle sync on and off -read sync statistics

Wallpaper -set wallpaper

Check if Cookie Exists

Sometimes you still need to know if Cookie exists in Response. Then you can check if cookie key exists:

HttpContext.Current.Response.Cookies.AllKeys.Contains("myCookie")

More info can be found here.

In my case I had to modify Response Cookie in Application_EndRequest method in Global.asax. If Cookie doesn't exist I don't touch it:

string name = "myCookie";
HttpContext context = ((HttpApplication)sender).Context;
HttpCookie cookie = null;

if (context.Response.Cookies.AllKeys.Contains(name))
{
    cookie = context.Response.Cookies[name];
}

if (cookie != null)
{
    // update response cookie
}

How to log PostgreSQL queries?

There is an extension in postgresql for this. It's name is "pg_stat_statements". https://www.postgresql.org/docs/9.4/pgstatstatements.html

Basically you have to change postgresql.conf file a little bit:

shared_preload_libraries= 'pg_stat_statements'
pg_stat_statements.track = 'all'

Then you have to log in DB and run this command:

create extension pg_stat_statements;

It will create new view with name "pg_stat_statements". In this view you can see all the executed queries.

Configure active profile in SpringBoot via Maven

I would like to run an automation test in different environments.
So I add this to command maven command:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"

Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

How can I slice an ArrayList out of an ArrayList in Java?

In Java, it is good practice to use interface types rather than concrete classes in APIs.

Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

This is what your code should look like:

List input = new ArrayList(...);

public void doSomething(List input) {
   List inputA = input.subList(0, input.size()/2);
   ...
}

this.doSomething(input);

Your proposed "solution" to the problem was/is this:

new ArrayList(input.subList(0, input.size()/2))

That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.


If you are constrained by APIs that you cannot change, such that you have to declare inputA as an ArrayList, you might be able to implement a custom subclass of ArrayList in which the subList method returns a subclass of ArrayList. However:

  1. It would be a lot of work to design, implement and test.
  2. You have now added significant new class to your code base, possibly with dependencies on undocumented aspects (and therefore "subject to change") aspects of the ArrayList class.
  3. You would need to change relevant places in your codebase where you are creating ArrayList instances to create instances of your subclass instead.

The "copy the array" solution is more practical ... bearing in mind that these are not true slices.

Can't push to remote branch, cannot be resolved to branch

Git will let you checkout the current branch with a different casing, and it will fail to find a ref on the remote.

Just found out the hard way.

Is it possible to specify the schema when connecting to postgres with JDBC?

As of version 9.4, you can use the currentSchema parameter in your connection string.

For example:

jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema

Is there a MessageBox equivalent in WPF?

WPF contains the following MessageBox:

if (MessageBox.Show("Do you want to Save?", "Confirm", 
    MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{

}

Executing Shell Scripts from the OS X Dock?

You could create a Automator workflow with a single step - "Run Shell Script"

Then File > Save As, and change the File Format to "Application". When you open the application, it will run the Shell Script step, executing the command, exiting after it completes.

The benefit to this is it's really simple to do, and you can very easily get user input (say, selecting a bunch of files), then pass it to the input of the shell script (either to stdin, or as arguments).

(Automator is in your /Applications folder!)

Example workflow

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

C++ alignment when printing cout <<

Another way to make column aligned is as follows:

using namespace std;

cout.width(20); cout << left << "Artist";
cout.width(20); cout << left << "Title";
cout.width(10); cout << left << "Price";
...
cout.width(20); cout << left << artist;
cout.width(20); cout << left << title;
cout.width(10); cout << left << price;

We should estimate maximum length of values for each column. In this case, values of "Artist" column should not exceed 20 characters and so on.

Best way to split string into lines

Slightly twisted, but an iterator block to do it:

public static IEnumerable<string> Lines(this string Text)
{
    int cIndex = 0;
    int nIndex;
    while ((nIndex = Text.IndexOf(Environment.NewLine, cIndex + 1)) != -1)
    {
        int sIndex = (cIndex == 0 ? 0 : cIndex + 1);
        yield return Text.Substring(sIndex, nIndex - sIndex);
        cIndex = nIndex;
    }
    yield return Text.Substring(cIndex + 1);
}

You can then call:

var result = input.Lines().ToArray();

Open terminal here in Mac OS finder

There is an updated version of the very nice and slim Open Terminal Here posted by vgm64 and d0k. The change was made by james david low. He published the new version on his site. Just download OpenTerminalHere.zip, extract it, move the bundle to your Library/Scripts folder and drag it from there to your Finder toolbar.

What is special about it is that it always opens a new tab if a Terminal.app window is already open. Very useful! I also noted that the style of the button of the application better fits the Snow Leopard Finder.app style than cdto posted by redacted did.

Best practices to test protected methods with PHPUnit

You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:

class Foo {
  protected function stuff() {
    // secret stuff, you want to test
  }
}

class SubFoo extends Foo {
  public function exposedStuff() {
    return $this->stuff();
  }
}

Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.

How to timeout a thread

Assuming the thread code is out of your control:

From the Java documentation mentioned above:

What if a thread doesn't respond to Thread.interrupt?

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.

Bottom Line:

Make sure all threads can be interrupted, or else you need specific knowledge of the thread - like having a flag to set. Maybe you can require that the task be given to you along with the code needed to stop it - define an interface with a stop() method. You can also warn when you failed to stop a task.

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

you don't - not like this. give an id to your tag , lets say it looks like this now :

<h3 id="myHeader"></h3>

then set the value like that :

myHeader.innerText = "public offers";

how to make UITextView height dynamic according to text length?

Followed by DeyaEldeen's answer.
In my case. I grow the textview height automatically by adding

swift 3

textView.translatesAutoresizingMaskIntoConstraints = false textView.isScrollEnabled = false

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

Facebook Javascript SDK Problem: "FB is not defined"

Try to load your scripts in Head section. Moreover, it will be better if you define your scripts under some call like: document.ready, if you defined these scripts in body section

Why can I not create a wheel in python?

Install the wheel package first:

pip install wheel

The documentation isn't overly clear on this, but "the wheel project provides a bdist_wheel command for setuptools" actually means "the wheel package...".

Erasing elements from a vector

Use the remove/erase idiom:

std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());

What happens is that remove compacts the elements that differ from the value to be removed (number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements (whose value is unspecified).

DateTime "null" value

If you're using .NET 2.0 (or later) you can use the nullable type:

DateTime? dt = null;

or

Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

And you can check the value with:

if (dt.HasValue)
{
  // Do something with dt.Value
}

Or you can use it like:

DateTime dt2 = dt ?? DateTime.MinValue;

You can read more here:
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

Rebasing remote branches in Git

You can disable the check (if you're really sure you know what you're doing) by using the --force option to git push.

How to round down to nearest integer in MySQL?

SELECT FLOOR(12345.7344);

Read more here.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

Apache POI error loading XSSFWorkbook class

commons-collections4-x.x.jar definitely solve this problem but Apache has removed the Interface ListValuedMap from commons-Collections4-4.0.jar so use updated version 4.1 it has the required classes and Interfaces.

Refer here if you want to read Excel (2003 or 2007+) using java code.

http://www.codejava.net/coding/how-to-read-excel-files-in-java-using-apache-poi

Format specifier %02x

You are actually getting the correct value out.

The way your x86 (compatible) processor stores data like this, is in Little Endian order, meaning that, the MSB is last in your output.

So, given your output:

10101010

the last two hex values 10 are the Most Significant Byte (2 hex digits = 1 byte = 8 bits (for (possibly unnecessary) clarification).

So, by reversing the memory storage order of the bytes, your value is actually: 01010101.

Hope that clears it up!

How to use GROUP BY to concatenate strings in SQL Server?

SQL Server 2005 and later allow you to create your own custom aggregate functions, including for things like concatenation- see the sample at the bottom of the linked article.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

IP to Location using Javascript

You can submit the IP you receive to an online geolocation service, such as http://www.geoplugin.net/json.gp?ip=<your ip here>&jsoncallback=<suitable javascript function in your source>, then including the source it returns which will run the function you specify in jsoncallback with the geolocation information.

Alternatively, you may want to look into HTML5's geolocation features -- you can see a demo of it in action here. The advantage of this is that you do not need to make requests to foreign servers, but it may not work on browsers that do not support HTML5.

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

Main Class:

public class AndroidLocationActivity extends Activity {

Button btnGPSShowLocation;
Button btnNWShowLocation;

AppLocationService appLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    appLocationService = new AppLocationService(
            AndroidLocationActivity.this);

    btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location gpsLocation = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);

            if (gpsLocation != null) {
                double latitude = gpsLocation.getLatitude();
                double longitude = gpsLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (GPS): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();
            } else {
                showSettingsAlert("GPS");
            }

        }
    });

    btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
    btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location nwLocation = appLocationService
                    .getLocation(LocationManager.NETWORK_PROVIDER);

            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (NW): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();

            } else {
                showSettingsAlert("NETWORK");
            }

        }
    });

}

public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            AndroidLocationActivity.this);

    alertDialog.setTitle(provider + " SETTINGS");

    alertDialog.setMessage(provider
            + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    AndroidLocationActivity.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

}

}

Next Class:

public class AppLocationService extends Service implements LocationListener {

protected LocationManager locationManager;
Location location;

private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

public AppLocationService(Context context) {
    locationManager = (LocationManager) context
            .getSystemService(LOCATION_SERVICE);
}

public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider,
                MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            return location;
        }
    }
    return null;
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

Don't forget to add in your manifest.

<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />

How to Change Font Size in drawString Java

Font myFont = new Font ("Courier New", 1, 17);

The 17 represents the font size. Once you have that, you can put:

g.setFont (myFont);
g.drawString ("Hello World", 10, 10);

How to recover Git objects damaged by hard disk failure?

Git checkout can actually pick out individual files from a revision. Just give it the commit hash and the file name. More detailed info here.

I guess the easiest way to fix this safely is to revert to the newest uncommited backup and then selectively pick out uncorrupted files from newer commits. Good luck!

How to display pandas DataFrame of floats using a format string for columns?

summary:


    df = pd.DataFrame({'money': [100.456, 200.789], 'share': ['100,000', '200,000']})
    print(df)
    print(df.to_string(formatters={'money': '${:,.2f}'.format}))
    for col_name in ('share',):
        df[col_name] = df[col_name].map(lambda p: int(p.replace(',', '')))
    print(df)
    """
        money    share
    0  100.456  100,000
    1  200.789  200,000

        money    share
    0 $100.46  100,000
    1 $200.79  200,000

         money   share
    0  100.456  100000
    1  200.789  200000
    """

How should I make my VBA code compatible with 64-bit Windows?

To write for all versions of Office use a combination of the newer VBA7 and Win64 conditional Compiler Constants.

VBA7 determines if code is running in version 7 of the VB editor (VBA version shipped in Office 2010+).

Win64 determines which version (32-bit or 64-bit) of Office is running.

#If VBA7 Then
'Code is running VBA7 (2010 or later).

     #If Win64 Then
     'Code is running in 64-bit version of Microsoft Office.
     #Else
     'Code is running in 32-bit version of Microsoft Office.
     #End If

#Else
'Code is running VBA6 (2007 or earlier).

#End If

See Microsoft Support Article for more details.

Does HTTP use UDP?

I think some of the answers are missing an important point. The choice between UDP and TCP should not be based on the type of data (e.g., audio or video) or whether the application starts to play it before the transfer is completed ("streaming"), but whether it is real time. Real time data is (by definition) delay-sensitive, so it is often best sent over RTP/UDP (Real Time Protocol over UDP).

Delay is not an issue with stored data from a file, even if it's audio and/or video, so it is probably best sent over TCP so any packet losses can be corrected. The sender can read ahead and keep the network pipe full and the receiver can also use lots of playout buffering so it won't be interrupted by the occasional TCP retransmission or momentary network slowdown. The limiting case is where the entire recording is transferred before playback begins. This eliminates any risk of a playback stall, but is often impractical.

The problem with TCP for real-time data isn't retransmissions so much as excessive buffering as TCP tries to use the pipe as efficiently as possible without regard to latency. UDP preserves application packet boundaries and has no internal storage, so it does not introduce any latency.

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.

To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().

As like below example:

SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
     SELECT DISTINCT <column names>...
) AS tbl

jquery - return value using ajax result on success

EDIT: This is quite old, and ugly, don't do this. You should use callbacks: https://stackoverflow.com/a/5316755/591257

EDIT 2: See the fetch API

Had same problem, solved it this way, using a global var. Not sure if it's the best but surely works. On error you get an empty string (myVar = ''), so you can handle that as needed.

var myVar = '';
function isSession(selector) {
  $.ajax({
    'type': 'POST',
    'url': '/order.html',
    'data': {
      'issession': 1,
      'selector': selector
    },
    'dataType': 'html',
    'success': function(data) {
      myVar = data;
    },
    'error': function() {
      alert('Error occured');
    }
  });
  return myVar;
}

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

Throwing exceptions in a PHP Try Catch block

Just remove the throw from the catch block — change it to an echo or otherwise handle the error.

It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.

In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.

A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.

Get unique values from a list in python

As a bonus, Counter is a simple way to get both the unique values and the count for each value:

from collections import Counter
l = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
c = Counter(l)

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

Change type of varchar field to integer: "cannot be cast automatically to type integer"

this worked for me.

change varchar column to int

change_column :table_name, :column_name, :integer

got:

PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

chnged to

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

C# Get a control's position on a form

I usually combine PointToScreen and PointToClient:

Point locationOnForm = control.FindForm().PointToClient(
    control.Parent.PointToScreen(control.Location));

Converting String To Float in C#

Use Convert.ToDouble("41.00027357629127");

Convert.ToDouble documentation

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

Look in wp-includes/version.php

/**
 * The WordPress version string
 *
 * @global string $wp_version
 */
$wp_version = '2.8.4';

How do you create an asynchronous HTTP request in JAVA?

Here is a solution using apache HttpClient and making the call in a separate thread. This solution is useful if you are only making one async call. If you are making multiple calls I suggest using apache HttpAsyncClient and placing the calls in a thread pool.

import java.lang.Thread;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;

public class ApacheHttpClientExample {
    public static void main(final String[] args) throws Exception {
        try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
            final HttpGet httpget = new HttpGet("http://httpbin.org/get");
            new Thread(() -> {
                 final String responseBody = httpclient.execute(httpget);
            }).start();
        }
    }
}

How to initialize an array of objects in Java

If you are unsure of the size of the array or if it can change you can do this to have a static array.

ArrayList<Player> thePlayersList = new ArrayList<Player>(); 

thePlayersList.add(new Player(1));
thePlayersList.add(new Player(2));
.
.
//Some code here that changes the number of players e.g

Players[] thePlayers = thePlayersList.toArray();

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

Replace 123 with number of commits your branch has diverged from origin.

git reset HEAD~123 && git reset && git checkout . && git clean -fd && git pull

Cross-platform way of getting temp directory in Python

The simplest way, based on @nosklo's comment and answer:

import tempfile
tmp = tempfile.mkdtemp()

But if you want to manually control the creation of the directories:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

This is similar to what applications like Google Chrome and Linux systemd do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.

How to 'insert if not exists' in MySQL?

There are several answers that cover how to solve this if you have a UNIQUE index that you can check against with ON DUPLICATE KEY or INSERT IGNORE. That is not always the case, and as UNIQUE has a length constraint (1000 bytes) you might not be able to change that. For example, I had to work with metadata in WordPress (wp_postmeta).

I finally solved it with two queries:

UPDATE wp_postmeta SET meta_value = ? WHERE meta_key = ? AND post_id = ?;
INSERT INTO wp_postmeta (post_id, meta_key, meta_value) SELECT DISTINCT ?, ?, ? FROM wp_postmeta WHERE NOT EXISTS(SELECT * FROM wp_postmeta WHERE meta_key = ? AND post_id = ?);

Query 1 is a regular UPDATE query with no effect when the dataset in question is not there. Query 2 is an INSERT which depends on a NOT EXISTS, i.e. the INSERT is only executed when the dataset doesn't exist.

htmlentities() vs. htmlspecialchars()

**HTML Character Entity Reference Chart at W3.org**

https://dev.w3.org/html5/html-author/charref

&Tab;
&NewLine;
!
&excl;
"
&quot; &QUOT;
#
&num;
$
&dollar;
%
&percnt;
&
&amp; &AMP;
'
&apos;
(
&lpar;
)
&rpar;
*
&ast; &midast;
+
&plus;
,
&comma;
.
&period;
/
&sol;
:
&colon;
;
&semi;
<
&lt; &LT;
=
&equals;
>
&gt; &GT;
?
&quest;
@
&commat;
[
&lsqb; &lbrack;
\
&bsol;
]
&rsqb; &rbrack;
^
&Hat;
_
&lowbar;
`
&grave; &DiacriticalGrave;
{
&lcub; &lbrace;
|
&verbar; &vert; &VerticalLine;
}
&rcub; &rbrace;

&nbsp; &NonBreakingSpace;
¡
&iexcl;
¢
&cent;
£
&pound;
¤
&curren;
¥
&yen;
¦
&brvbar;
§
&sect;
¨
&Dot; &die; &DoubleDot; &uml;
©
&copy; &COPY;
ª
&ordf;
«
&laquo;
¬
&not;
&shy;
®
&reg; &circledR; &REG;
¯
&macr; &OverBar; &strns;
°
&deg;
±
&plusmn; &pm; &PlusMinus;
²
&sup2;
³
&sup3;
´
&acute; &DiacriticalAcute;
µ
&micro;
¶
&para;
·
&middot; &centerdot; &CenterDot;
¸
&cedil; &Cedilla;
¹
&sup1;
º
&ordm;
»
&raquo;
¼
&frac14;
½
&frac12; &half;
¾
&frac34;
¿
&iquest;
À
&Agrave;
Á
&Aacute;
Â
&Acirc;
Ã
&Atilde;
Ä
&Auml;
Å
&Aring;
Æ
&AElig;
Ç
&Ccedil;
È
&Egrave;
É
&Eacute;
Ê
&Ecirc;
Ë
&Euml;
Ì
&Igrave;
Í
&Iacute;
Î
&Icirc;
Ï
&Iuml;
Ð
&ETH;
Ñ
&Ntilde;
Ò
&Ograve;
Ó
&Oacute;
Ô
&Ocirc;
Õ
&Otilde;
Ö
&Ouml;
×
&times;
Ø
&Oslash;
Ù
&Ugrave;
Ú
&Uacute;
Û
&Ucirc;
Ü
&Uuml;
Ý
&Yacute;
Þ
&THORN;
ß
&szlig;
à
&agrave;
á
&aacute;
â
&acirc;
ã
&atilde;
ä
&auml;
å
&aring;
æ
&aelig;
ç
&ccedil;
è
&egrave;
é
&eacute;
ê
&ecirc;
ë
&euml;
ì
&igrave;
í
&iacute;
î
&icirc;
ï
&iuml;
ð
&eth;
ñ
&ntilde;
ò
&ograve;
ó
&oacute;
ô
&ocirc;
õ
&otilde;
ö
&ouml;
÷
&divide; &div;
ø
&oslash;
ù
&ugrave;
ú
&uacute;
û
&ucirc;
ü
&uuml;
ý
&yacute;
þ
&thorn;
ÿ
&yuml;
A
&Amacr;
a
&amacr;
A
&Abreve;
a
&abreve;
A
&Aogon;
a
&aogon;
C
&Cacute;
c
&cacute;
C
&Ccirc;
c
&ccirc;
C
&Cdot;
c
&cdot;
C
&Ccaron;
c
&ccaron;
D
&Dcaron;
d
&dcaron;
Ð
&Dstrok;
d
&dstrok;
E
&Emacr;
e
&emacr;
E
&Edot;
e
&edot;
E
&Eogon;
e
&eogon;
E
&Ecaron;
e
&ecaron;
G
&Gcirc;
g
&gcirc;
G
&Gbreve;
g
&gbreve;
G
&Gdot;
g
&gdot;
G
&Gcedil;
H
&Hcirc;
h
&hcirc;
H
&Hstrok;
h
&hstrok;
I
&Itilde;
i
&itilde;
I
&Imacr;
i
&imacr;
I
&Iogon;
i
&iogon;
I
&Idot;
i
&imath; &inodot;
?
&IJlig;
?
&ijlig;
J
&Jcirc;
j
&jcirc;
K
&Kcedil;
k
&kcedil;
?
&kgreen;
L
&Lacute;
l
&lacute;
L
&Lcedil;
l
&lcedil;
L
&Lcaron;
l
&lcaron;
?
&Lmidot;
?
&lmidot;
L
&Lstrok;
l
&lstrok;
N
&Nacute;
n
&nacute;
N
&Ncedil;
n
&ncedil;
N
&Ncaron;
n
&ncaron;
?
&napos;
?
&ENG;
?
&eng;
O
&Omacr;
o
&omacr;
O
&Odblac;
o
&odblac;
Œ
&OElig;
œ
&oelig;
R
&Racute;
r
&racute;
R
&Rcedil;
r
&rcedil;
R
&Rcaron;
r
&rcaron;
S
&Sacute;
s
&sacute;
S
&Scirc;
s
&scirc;
S
&Scedil;
s
&scedil;
Š
&Scaron;
š
&scaron;
T
&Tcedil;
t
&tcedil;
T
&Tcaron;
t
&tcaron;
T
&Tstrok;
t
&tstrok;
U
&Utilde;
u
&utilde;
U
&Umacr;
u
&umacr;
U
&Ubreve;
u
&ubreve;
U
&Uring;
u
&uring;
U
&Udblac;
u
&udblac;
U
&Uogon;
u
&uogon;
W
&Wcirc;
w
&wcirc;
Y
&Ycirc;
y
&ycirc;
Ÿ
&Yuml;
Z
&Zacute;
z
&zacute;
Z
&Zdot;
z
&zdot;
Ž
&Zcaron;
ž
&zcaron;
ƒ
&fnof;
?
&imped;
?
&gacute;
?
&jmath;
ˆ
&circ;
?
&caron; &Hacek;
?
&breve; &Breve;
?
&dot; &DiacriticalDot;
°
&ring;
?
&ogon;
˜
&tilde; &DiacriticalTilde;
?
&dblac; &DiacriticalDoubleAcute;
?
&DownBreve;
_
&UnderBar;
?
&Alpha;
?
&Beta;
G
&Gamma;
?
&Delta;
?
&Epsilon;
?
&Zeta;
?
&Eta;
T
&Theta;
?
&Iota;
?
&Kappa;
?
&Lambda;
?
&Mu;
?
&Nu;
?
&Xi;
?
&Omicron;
?
&Pi;
?
&Rho;
S
&Sigma;
?
&Tau;
?
&Upsilon;
F
&Phi;
?
&Chi;
?
&Psi;
O
&Omega;
a
&alpha;
ß
&beta;
?
&gamma;
d
&delta;
e
&epsiv; &varepsilon; &epsilon;
?
&zeta;
?
&eta;
?
&theta;
?
&iota;
?
&kappa;
?
&lambda;
µ
&mu;
?
&nu;
?
&xi;
?
&omicron;
p
&pi;
?
&rho;
?
&sigmav; &varsigma; &sigmaf;
s
&sigma;
t
&tau;
?
&upsi; &upsilon;
f
&phi; &phiv; &varphi;
?
&chi;
?
&psi;
?
&omega;
?
&thetav; &vartheta; &thetasym;
?
&Upsi; &upsih;
?
&straightphi;
?
&piv; &varpi;
?
&Gammad;
?
&gammad; &digamma;
?
&kappav; &varkappa;
?
&rhov; &varrho;
?
&epsi; &straightepsilon;
?
&bepsi; &backepsilon;
?
&IOcy;
?
&DJcy;
?
&GJcy;
?
&Jukcy;
?
&DScy;
?
&Iukcy;
?
&YIcy;
?
&Jsercy;
?
&LJcy;
?
&NJcy;
?
&TSHcy;
?
&KJcy;
?
&Ubrcy;
?
&DZcy;
?
&Acy;
?
&Bcy;
?
&Vcy;
?
&Gcy;
?
&Dcy;
?
&IEcy;
?
&ZHcy;
?
&Zcy;
?
&Icy;
?
&Jcy;
?
&Kcy;
?
&Lcy;
?
&Mcy;
?
&Ncy;
?
&Ocy;
?
&Pcy;
?
&Rcy;
?
&Scy;
?
&Tcy;
?
&Ucy;
?
&Fcy;
?
&KHcy;
?
&TScy;
?
&CHcy;
?
&SHcy;
?
&SHCHcy;
?
&HARDcy;
?
&Ycy;
?
&SOFTcy;
?
&Ecy;
?
&YUcy;
?
&YAcy;
?
&acy;
?
&bcy;
?
&vcy;
?
&gcy;
?
&dcy;
?
&iecy;
?
&zhcy;
?
&zcy;
?
&icy;
?
&jcy;
?
&kcy;
?
&lcy;
?
&mcy;
?
&ncy;
?
&ocy;
?
&pcy;
?
&rcy;
?
&scy;
?
&tcy;
?
&ucy;
?
&fcy;
?
&khcy;
?
&tscy;
?
&chcy;
?
&shcy;
?
&shchcy;
?
&hardcy;
?
&ycy;
?
&softcy;
?
&ecy;
?
&yucy;
?
&yacy;
?
&iocy;
?
&djcy;
?
&gjcy;
?
&jukcy;
?
&dscy;
?
&iukcy;
?
&yicy;
?
&jsercy;
?
&ljcy;
?
&njcy;
?
&tshcy;
?
&kjcy;
?
&ubrcy;
?
&dzcy;
 
&ensp;
 
&emsp;
 
&emsp13;
 
&emsp14;
 
&numsp;
 
&puncsp;
 
&thinsp; &ThinSpace;
 
&hairsp; &VeryThinSpace;
?
&ZeroWidthSpace; &NegativeVeryThinSpace; &NegativeThinSpace; &NegativeMediumSpace; &NegativeThickSpace;
?
&zwnj;
?
&zwj;
?
&lrm;
?
&rlm;
-
&hyphen; &dash;
–
&ndash;
—
&mdash;
-
&horbar;
?
&Verbar; &Vert;
‘
&lsquo; &OpenCurlyQuote;
’
&rsquo; &rsquor; &CloseCurlyQuote;
‚
&lsquor; &sbquo;
“
&ldquo; &OpenCurlyDoubleQuote;
”
&rdquo; &rdquor; &CloseCurlyDoubleQuote;
„
&ldquor; &bdquo;
†
&dagger;
‡
&Dagger; &ddagger;
•
&bull; &bullet;
?
&nldr;
…
&hellip; &mldr;
‰
&permil;
?
&pertenk;
'
&prime;
"
&Prime;
?
&tprime;
`
&bprime; &backprime;
‹
&lsaquo;
›
&rsaquo;
?
&oline;
?
&caret;
?
&hybull;
/
&frasl;
?
&bsemi;
?
&qprime;
?
&MediumSpace;
?
&NoBreak;
?
&ApplyFunction; &af;
?
&InvisibleTimes; &it;
?
&InvisibleComma; &ic;
€
&euro;
?
&tdot; &TripleDot;
?
&DotDot;
C
&Copf; &complexes;
?
&incare;
g
&gscr;
H
&hamilt; &HilbertSpace; &Hscr;
H
&Hfr; &Poincareplane;
H
&quaternions; &Hopf;
h
&planckh;
?
&planck; &hbar; &plankv; &hslash;
I
&Iscr; &imagline;
I
&image; &Im; &imagpart; &Ifr;
L
&Lscr; &lagran; &Laplacetrf;
l
&ell;
N
&Nopf; &naturals;
?
&numero;
?
&copysr;
P
&weierp; &wp;
P
&Popf; &primes;
Q
&rationals; &Qopf;
R
&Rscr; &realine;
R
&real; &Re; &realpart; &Rfr;
R
&reals; &Ropf;
?
&rx;
™
&trade; &TRADE;
Z
&integers; &Zopf;
?
&ohm;
?
&mho;
Z
&Zfr; &zeetrf;
?
&iiota;
Å
&angst;
B
&bernou; &Bernoullis; &Bscr;
C
&Cfr; &Cayleys;
e
&escr;
E
&Escr; &expectation;
F
&Fscr; &Fouriertrf;
M
&phmmat; &Mellintrf; &Mscr;
o
&order; &orderof; &oscr;
?
&alefsym; &aleph;
?
&beth;
?
&gimel;
?
&daleth;
?
&CapitalDifferentialD; &DD;
?
&DifferentialD; &dd;
?
&ExponentialE; &exponentiale; &ee;
?
&ImaginaryI; &ii;
?
&frac13;
?
&frac23;
?
&frac15;
?
&frac25;
?
&frac35;
?
&frac45;
?
&frac16;
?
&frac56;
?
&frac18;
?
&frac38;
?
&frac58;
?
&frac78;
?
&larr; &leftarrow; &LeftArrow; &slarr; &ShortLeftArrow;
?
&uarr; &uparrow; &UpArrow; &ShortUpArrow;
?
&rarr; &rightarrow; &RightArrow; &srarr; &ShortRightArrow;
?
&darr; &downarrow; &DownArrow; &ShortDownArrow;
?
&harr; &leftrightarrow; &LeftRightArrow;
?
&varr; &updownarrow; &UpDownArrow;
?
&nwarr; &UpperLeftArrow; &nwarrow;
?
&nearr; &UpperRightArrow; &nearrow;
?
&searr; &searrow; &LowerRightArrow;
?
&swarr; &swarrow; &LowerLeftArrow;
?
&nlarr; &nleftarrow;
?
&nrarr; &nrightarrow;
?
&rarrw; &rightsquigarrow;
?
&Larr; &twoheadleftarrow;
?
&Uarr;
?
&Rarr; &twoheadrightarrow;
?
&Darr;
?
&larrtl; &leftarrowtail;
?
&rarrtl; &rightarrowtail;
?
&LeftTeeArrow; &mapstoleft;
?
&UpTeeArrow; &mapstoup;
?
&map; &RightTeeArrow; &mapsto;
?
&DownTeeArrow; &mapstodown;
?
&larrhk; &hookleftarrow;
?
&rarrhk; &hookrightarrow;
?
&larrlp; &looparrowleft;
?
&rarrlp; &looparrowright;
?
&harrw; &leftrightsquigarrow;
?
&nharr; &nleftrightarrow;
?
&lsh; &Lsh;
?
&rsh; &Rsh;
?
&ldsh;
?
&rdsh;
?
&crarr;
?
&cularr; &curvearrowleft;
?
&curarr; &curvearrowright;
?
&olarr; &circlearrowleft;
?
&orarr; &circlearrowright;
?
&lharu; &LeftVector; &leftharpoonup;
?
&lhard; &leftharpoondown; &DownLeftVector;
?
&uharr; &upharpoonright; &RightUpVector;
?
&uharl; &upharpoonleft; &LeftUpVector;
?
&rharu; &RightVector; &rightharpoonup;
?
&rhard; &rightharpoondown; &DownRightVector;
?
&dharr; &RightDownVector; &downharpoonright;
?
&dharl; &LeftDownVector; &downharpoonleft;
?
&rlarr; &rightleftarrows; &RightArrowLeftArrow;
?
&udarr; &UpArrowDownArrow;
?
&lrarr; &leftrightarrows; &LeftArrowRightArrow;
?
&llarr; &leftleftarrows;
?
&uuarr; &upuparrows;
?
&rrarr; &rightrightarrows;
?
&ddarr; &downdownarrows;
?
&lrhar; &ReverseEquilibrium; &leftrightharpoons;
?
&rlhar; &rightleftharpoons; &Equilibrium;
?
&nlArr; &nLeftarrow;
?
&nhArr; &nLeftrightarrow;
?
&nrArr; &nRightarrow;
?
&lArr; &Leftarrow; &DoubleLeftArrow;
?
&uArr; &Uparrow; &DoubleUpArrow;
?
&rArr; &Rightarrow; &Implies; &DoubleRightArrow;
?
&dArr; &Downarrow; &DoubleDownArrow;
?
&hArr; &Leftrightarrow; &DoubleLeftRightArrow; &iff;
?
&vArr; &Updownarrow; &DoubleUpDownArrow;
?
&nwArr;
?
&neArr;
?
&seArr;
?
&swArr;
?
&lAarr; &Lleftarrow;
?
&rAarr; &Rrightarrow;
?
&zigrarr;
?
&larrb; &LeftArrowBar;
?
&rarrb; &RightArrowBar;
?
&duarr; &DownArrowUpArrow;
?
&loarr;
?
&roarr;
?
&hoarr;
?
&forall; &ForAll;
?
&comp; &complement;
?
&part; &PartialD;
?
&exist; &Exists;
?
&nexist; &NotExists; &nexists;
Ø
&empty; &emptyset; &emptyv; &varnothing;
?
&nabla; &Del;
?
&isin; &isinv; &Element; &in;
?
&notin; &NotElement; &notinva;
?
&niv; &ReverseElement; &ni; &SuchThat;
?
&notni; &notniva; &NotReverseElement;
?
&prod; &Product;
?
&coprod; &Coproduct;
?
&sum; &Sum;
-
&minus;
±
&mnplus; &mp; &MinusPlus;
?
&plusdo; &dotplus;
\
&setmn; &setminus; &Backslash; &ssetmn; &smallsetminus;
*
&lowast;
°
&compfn; &SmallCircle;
v
&radic; &Sqrt;
?
&prop; &propto; &Proportional; &vprop; &varpropto;
8
&infin;
?
&angrt;
?
&ang; &angle;
?
&angmsd; &measuredangle;
?
&angsph;
|
&mid; &VerticalBar; &smid; &shortmid;
?
&nmid; &NotVerticalBar; &nsmid; &nshortmid;
?
&par; &parallel; &DoubleVerticalBar; &spar; &shortparallel;
?
&npar; &nparallel; &NotDoubleVerticalBar; &nspar; &nshortparallel;
?
&and; &wedge;
?
&or; &vee;
n
&cap;
?
&cup;
?
&int; &Integral;
?
&Int;
?
&tint; &iiint;
?
&conint; &oint; &ContourIntegral;
?
&Conint; &DoubleContourIntegral;
?
&Cconint;
?
&cwint;
?
&cwconint; &ClockwiseContourIntegral;
?
&awconint; &CounterClockwiseContourIntegral;
?
&there4; &therefore; &Therefore;
?
&becaus; &because; &Because;
:
&ratio;
?
&Colon; &Proportion;
?
&minusd; &dotminus;
?
&mDDot;
?
&homtht;
~
&sim; &Tilde; &thksim; &thicksim;
?
&bsim; &backsim;
?
&ac; &mstpos;
?
&acd;
?
&wreath; &VerticalTilde; &wr;
?
&nsim; &NotTilde;
?
&esim; &EqualTilde; &eqsim;
?
&sime; &TildeEqual; &simeq;
?
&nsime; &nsimeq; &NotTildeEqual;
?
&cong; &TildeFullEqual;
?
&simne;
?
&ncong; &NotTildeFullEqual;
˜
&asymp; &ap; &TildeTilde; &approx; &thkap; &thickapprox;
?
&nap; &NotTildeTilde; &napprox;
?
&ape; &approxeq;
?
&apid;
?
&bcong; &backcong;
?
&asympeq; &CupCap;
?
&bump; &HumpDownHump; &Bumpeq;
?
&bumpe; &HumpEqual; &bumpeq;
?
&esdot; &DotEqual; &doteq;
?
&eDot; &doteqdot;
?
&efDot; &fallingdotseq;
?
&erDot; &risingdotseq;
?
&colone; &coloneq; &Assign;
?
&ecolon; &eqcolon;
?
&ecir; &eqcirc;
?
&cire; &circeq;
?
&wedgeq;
?
&veeeq;
?
&trie; &triangleq;
?
&equest; &questeq;
?
&ne; &NotEqual;
=
&equiv; &Congruent;
?
&nequiv; &NotCongruent;
=
&le; &leq;
=
&ge; &GreaterEqual; &geq;
?
&lE; &LessFullEqual; &leqq;
?
&gE; &GreaterFullEqual; &geqq;
?
&lnE; &lneqq;
?
&gnE; &gneqq;
«
&Lt; &NestedLessLess; &ll;
»
&Gt; &NestedGreaterGreater; &gg;
?
&twixt; &between;
?
&NotCupCap;
?
&nlt; &NotLess; &nless;
?
&ngt; &NotGreater; &ngtr;
?
&nle; &NotLessEqual; &nleq;
?
&nge; &NotGreaterEqual; &ngeq;
?
&lsim; &LessTilde; &lesssim;
?
&gsim; &gtrsim; &GreaterTilde;
?
&nlsim; &NotLessTilde;
?
&ngsim; &NotGreaterTilde;
?
&lg; &lessgtr; &LessGreater;
?
&gl; &gtrless; &GreaterLess;
?
&ntlg; &NotLessGreater;
?
&ntgl; &NotGreaterLess;
?
&pr; &Precedes; &prec;
?
&sc; &Succeeds; &succ;
?
&prcue; &PrecedesSlantEqual; &preccurlyeq;
?
&sccue; &SucceedsSlantEqual; &succcurlyeq;
?
&prsim; &precsim; &PrecedesTilde;
?
&scsim; &succsim; &SucceedsTilde;
?
&npr; &nprec; &NotPrecedes;
?
&nsc; &nsucc; &NotSucceeds;
?
&sub; &subset;
?
&sup; &supset; &Superset;
?
&nsub;
?
&nsup;
?
&sube; &SubsetEqual; &subseteq;
?
&supe; &supseteq; &SupersetEqual;
?
&nsube; &nsubseteq; &NotSubsetEqual;
?
&nsupe; &nsupseteq; &NotSupersetEqual;
?
&subne; &subsetneq;
?
&supne; &supsetneq;
?
&cupdot;
?
&uplus; &UnionPlus;
?
&sqsub; &SquareSubset; &sqsubset;
?
&sqsup; &SquareSuperset; &sqsupset;
?
&sqsube; &SquareSubsetEqual; &sqsubseteq;
?
&sqsupe; &SquareSupersetEqual; &sqsupseteq;
?
&sqcap; &SquareIntersection;
?
&sqcup; &SquareUnion;
?
&oplus; &CirclePlus;
?
&ominus; &CircleMinus;
?
&otimes; &CircleTimes;
?
&osol;
?
&odot; &CircleDot;
?
&ocir; &circledcirc;
?
&oast; &circledast;
?
&odash; &circleddash;
?
&plusb; &boxplus;
?
&minusb; &boxminus;
?
&timesb; &boxtimes;
?
&sdotb; &dotsquare;
?
&vdash; &RightTee;
?
&dashv; &LeftTee;
?
&top; &DownTee;
?
&bottom; &bot; &perp; &UpTee;
?
&models;
?
&vDash; &DoubleRightTee;
?
&Vdash;
?
&Vvdash;
?
&VDash;
?
&nvdash;
?
&nvDash;
?
&nVdash;
?
&nVDash;
?
&prurel;
?
&vltri; &vartriangleleft; &LeftTriangle;
?
&vrtri; &vartriangleright; &RightTriangle;
?
&ltrie; &trianglelefteq; &LeftTriangleEqual;
?
&rtrie; &trianglerighteq; &RightTriangleEqual;
?
&origof;
?
&imof;
?
&mumap; &multimap;
?
&hercon;
?
&intcal; &intercal;
?
&veebar;
?
&barvee;
?
&angrtvb;
?
&lrtri;
?
&xwedge; &Wedge; &bigwedge;
?
&xvee; &Vee; &bigvee;
?
&xcap; &Intersection; &bigcap;
?
&xcup; &Union; &bigcup;
?
&diam; &diamond; &Diamond;
·
&sdot;
?
&sstarf; &Star;
?
&divonx; &divideontimes;
?
&bowtie;
?
&ltimes;
?
&rtimes;
?
&lthree; &leftthreetimes;
?
&rthree; &rightthreetimes;
?
&bsime; &backsimeq;
?
&cuvee; &curlyvee;
?
&cuwed; &curlywedge;
?
&Sub; &Subset;
?
&Sup; &Supset;
?
&Cap;
?
&Cup;
?
&fork; &pitchfork;
?
&epar;
?
&ltdot; &lessdot;
?
&gtdot; &gtrdot;
?
&Ll;
?
&Gg; &ggg;
?
&leg; &LessEqualGreater; &lesseqgtr;
?
&gel; &gtreqless; &GreaterEqualLess;
?
&cuepr; &curlyeqprec;
?
&cuesc; &curlyeqsucc;
?
&nprcue; &NotPrecedesSlantEqual;
?
&nsccue; &NotSucceedsSlantEqual;
?
&nsqsube; &NotSquareSubsetEqual;
?
&nsqsupe; &NotSquareSupersetEqual;
?
&lnsim;
?
&gnsim;
?
&prnsim; &precnsim;
?
&scnsim; &succnsim;
?
&nltri; &ntriangleleft; &NotLeftTriangle;
?
&nrtri; &ntriangleright; &NotRightTriangle;
?
&nltrie; &ntrianglelefteq; &NotLeftTriangleEqual;
?
&nrtrie; &ntrianglerighteq; &NotRightTriangleEqual;
?
&vellip;
?
&ctdot;
?
&utdot;
?
&dtdot;
?
&disin;
?
&isinsv;
?
&isins;
?
&isindot;
?
&notinvc;
?
&notinvb;
?
&isinE;
?
&nisd;
?
&xnis;
?
&nis;
?
&notnivc;
?
&notnivb;
?
&barwed; &barwedge;
?
&Barwed; &doublebarwedge;
?
&lceil; &LeftCeiling;
?
&rceil; &RightCeiling;
?
&lfloor; &LeftFloor;
?
&rfloor; &RightFloor;
?
&drcrop;
?
&dlcrop;
?
&urcrop;
?
&ulcrop;
¬
&bnot;
?
&profline;
?
&profsurf;
?
&telrec;
?
&target;
?
&ulcorn; &ulcorner;
?
&urcorn; &urcorner;
?
&dlcorn; &llcorner;
?
&drcorn; &lrcorner;
?
&frown; &sfrown;
?
&smile; &ssmile;
?
&cylcty;
?
&profalar;
?
&topbot;
?
&ovbar;
?
&solbar;
?
&angzarr;
?
&lmoust; &lmoustache;
?
&rmoust; &rmoustache;
?
&tbrk; &OverBracket;
?
&bbrk; &UnderBracket;
?
&bbrktbrk;
?
&OverParenthesis;
?
&UnderParenthesis;
?
&OverBrace;
?
&UnderBrace;
?
&trpezium;
?
&elinters;
?
&blank;
?
&oS; &circledS;
-
&boxh; &HorizontalLine;
¦
&boxv;
+
&boxdr;
+
&boxdl;
+
&boxur;
+
&boxul;
+
&boxvr;
¦
&boxvl;
-
&boxhd;
-
&boxhu;
+
&boxvh;
-
&boxH;
¦
&boxV;
+
&boxdR;
+
&boxDr;
+
&boxDR;
+
&boxdL;
+
&boxDl;
+
&boxDL;
+
&boxuR;
+
&boxUr;
+
&boxUR;
+
&boxuL;
+
&boxUl;
+
&boxUL;
¦
&boxvR;
¦
&boxVr;
¦
&boxVR;
¦
&boxvL;
¦
&boxVl;
¦
&boxVL;
-
&boxHd;
-
&boxhD;
-
&boxHD;
-
&boxHu;
-
&boxhU;
-
&boxHU;
+
&boxvH;
+
&boxVh;
+
&boxVH;
¯
&uhblk;
_
&lhblk;
¦
&block;
¦
&blk14;
¦
&blk12;
¦
&blk34;
?
&squ; &square; &Square;
?
&squf; &squarf; &blacksquare; &FilledVerySmallSquare;
?
&EmptyVerySmallSquare;
?
&rect;
?
&marker;
?
&fltns;
?
&xutri; &bigtriangleup;
?
&utrif; &blacktriangle;
?
&utri; &triangle;
?
&rtrif; &blacktriangleright;
?
&rtri; &triangleright;
?
&xdtri; &bigtriangledown;
?
&dtrif; &blacktriangledown;
?
&dtri; &triangledown;
?
&ltrif; &blacktriangleleft;
?
&ltri; &triangleleft;
?
&loz; &lozenge;
?
&cir;
?
&tridot;
?
&xcirc; &bigcirc;
?
&ultri;
?
&urtri;
?
&lltri;
?
&EmptySmallSquare;
?
&FilledSmallSquare;
?
&starf; &bigstar;
?
&star;
?
&phone;
?
&female;
?
&male;
?
&spades; &spadesuit;
?
&clubs; &clubsuit;
?
&hearts; &heartsuit;
?
&diams; &diamondsuit;
?
&sung;
?
&flat;
?
&natur; &natural;
?
&sharp;
?
&check; &checkmark;
?
&cross;
?
&malt; &maltese;
?
&sext;
|
&VerticalSeparator;
?
&lbbrk;
?
&rbbrk;
?
&lobrk; &LeftDoubleBracket;
?
&robrk; &RightDoubleBracket;
?
&lang; &LeftAngleBracket; &langle;
?
&rang; &RightAngleBracket; &rangle;
?
&Lang;
?
&Rang;
?
&loang;
?
&roang;
?
&xlarr; &longleftarrow; &LongLeftArrow;
?
&xrarr; &longrightarrow; &LongRightArrow;
?
&xharr; &longleftrightarrow; &LongLeftRightArrow;
?
&xlArr; &Longleftarrow; &DoubleLongLeftArrow;
?
&xrArr; &Longrightarrow; &DoubleLongRightArrow;
?
&xhArr; &Longleftrightarrow; &DoubleLongLeftRightArrow;
?
&xmap; &longmapsto;
?
&dzigrarr;
?
&nvlArr;
?
&nvrArr;
?
&nvHarr;
?
&Map;
?
&lbarr;
?
&rbarr; &bkarow;
?
&lBarr;
?
&rBarr; &dbkarow;
?
&RBarr; &drbkarow;
?
&DDotrahd;
?
&UpArrowBar;
?
&DownArrowBar;
?
&Rarrtl;
?
&latail;
?
&ratail;
?
&lAtail;
?
&rAtail;
?
&larrfs;
?
&rarrfs;
?
&larrbfs;
?
&rarrbfs;
?
&nwarhk;
?
&nearhk;
?
&searhk; &hksearow;
?
&swarhk; &hkswarow;
?
&nwnear;
?
&nesear; &toea;
?
&seswar; &tosa;
?
&swnwar;
?
&rarrc;
?
&cudarrr;
?
&ldca;
?
&rdca;
?
&cudarrl;
?
&larrpl;
?
&curarrm;
?
&cularrp;
?
&rarrpl;
?
&harrcir;
?
&Uarrocir;
?
&lurdshar;
?
&ldrushar;
?
&LeftRightVector;
?
&RightUpDownVector;
?
&DownLeftRightVector;
?
&LeftUpDownVector;
?
&LeftVectorBar;
?
&RightVectorBar;
?
&RightUpVectorBar;
?
&RightDownVectorBar;
?
&DownLeftVectorBar;
?
&DownRightVectorBar;
?
&LeftUpVectorBar;
?
&LeftDownVectorBar;
?
&LeftTeeVector;
?
&RightTeeVector;
?
&RightUpTeeVector;
?
&RightDownTeeVector;
?
&DownLeftTeeVector;
?
&DownRightTeeVector;
?
&LeftUpTeeVector;
?
&LeftDownTeeVector;
?
&lHar;
?
&uHar;
?
&rHar;
?
&dHar;
?
&luruhar;
?
&ldrdhar;
?
&ruluhar;
?
&rdldhar;
?
&lharul;
?
&llhard;
?
&rharul;
?
&lrhard;
?
&udhar; &UpEquilibrium;
?
&duhar; &ReverseUpEquilibrium;
?
&RoundImplies;
?
&erarr;
?
&simrarr;
?
&larrsim;
?
&rarrsim;
?
&rarrap;
?
&ltlarr;
?
&gtrarr;
?
&subrarr;
?
&suplarr;
?
&lfisht;
?
&rfisht;
?
&ufisht;
?
&dfisht;
?
&lopar;
?
&ropar;
?
&lbrke;
?
&rbrke;
?
&lbrkslu;
?
&rbrksld;
?
&lbrksld;
?
&rbrkslu;
?
&langd;
?

Not fully, pls track the link for fully document.

Adding devices to team provisioning profile

Note that testers are no longer added via UUID in the new Apple TestFlight.

Test Flight builds now require an App Store Distribution Provisioning Profile. The portal does not allow UUIDs to be added to this type of provisioning profile.

Instead, add "Internal Testers" via iTunes Connect:

Internal testers are iTunes Connect users with the Admin or Technical role. They can be added in Users and Roles.

After adding a user, be sure to click on their name and flip the "Internal Tester" switch.

Internal Tester Toggle Switch

Then, go to App > Prerelease > Internal Testers and invite them to the build.

How to keep a Python script output window open?

You have a few options:

  1. Run the program from an already-open terminal. Open a command prompt and type:

    python myscript.py
    

    For that to work you need the python executable in your path. Just check on how to edit environment variables on Windows, and add C:\PYTHON26 (or whatever directory you installed python to).

    When the program ends, it'll drop you back to the cmd prompt instead of closing the window.

  2. Add code to wait at the end of your script. For Python2, adding ...

    raw_input()
    

    ... at the end of the script makes it wait for the Enter key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. For Python3, use input().

  3. Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "python -i myscript.py" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.

Is there an arraylist in Javascript?

Try this, maybe can help, it do what you want:

ListArray

_x000D_
_x000D_
var listArray = new ListArray();_x000D_
let element = {name: 'Edy', age: 27, country: "Brazil"};_x000D_
let element2 = {name: 'Marcus', age: 27, country: "Brazil"};_x000D_
listArray.push(element);_x000D_
listArray.push(element2);_x000D_
_x000D_
console.log(listArray.array)
_x000D_
<script src="https://marcusvi200.github.io/list-array/script/ListArray.js"></script>
_x000D_
_x000D_
_x000D_

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

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

Java: JSON -> Protobuf & back conversion

I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.

Converting protobuf to JSON for storage and then back to protobuf on load is much more likely to create compatibility problems, because:

  • If the process which performs the conversion is not built with the latest version of the protobuf schema, then converting will silently drop any fields that the process doesn't know about. This is true both of the storing and loading ends.
  • Even with the most recent schema available, JSON <-> Protobuf conversion may be lossy in the presence of imprecise floating-point values and similar corner cases.
  • Protobufs actually have (slightly) stronger backwards-compatibility guarantees than JSON. Like with JSON, if you add a new field, old clients will ignore it. Unlike with JSON, Protobufs allow declaring a default value, which can make it somewhat easier for new clients to deal with old data that is otherwise missing the field. This is only a slight advantage, but otherwise Protobuf and JSON have equivalent backwards-compatibility properties, therefore you are not gaining any backwards-compatibility advantages from storing in JSON.

With all that said, there are many libraries out there for converting protobufs to JSON, usually built on the Protobuf reflection interface (not to be confused with the Java reflection interface; Protobuf reflection is offered by the com.google.protobuf.Message interface).

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

This solved my similar problem. I used it to revert the changes, then I added everything and commited changes in the terminal with

svn add folder_path/*
svn commit -m "message"

How does one check if a table exists in an Android SQLite database?

..... Toast t = Toast.makeText(context, "try... " , Toast.LENGTH_SHORT); t.show();

    Cursor callInitCheck = db.rawQuery("select count(*) from call", null);

    Toast t2a = Toast.makeText(context, "count rows " + callInitCheck.getCount() , Toast.LENGTH_SHORT);
    t2a.show();

    callInitCheck.moveToNext();
    if( Integer.parseInt( callInitCheck.getString(0)) == 0) // if no rows then do
    {
        // if empty then insert into call

.....

Adding subscribers to a list using Mailchimp's API v3

These are good answers but detached from a full answer as to how you would get a form to send data and handle that response. This will demonstrate how to add a member to a list with v3.0 of the API from an HTML page via jquery .ajax().

In Mailchimp:

  1. Acquire your API Key and List ID
  2. Make sure you setup your list and what custom fields you want to use with it. In this case, I've set up zipcode as a custom field in the list BEFORE I did the API call.
  3. Check out the API docs on adding members to lists. We are using the create method which requires the use of HTTP POST requests. There are other options in here that require PUT if you want to be able to modify/delete subs.

HTML:

<form id="pfb-signup-submission" method="post">
  <div class="sign-up-group">
    <input type="text" name="pfb-signup" id="pfb-signup-box-fname" class="pfb-signup-box" placeholder="First Name">
    <input type="text" name="pfb-signup" id="pfb-signup-box-lname" class="pfb-signup-box" placeholder="Last Name">
    <input type="email" name="pfb-signup" id="pfb-signup-box-email" class="pfb-signup-box" placeholder="[email protected]">
    <input type="text" name="pfb-signup" id="pfb-signup-box-zip" class="pfb-signup-box" placeholder="Zip Code">
  </div>
  <input type="submit" class="submit-button" value="Sign-up" id="pfb-signup-button"></a>
  <div id="pfb-signup-result"></div>
</form>

Key things:

  1. Give your <form> a unique ID and don't forget the method="post" attribute so the form works.
  2. Note the last line #signup-result is where you will deposit the feedback from the PHP script.

PHP:

<?php
  /*
   * Add a 'member' to a 'list' via mailchimp API v3.x
   * @ http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   *
   * ================
   * BACKGROUND
   * Typical use case is that this code would get run by an .ajax() jQuery call or possibly a form action
   * The live data you need will get transferred via the global $_POST variable
   * That data must be put into an array with keys that match the mailchimp endpoints, check the above link for those
   * You also need to include your API key and list ID for this to work.
   * You'll just have to go get those and type them in here, see README.md
   * ================
   */

  // Set API Key and list ID to add a subscriber
  $api_key = 'your-api-key-here';
  $list_id = 'your-list-id-here';

  /* ================
   * DESTINATION URL
   * Note: your API URL has a location subdomain at the front of the URL string
   * It can vary depending on where you are in the world
   * To determine yours, check the last 3 digits of your API key
   * ================
   */
  $url = 'https://us5.api.mailchimp.com/3.0/lists/' . $list_id . '/members/';

  /* ================
   * DATA SETUP
   * Encode data into a format that the add subscriber mailchimp end point is looking for
   * Must include 'email_address' and 'status'
   * Statuses: pending = they get an email; subscribed = they don't get an email
   * Custom fields go into the 'merge_fields' as another array
   * More here: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   * ================
   */
  $pfb_data = array(
    'email_address' => $_POST['emailname'],
    'status'        => 'pending',
    'merge_fields'  => array(
      'FNAME'       => $_POST['firstname'],
      'LNAME'       => $_POST['lastname'],
      'ZIPCODE'     => $_POST['zipcode']
    ),
  );

  // Encode the data
  $encoded_pfb_data = json_encode($pfb_data);

  // Setup cURL sequence
  $ch = curl_init();

  /* ================
   * cURL OPTIONS
   * The tricky one here is the _USERPWD - this is how you transfer the API key over
   * _RETURNTRANSFER allows us to get the response into a variable which is nice
   * This example just POSTs, we don't edit/modify - just a simple add to a list
   * _POSTFIELDS does the heavy lifting
   * _SSL_VERIFYPEER should probably be set but I didn't do it here
   * ================
   */
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_pfb_data);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  $results = curl_exec($ch); // store response
  $response = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get HTTP CODE
  $errors = curl_error($ch); // store errors

  curl_close($ch);

  // Returns info back to jQuery .ajax or just outputs onto the page

  $results = array(
    'results' => $result_info,
    'response' => $response,
    'errors' => $errors
  );

  // Sends data back to the page OR the ajax() in your JS
  echo json_encode($results);
?>

Key things:

  1. CURLOPT_USERPWD handles the API key and Mailchimp doesn't really show you how to do this.
  2. CURLOPT_RETURNTRANSFER gives us the response in such a way that we can send it back into the HTML page with the .ajax() success handler.
  3. Use json_encodeon the data you received.

JS:

// Signup form submission
$('#pfb-signup-submission').submit(function(event) {
  event.preventDefault();

  // Get data from form and store it
  var pfbSignupFNAME = $('#pfb-signup-box-fname').val();
  var pfbSignupLNAME = $('#pfb-signup-box-lname').val();
  var pfbSignupEMAIL = $('#pfb-signup-box-email').val();
  var pfbSignupZIP = $('#pfb-signup-box-zip').val();

  // Create JSON variable of retreived data
  var pfbSignupData = {
    'firstname': pfbSignupFNAME,
    'lastname': pfbSignupLNAME,
    'email': pfbSignupEMAIL,
    'zipcode': pfbSignupZIP
  };

  // Send data to PHP script via .ajax() of jQuery
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'mailchimp-signup.php',
    data: pfbSignupData,
    success: function (results) {
      $('#pfb-signup-box-fname').hide();
      $('#pfb-signup-box-lname').hide();
      $('#pfb-signup-box-email').hide();
      $('#pfb-signup-box-zip').hide();
      $('#pfb-signup-result').text('Thanks for adding yourself to the email list. We will be in touch.');
      console.log(results);
    },
    error: function (results) {
      $('#pfb-signup-result').html('<p>Sorry but we were unable to add you into the email list.</p>');
      console.log(results);
    }
  });
});

Key things:

  1. JSON data is VERY touchy on transfer. Here, I am putting it into an array and it looks easy. If you are having problems, it is likely because of how your JSON data is structured. Check this out!
  2. The keys for your JSON data will become what you reference in the PHP _POST global variable. In this case it will be _POST['email'], _POST['firstname'], etc. But you could name them whatever you want - just remember what you name the keys of the data part of your JSON transfer is how you access them in PHP.
  3. This obviously requires jQuery ;)

How to delete from a text file, all lines that contain a specific string?

cat filename | grep -v "pattern" > filename.1
mv filename.1 filename

Reading CSV file and storing values into an array

I have been using csvreader.com(paid component) for years, and I have never had a problem. It is solid, small and fast, but you do have to pay for it. You can set the delimiter to whatever you like.

using (CsvReader reader = new CsvReader(s) {
    reader.Settings.Delimiter = ';';
    reader.ReadHeaders();  // if headers on a line by themselves.  Makes reader.Headers[] available
    while (reader.ReadRecord())
        ... use reader.Values[col_i] ...
}

xcopy file, rename, suppress "Does xxx specify a file name..." message

So, there is a simple fix for this. It is admittedly awkward, but it works. xcopy will not prompt to find out if the destination is a directory or file IF the new file(filename) already exists. If you precede your xcopy command with a simple echo to the new filename, it will overwrite the empty file. Example

echo.>newfile.txt
xcopy oldfile.txt newfile.txt /Y

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

HTTPScoop is awesome for inspecting the web traffic on your Mac. It's been incredibly helpful for me. I didn't think twice about the $15 price tag. There is a 14 day trial.

Convert integer to class Date

Another way to get the same result:

date <- strptime(v,format="%Y%m%d")

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

  • Update your support library to last version

  • Open Manifest File , and add it into Manifest File

  • <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/>

  • And add for recyclerview in >> build.gradle Module app :

  • compile 'com.android.support:recyclerview-v7:25.3.1'

  • And click : Sync Now

Android Studio - Unable to find valid certification path to requested target

I changed(updated) my gradle version and it worked Form

classpath 'com.android.tools.build:gradle:3.1.4'

To

classpath 'com.android.tools.build:gradle:3.3.0'

How to redirect docker container logs to a single file?

docker logs -f docker_container_name >> YOUR_LOG_PATH 2>&1 &

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

ModalPopupExtender OK Button click event not firing?

Put into the Button-Control the Attribute "UseSubmitBehavior=false".

Executable directory where application is running from?

I needed to know this and came here, before I remembered the Environment class.

In case anyone else had this issue, just use this: Environment.CurrentDirectory.

Example:

Dim dataDirectory As String = String.Format("{0}\Data\", Environment.CurrentDirectory)

When run from Visual Studio in debug mode yeilds:

C:\Development\solution folder\application folder\bin\debug

This is the exact behaviour I needed, and its simple and straightforward enough.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

Export to xls using angularjs

I had this problem and I made a tool to export an HTML table to CSV file. The problem I had with FileSaver.js is that this tool grabs the table with html format, this is why some people can't open the file in excel or google. All you have to do is export the js file and then call the function. This is the github url https://github.com/snake404/tableToCSV if someone has the same problem.

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.6;
  background: rgba(200, 54, 54, 0.5);  
  background-color: yellow;
  filter: alpha(opacity=50);
  zoom: 1;  
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";  
  -moz-opacity: 0.5; 
  -khtml-opacity: 0.5;  
}

What is the best open source help ticket system?

Howabout Bugzilla. Open source and what Mozilla uses.

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

It is just letting you know that the object you are printing is not a string, rather a byte object as a byte literal. People explain this in incomplete ways, so here is my take.

Consider creating a byte object by typing a byte literal (literally defining a byte object without actually using a byte object e.g. by typing b'') and converting it into a string object encoded in utf-8. (Note that converting here means decoding)

byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations

You see that we simply apply the .decode(utf8) function.

Bytes in Python

https://docs.python.org/3.3/library/stdtypes.html#bytes

String literals are described by the following lexical definitions:

https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals

stringliteral   ::=  [stringprefix](shortstring | longstring)
stringprefix    ::=  "r" | "u" | "R" | "U"
shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::=  shortstringchar | stringescapeseq
longstringitem  ::=  longstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
longstringchar  ::=  <any source character except "\">
stringescapeseq ::=  "\" <any source character>

bytesliteral   ::=  bytesprefix(shortbytes | longbytes)
bytesprefix    ::=  "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes     ::=  "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes      ::=  "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::=  shortbyteschar | bytesescapeseq
longbytesitem  ::=  longbyteschar | bytesescapeseq
shortbyteschar ::=  <any ASCII character except "\" or newline or the quote>
longbyteschar  ::=  <any ASCII character except "\">
bytesescapeseq ::=  "\" <any ASCII character>

Java: Array with loop

Here's how:

// Create an array with room for 100 integers
int[] nums = new int[100];

// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
    nums[i] = i + 1;  // +1 since we want 1-100 and not 0-99

// Compute sum
int sum = 0;
for (int n : nums)
    sum += n;

// Print the result (5050)
System.out.println(sum);

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

First you need to install cors by using below command :

npm install cors --save

Now add the following code to your app starting file like ( app.js or server.js)

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

require('./router/index')(app);

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

I understand the accepted answer, and have up-voted it but thought I'd dump my laymen's answer here...

Creating a hash

  1. The salt is randomly generated using the function Rfc2898DeriveBytes which generates a hash and a salt. Inputs to Rfc2898DeriveBytes are the password, the size of the salt to generate and the number of hashing iterations to perform. https://msdn.microsoft.com/en-us/library/h83s4e12(v=vs.110).aspx
  2. The salt and the hash are then mashed together(salt first followed by the hash) and encoded as a string (so the salt is encoded in the hash). This encoded hash (which contains the salt and hash) is then stored (typically) in the database against the user.

Checking a password against a hash

To check a password that a user inputs.

  1. The salt is extracted from the stored hashed password.
  2. The salt is used to hash the users input password using an overload of Rfc2898DeriveBytes which takes a salt instead of generating one. https://msdn.microsoft.com/en-us/library/yx129kfs(v=vs.110).aspx
  3. The stored hash and the test hash are then compared.

The Hash

Under the covers the hash is generated using the SHA1 hash function (https://en.wikipedia.org/wiki/SHA-1). This function is iteratively called 1000 times (In the default Identity implementation)

Why is this secure

  • Random salts means that an attacker can’t use a pre-generated table of hashs to try and break passwords. They would need to generate a hash table for every salt. (Assuming here that the hacker has also compromised your salt)
  • If 2 passwords are identical they will have different hashes. (meaning attackers can’t infer ‘common’ passwords)
  • Iteratively calling SHA1 1000 times means that the attacker also needs to do this. The idea being that unless they have time on a supercomputer they won’t have enough resource to brute force the password from the hash. It would massively slow down the time to generate a hash table for a given salt.

Should I use int or Int32

As already stated, int = Int32. To be safe, be sure to always use int.MinValue/int.MaxValue when implementing anything that cares about the data type boundaries. Suppose .NET decided that int would now be Int64, your code would be less dependent on the bounds.

How to test abstract class in Java with JUnit?

Create a concrete class that inherits the abstract class and then test the functions the concrete class inherits from the abstract class.

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

I had same issue. My Json response from the server was having [, and, ]:

[{"DATE_HIRED":852344800000,"FRNG_SUB_ACCT":0,"MOVING_EXP":0,"CURRENCY_CODE":"CAD  ","PIN":"          ","EST_REMUN":0,"HM_DIST_CO":1,"SICK_PAY":0,"STAND_AMT":0,"BSI_GROUP":"           ","LAST_DED_SEQ":36}]

http://jsonlint.com/ says valid json. you can copy and verify it.

I have fixed with below code as temporary solution:

BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String result ="";
String output = null;
while ((result = br.readLine()) != null) {
    output = result.replace("[", "").replace("]", "");
    JSONObject jsonObject = new JSONObject(output); 
    JSONArray jsonArray = new JSONArray(output); 
    .....   
}

Cloning specific branch

You can use the following flags --single-branch && --depth to download the specific branch and to limit the amount of history which will be downloaded.

You will clone the repo from a certain point in time and only for the given branch

git clone -b <branch> --single-branch <url> --depth <number of commits>

--[no-]single-branch


Clone only the history leading to the tip of a single branch, either specified by the --branch option or the primary branch remote’s HEAD points at.

Further fetches into the resulting repository will only update the remote-tracking branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when --single-branch clone was made, no remote-tracking branch is created.


--depth

Create a shallow clone with a history truncated to the specified number of commits

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

Install a .NET windows service without InstallUtil.exe

You can always fall back to the good old WinAPI calls, although the amount of work involved is non-trivial. There is no requirement that .NET services be installed via a .NET-aware mechanism.

To install:

  • Open the service manager via OpenSCManager.
  • Call CreateService to register the service.
  • Optionally call ChangeServiceConfig2 to set a description.
  • Close the service and service manager handles with CloseServiceHandle.

To uninstall:

  • Open the service manager via OpenSCManager.
  • Open the service using OpenService.
  • Delete the service by calling DeleteService on the handle returned by OpenService.
  • Close the service and service manager handles with CloseServiceHandle.

The main reason I prefer this over using the ServiceInstaller/ServiceProcessInstaller is that you can register the service with your own custom command line arguments. For example, you might register it as "MyApp.exe -service", then if the user runs your app without any arguments you could offer them a UI to install/remove the service.

Running Reflector on ServiceInstaller can fill in the details missing from this brief explanation.

P.S. Clearly this won't have "the same effect as calling: InstallUtil MyService.exe" - in particular, you won't be able to uninstall using InstallUtil. But it seems that perhaps this wasn't an actual stringent requirement for you.

How to copy multiple files in one layer using a Dockerfile?

COPY <all> <the> <things> <last-arg-is-destination>

But here is an important excerpt from the docs:

If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This ensures that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.

https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy

How do I measure the execution time of JavaScript code with callbacks?

Use the Node.js console.time() and console.timeEnd():

var i;
console.time("dbsave");

for(i = 1; i < LIMIT; i++){
    db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}

end = function(err, saved) {
    console.log(( err || !saved )?"Error":"Saved");
    if(--i === 1){console.timeEnd("dbsave");}
};

Check, using jQuery, if an element is 'display:none' or block on click

another shortcut i personally prefer more than .is() or .length:

if($('.myclass:visible')[0]){
   // is visible
}else {
   // is hidden
}

Why does the arrow (->) operator in C exist?

Structure in C

First you need to declare your structure:

struct mystruct{
 char element_1,
 char element_2
};

Instantiate C structure

Once you declared your structure , you can instantiate a variable that has as type your structure using either:

mystruct struct_example;

or :

mystruct* struct_example;

For the first use case you can access the varaiable eleemnet using the following syntax: struct_example.element_1 = 5;

For the second use case which is having a pointer to variable of type your structure, to be able to access the variable structure you need an arrow:

struct_example->element_1 = 5;

mysql stored-procedure: out parameter

If you are calling from within Stored Procedure don't use @. In my case it returns 0

CALL SP_NAME(L_OUTPUT_PARAM)

How do I convert ticks to minutes?

You can do this way :

TimeSpan duration = new TimeSpan(tickCount)
double minutes = duration.TotalMinutes;

C# ASP.NET Single Sign-On Implementation

There are multiple options to implement SSO for a .NET application.

Check out the following tutorials online:

Basics of Single Sign on, July 2012

http://www.codeproject.com/Articles/429166/Basics-of-Single-Sign-on-SSO

GaryMcAllisterOnline: ASP.NET MVC 4, ADFS 2.0 and 3rd party STS integration (IdentityServer2), Jan 2013

http://garymcallisteronline.blogspot.com/2013/01/aspnet-mvc-4-adfs-20-and-3rd-party-sts.html

The first one uses ASP.NET Web Forms, while the second one uses ASP.NET MVC4.

If your requirements allow you to use a third-party solution, also consider OpenID. There's an open source library called DotNetOpenAuth.

For further information, read MSDN blog post Integrate OpenAuth/OpenID with your existing ASP.NET application using Universal Providers.

Hope this helps!

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

How to set alignment center in TextBox in ASP.NET?

To center align text

input[type='text'] { text-align:center;}

To center align the textbox in the container that it sits in, apply text-align:center to the container.

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

Serializing PHP object to JSON

Just implement an Interface given by PHP JsonSerializable.

How to fix homebrew permissions?

If you're on OSX High Sierra, /usr/local can no longer be chown'd. You can use:

sudo chown -R $(whoami) $(brew --prefix)/*

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

Tablets supports tvdpi and for that scaling factor is 1.33 times dimensions of medium dpi

    ldpi | mdpi | tvdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
    0.75 | 1    | 1.33  | 1.5  | 2     | 3      | 4

This means that if you generate a 400x400 image for xxxhdpi devices, you should generate the same resource in 300x300 for xxhdpi, 200x200 for xhdpi, 133x133 for tvdpi, 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

Styling twitter bootstrap buttons

In Twitter Bootstrap bootstrap 3.0.0, Twitter button is flat. You can customize it from http://getbootstrap.com/customize. Button color, border radious etc.

Also you can find the HTML code and others functionality http://twitterbootstrap.org/bootstrap-css-buttons.

Bootstrap 2.3.2 button is gradient but 3.0.0 ( new release ) flat and looks more cool.

and also you can find to customize the entire bootstrap looks and style form this resources: http://twitterbootstrap.org/top-5-customizing-bootstrap-resources/

Can I remove the URL from my print css, so the web address doesn't print?

This solution will do the trick in Chrome and Opera by setting margin to 0 in a css @page directive. It will not (currently) work for other browsers though...

How to convert a ruby hash object to JSON?

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).

So, take a look here:

car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
#   from (irb):11
#   from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"

As you can see, requiring json has magically brought method to_json to our Hash.

Selecting the last value of a column

function getDashboardSheet(spreadsheet) {
  var sheetName = 'Name';
  return spreadsheet.getSheetByName(sheetName);
}
      var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);  
      var dashboardSheet = getDashboardSheet(spreadsheet);
      Logger.log('see:'+dashboardSheet.getLastRow());

How to convert BigDecimal to Double in Java?

You can convert BigDecimal to double using .doubleValue(). But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal objects directly. Precision loss in these calculations are big time problems in currency related calculations.

psql: FATAL: Ident authentication failed for user "postgres"

The problem is still your pg_hba.conf file. This line: You can found this file in /etc/postgres/varion/main

local   all             postgres                                peer
Should be

local   all             postgres                                md5

These are brief descriptions of both options according to the official PostgreSQL docs on authentication methods.

Peer authentication

The peer authentication method works by obtaining the client's operating system user name from the kernel and using it as the allowed database user name (with optional user name mapping). This method is only supported on local connections.

Password authentication

The password-based authentication methods are md5 and password. These methods operate similarly except for the way that the password is sent across the connection, namely MD5-hashed and clear-text respectively.

If you are at all concerned about password "sniffing" attacks then md5 is preferred. Plain password should always be avoided if possible. However, md5 cannot be used with the db_user_namespace feature. If the connection is protected by SSL encryption then password can be used safely (though SSL certificate authentication might be a better choice if one is depending on using SSL).

After altering this file, don't forget to restart your PostgreSQL server. If you're on Linux, that would be sudo service postgresql restart.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

Gradle proxy configuration

If this issue with HTTP error 407 happened to selected packages only then the problem is not in the proxy setting and internet connection. You even may expose your PC to the internet through NAT and still will face this problem. Typically at the same time you can download desired packages in browser. The only solution I find: delete the .gradle folder in your profile (not in the project). After that sync the project, it will take a long time but restore everything.

How to retrieve SQL result column value using column name in Python?

You didn't provide many details, but you could try something like this:

# conn is an ODBC connection to the DB
dbCursor = conn.cursor()
sql = ('select field1, field2 from table') 
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
    # Now you should be able to access the fields as properties of "row"
    myVar1 = row.field1
    myVar2 = row.field2
conn.close()

Display a jpg image on a JPanel

I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.

Here's Sun's docs on the subject matter.

What is difference between sleep() method and yield() method of multi threading?

yield(): yield method is used to pause the execution of currently running process so that other waiting thread with the same priority will get CPU to execute.Threads with lower priority will not be executed on yield. if there is no waiting thread then this thread will start its execution.

join(): join method stops currently executing thread and wait for another to complete on which in calls the join method after that it will resume its own execution.

For detailed explanation, see this link.

Paging with LINQ for objects

There are two main options:

.NET >= 4.0 Dynamic LINQ:

  1. Add using System.Linq.Dynamic; at the top.
  2. Use: var people = people.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();

You can also get it by NuGet.

.NET < 4.0 Extension Methods:

private static readonly Hashtable accessors = new Hashtable();

private static readonly Hashtable callSites = new Hashtable();

private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(string name) {
    var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];
    if(callSite == null)
    {
        callSites[name] = callSite = CallSite<Func<CallSite, object, object>>.Create(
                    Binder.GetMember(CSharpBinderFlags.None, name, typeof(AccessorCache),
                new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
    }
    return callSite;
}

internal static Func<dynamic,object> GetAccessor(string name)
{
    Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];
    if (accessor == null)
    {
        lock (accessors )
        {
            accessor = (Func<dynamic, object>)accessors[name];
            if (accessor == null)
            {
                if(name.IndexOf('.') >= 0) {
                    string[] props = name.Split('.');
                    CallSite<Func<CallSite, object, object>>[] arr = Array.ConvertAll(props, GetCallSiteLocked);
                    accessor = target =>
                    {
                        object val = (object)target;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            var cs = arr[i];
                            val = cs.Target(cs, val);
                        }
                        return val;
                    };
                } else {
                    var callSite = GetCallSiteLocked(name);
                    accessor = target =>
                    {
                        return callSite.Target(callSite, (object)target);
                    };
                }
                accessors[name] = accessor;
            }
        }
    }
    return accessor;
}
public static IOrderedEnumerable<dynamic> OrderBy(this IEnumerable<dynamic> source, string property)
{
    return Enumerable.OrderBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> OrderByDescending(this IEnumerable<dynamic> source, string property)
{
    return Enumerable.OrderByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenBy(this IOrderedEnumerable<dynamic> source, string property)
{
    return Enumerable.ThenBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenByDescending(this IOrderedEnumerable<dynamic> source, string property)
{
    return Enumerable.ThenByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}

Using jQuery how to get click coordinates on the target element

see here enter link description here

html

<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>

css

#myPosition{
  background-color:red;
  height:200px;
  width:200px;
}

jquery

$(document).ready(function(){
    $("#myPosition").click(function(e){
       var elm = $(this);
       var xPos = e.pageX - elm.offset().left;
       var yPos = e.pageY - elm.offset().top;
       alert("X position: " + xPos + ", Y position: " + yPos);
    });
});

Table is marked as crashed and should be repaired

Run this from your server's command line:

 mysqlcheck --repair --all-databases