Programs & Examples On #Nextval

PostgreSQL next value of the sequences?

I stumbled upon this question b/c I was trying to find the next sequence value by table. This didn't answer my question however this is how its done, and it may help those looking for the sequence value not by name but by table:

SELECT nextval(pg_get_serial_sequence('<your_table>', 'id')) AS new_id; 

Hope it helps :)

get next sequence value from database using hibernate

I found the solution:

public class DefaultPostgresKeyServer
{
    private Session session;
    private Iterator<BigInteger> iter;
    private long batchSize;

    public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
    {
        this.session=sess;
        batchSize = batchFetchSize;
        iter = Collections.<BigInteger>emptyList().iterator();
    }

        @SuppressWarnings("unchecked")
        public Long getNextKey()
        {
            if ( ! iter.hasNext() )
            {
                Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );

                iter = (Iterator<BigInteger>) query.list().iterator();
            }
            return iter.next().longValue() ;
        }

}

Access POST values in Symfony2 request object

Symfony doc to get request data

Finally, the raw data sent with the request body can be accessed using getContent():

$content = $request->getContent();

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Dealing with HTTP content in HTTPS pages

Simply: DO NOT DO IT. Http Content within a HTTPS page is inherently insecure. Point. This is why IE shows a warning. Getting rid of the warning is a stupid hogwash approach.

Instead, a HTTPS page should only have HTTPS content. Make sure the content can be loaded via HTTPS, too, and reference it via https if the page is loaded via https. For external content this will mean loading and caching the elements locally so that they are available via https - sure. No way around that, sadly.

The warning is there for a good reason. Seriously. Spend 5 minutes thinking how you could take over a https shown page with custom content - you will be surprised.

1064 error in CREATE TABLE ... TYPE=MYISAM

Try the below query

CREATE TABLE card_types (
  card_type_id int(11) NOT NULL auto_increment,
  name varchar(50) NOT NULL default '',
  PRIMARY KEY  (card_type_id),
) ENGINE = MyISAM ;

What Makes a Method Thread-safe? What are the rules?

There is no hard and fast rule.

Here are some rules to make code thread safe in .NET and why these are not good rules:

  1. Function and all functions it calls must be pure (no side effects) and use local variables. Although this will make your code thread-safe, there is also very little amount of interesting things you can do with this restriction in .NET.
  2. Every function that operates on a common object must lock on a common thing. All locks must be done in same order. This will make the code thread safe, but it will be incredibly slow, and you might as well not use multiple threads.
  3. ...

There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that is accessing common objects.

How to know a Pod's own IP address from inside a container in the Pod?

Even simpler to remember than the sed approach is to use awk.

Here is an example, which you can run on your local machine:

kubectl describe pod `<podName>` | grep IP | awk '{print $2}'

The IP itself is on column 2 of the output, hence $2 .

How to get all possible combinations of a list’s elements?

Have a look at itertools.combinations:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Since 2.6, batteries are included!

IntelliJ how to zoom in / out

Update: This answer is old. Intellij has since added actions to adjust font size. Check out Wilker's answer for assigning the new actions to keymaps.

Try Ctrl+Mouse Wheel which can be enabled under File > Settings... > Editor > General : Change font size (Zoom) with Ctrl+Mouse Wheel

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

Very sort cut and effective solution is below:-

Add the below rule in your tsconfig.json file:-

"noImplicitAny": false

Then restart your project.

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

SQL: How To Select Earliest Row

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow

Fast and simple String encrypt/decrypt in JAVA

Simplest way is to add this JAVA library using Gradle:

compile 'se.simbio.encryption:library:2.0.0'

You can use it as simple as this:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

ArrayList of String Arrays

I wouldn't use arrays. They're problematic for several reasons and you can't declare it in terms of a specific array size anyway. Try:

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

But honestly for addresses, I'd create a class to model them.

If you were to use arrays it would be:

List<String[]> addresses = new ArrayList<String[]>();

ie you can't declare the size of the array.

Lastly, don't declare your types as concrete types in instances like this (ie for addresses). Use the interface as I've done above. This applies to member variables, return types and parameter types.

PostgreSQL: insert from another table

For referential integtity :

insert into  main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
        (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
        (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
        'init-load'
       );

Delete the first three rows of a dataframe in pandas

You can use python slicing, but note it's not in-place.

In [15]: import pandas as pd
In [16]: import numpy as np
In [17]: df = pd.DataFrame(np.random.random((5,2)))
In [18]: df
Out[18]:
          0         1
0  0.294077  0.229471
1  0.949007  0.790340
2  0.039961  0.720277
3  0.401468  0.803777
4  0.539951  0.763267

In [19]: df[3:]
Out[19]:
          0         1
3  0.401468  0.803777
4  0.539951  0.763267

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

Had the same problem yesterday. Now, after signing to the developer portal, for every invalid provisioning profile have a button "Renew". After renewing and downloading updated provisioning profile all seems to work as expected, so problem is definitely solved :)

Update: you may have to contact Apple to get a "Renew"-button, or they removed it -- and the solution is to just download it and add it to the keychain, no need to renew.

Load local HTML file in a C# WebBrowser

Note that the file:/// scheme does not work on the compact framework, at least it doesn't with 5.0.

You will need to use the following:

string appDir = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, @"Documentation\index.html"));

?: ?? Operators Instead Of IF|ELSE

The ?: Operator returns one of two values depending on the value of a Boolean expression.

Condition-Expression ? Expression1 : Expression2

Find here more on ?: operator, also know as a Ternary Operator:

How to download a file with Node.js (without using third-party libraries)?

Download using promise, which resolve a readable stream. put extra logic to handle the redirect.

var http = require('http');
var promise = require('bluebird');
var url = require('url');
var fs = require('fs');
var assert = require('assert');

function download(option) {
    assert(option);
    if (typeof option == 'string') {
        option = url.parse(option);
    }

    return new promise(function(resolve, reject) {
        var req = http.request(option, function(res) {
            if (res.statusCode == 200) {
                resolve(res);
            } else {
                if (res.statusCode === 301 && res.headers.location) {
                    resolve(download(res.headers.location));
                } else {
                    reject(res.statusCode);
                }
            }
        })
        .on('error', function(e) {
            reject(e);
        })
        .end();
    });
}

download('http://localhost:8080/redirect')
.then(function(stream) {
    try {

        var writeStream = fs.createWriteStream('holyhigh.jpg');
        stream.pipe(writeStream);

    } catch(e) {
        console.error(e);
    }
});

What are DDL and DML?

DDL stands for Data Definition Language. DDL is used for defining structure of the table such as create a table or adding a column to table and even drop and truncate table. DML stands for Data Manipulation Language. As the name suggest DML used for manipulating the data of table. There are some commands in DML such as insert and delete.

List of <p:ajax> events

You can search for "Ajax Behavior Events" in PrimeFaces User's Guide, and you will find plenty of them for all supported components. That's also what PrimeFaces lead Optimus Prime suggest to do in this related question at the PrimeFaces forum <p:ajax> event list?

There is no onblur event, that's the HTML attribute name, but there is a blur event. It's just without the "on" prefix like as the HTML attribute name. You can also look at all "on*" attributes of the tag documentation of the component in question to see which are all available, e.g. <p:inputText>.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

In my case, I was trying to embed the Facebook SDK and I was having the wrong Application ID; thus the error was popping up. In your manifest file, you should have the proper meta data:

<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

This happened to me when I upgraded. I had to downgrade back.

react-redux ^5.0.6 ? ^7.1.3

PHP code to convert a MySQL query to CSV

If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)

These functions setup the headers:

function setExcelContentType() {
    if(headers_sent())
        return false;

    header('Content-type: application/vnd.ms-excel');
    return true;
}

function setDownloadAsHeader($filename) {
    if(headers_sent())
        return false;

    header('Content-disposition: attachment; filename=' . $filename);
    return true;
}

This one sends a CSV to a stream using a mysql result

function csvFromResult($stream, $result, $showColumnHeaders = true) {
    if($showColumnHeaders) {
        $columnHeaders = array();
        $nfields = mysql_num_fields($result);
        for($i = 0; $i < $nfields; $i++) {
            $field = mysql_fetch_field($result, $i);
            $columnHeaders[] = $field->name;
        }
        fputcsv($stream, $columnHeaders);
    }

    $nrows = 0;
    while($row = mysql_fetch_row($result)) {
        fputcsv($stream, $row);
        $nrows++;
    }

    return $nrows;
}

This one uses the above function to write a CSV to a file, given by $filename

function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
    $fp = fopen($filename, 'w');
    $rc = csvFromResult($fp, $result, $showColumnHeaders);
    fclose($fp);
    return $rc;
}

And this is where the magic happens ;)

function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
    setExcelContentType();
    setDownloadAsHeader($asFilename);
    return csvFileFromResult('php://output', $result, $showColumnHeaders);
}

For example:

$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);

How can I detect if a selector returns null?

This is in the JQuery documentation:

http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );

How to include a PHP variable inside a MySQL statement

The text inside $type is substituted directly into the insert string, therefore MySQL gets this:

... VALUES(testing, 'john', 'whatever')

Notice that there are no quotes around testing, you need to put these in like so:

$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");

I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

C# string reference type?

Above answers are helpful, I'd just like to add an example that I think is demonstrating clearly what happens when we pass parameter without the ref keyword, even when that parameter is a reference type:

MyClass c = new MyClass(); c.MyProperty = "foo";

CNull(c); // only a copy of the reference is sent 
Console.WriteLine(c.MyProperty); // still foo, we only made the copy null
CPropertyChange(c); 
Console.WriteLine(c.MyProperty); // bar


private void CNull(MyClass c2)
        {          
            c2 = null;
        }
private void CPropertyChange(MyClass c2) 
        {
            c2.MyProperty = "bar"; // c2 is a copy, but it refers to the same object that c does (on heap) and modified property would appear on c.MyProperty as well.
        }

How to view files in binary from bash?

$ echo -n 'Hello world!' | hd
00000000  48 65 6c 6c 6f 20 77 6f  72 6c 64 21              |Hello world!|
0000000c

C++ Array Of Pointers

What you want is:

Foo *array[10]; // array of 10 Foo pointers

Not to be confused with:

Foo (*array)[10]; // pointer to array of 10 Foos

In either case, nothing will be automatically initialized because these represent pointers to Foos that have yet to be assigned to something (e.g. with new).

I finally "got" pointer/array declaration syntax in C when I realized that it describes how you access the base type. Foo *array[5][10]; means that *array[0..4][0..9] (subscript on an array of 5 items, then subscript on an array of 10 items, then dereference as a pointer) will access a Foo object (note that [] has higher precedence than *).

This seems backwards. You would think that int array[5][10]; (a.k.a. int (array[5])[10];) is an array of 10 int array[5]. Suppose this were the case. Then you would access the last element of the array by saying array[9][4]. Doesn't that look backwards too? Because a C array declaration is a pattern indicating how to get to the base type (rather than a composition of array expressions like one might expect), array declarations and code using arrays don't have to be flipflopped.

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

Convert an integer to a float number

intutils.ToFloat32

// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
    return float32(in)
}

// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
    return float64(in)
}

What is the recommended way to delete a large number of items from DynamoDB?

My approach to delete all rows from a table i DynamoDb is just to pull all rows out from the table, using DynamoDbs ScanAsync and then feed the result list to DynamoDbs AddDeleteItems. Below code in C# works fine for me.

        public async Task DeleteAllReadModelEntitiesInTable()
    {
        List<ReadModelEntity> readModels;

        var conditions = new List<ScanCondition>();
        readModels = await _context.ScanAsync<ReadModelEntity>(conditions).GetRemainingAsync();

        var batchWork = _context.CreateBatchWrite<ReadModelEntity>();
        batchWork.AddDeleteItems(readModels);
        await batchWork.ExecuteAsync();
    }

Note: Deleting the table and then recreating it again from the web console may cause problems if using YAML/CloudFormation to create the table.

assembly to compare two numbers

Compare two numbers. If it equals Yes "Y", it prints No "N" on the screen if it is not equal. I am using emu8086. You can use the SUB or CMP command.

MOV AX,5h
MOV BX,5h
SUB AX,BX 
JZ EQUALS
JNZ NOTEQUALS

EQUALS:
MOV CL,'Y'
JMP PRINT

NOTEQUALS:
MOV CL,'N'

PRINT:
MOV AH,2
MOV DL,CL
INT 21H

RET

enter image description here

How to clear File Input

By Setting $("ID").val(null), worked for me

Converting an int or String to a char array on Arduino

  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

    char charBuf[50];
    stringOne.toCharArray(charBuf, 50)
    

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.0 and later do this:

View > Tool Windows > Device File Explorer

How to add an object to an array

The way I made object creator with auto list:

var list = [];

function saveToArray(x) {
    list.push(x);
};

function newObject () {
    saveToArray(this);
};

JSON.Net Self referencing loop detected

I am using Dot.Net Core 3.1 and did an search for

"Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property "

I am adding this to this question, as it will be an easy reference. You should use the following in the Startup.cs file:

 services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    // Use the default property (Pascal) casing
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });

How to output MySQL query results in CSV format?

To expand on previous answers, the following one-liner exports a single table as a tab-separated file. It's suitable for automation, exporting the database every day or so.

mysql -B -D mydatabase -e 'select * from mytable'

Conveniently, we can use the same technique to list out MySQL's tables, and to describe the fields on a single table:

mysql -B -D mydatabase -e 'show tables'

mysql -B -D mydatabase -e 'desc users'

Field   Type    Null    Key Default Extra
id  int(11) NO  PRI NULL    auto_increment
email   varchar(128)    NO  UNI NULL    
lastName    varchar(100)    YES     NULL    
title   varchar(128)    YES UNI NULL    
userName    varchar(128)    YES UNI NULL    
firstName   varchar(100)    YES     NULL    

Git undo changes in some files

Source : http://git-scm.com/book/en/Git-Basics-Undoing-Things

git checkout -- modifiedfile.java


1)$ git status

you will see the modified file

2)$git checkout -- modifiedfile.java

3)$git status

"elseif" syntax in JavaScript

if ( 100 < 500 ) {
   //any action
}
else if ( 100 > 500 ){
   //any another action
}

Easy, use space

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

As mentioned in a comment above, you can have expressions within the template strings/literals. Example:

_x000D_
_x000D_
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
_x000D_
_x000D_

How to make the overflow CSS property work with hidden as value

Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden as well, e.g.:

<div style="overflow: hidden">
  <div style="overflow: hidden">some text that should not overflow<div>
</div>

Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)

How do I launch a program from command line without opening a new cmd window?

If you're doing it via CMD as you say, then you can just enter the command like so:

path\to\your.exe 

which will open it within the same window. For example in C++:

system("path\\to\\your.exe"); // Double backslash for escaping

will open your.exe in the current CMD window. Likewise to start with a new window, just go for:

system("start path\\to\\your.exe");

If you go for the first option, you would have to clear your screen unless you wanted to have the command to open your.exe on the screen still.

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

Zabbix server is not running: the information displayed may not be current

I solved this problem on Ubuntu 18.04 by uninstalling Zabbix and reinstalling it again from scratch.

The initial installation didn't work because I had followed old posts/guides/tutorials, even from Zabbix documentation itself, so these might probably be outdated. So, the trick was to find and follow the most updated guide to Zabbix installation from its docs.

Here are the two links I followed for uninstalling and reinstalling Zabbix:

When installing Zabbix from the link above, your choosen Zabbix Version, OS Distribution, OS Version or Database may be different from the ones I've selected, but following the instructions on this page will probably be also the right way for you to install your chosen Zabbix configuration without getting errors post installation.

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

Change Tomcat Server's timeout in Eclipse

I have tomcat 8 Update 25 and tomcat 7 but facing the same issue it shows the message Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

How to store Node.js deployment settings/configuration files?

For those who are visiting this old thread here is a package I find to be good.

https://www.npmjs.org/package/config

Find out which remote branch a local branch is tracking

Yet another way

git status -b --porcelain

This will give you

## BRANCH(...REMOTE)
modified and untracked files

How to determine if Javascript array contains an object with an attribute that equals a given value?

To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var  objectsFound = [];

for(let objectNumber in productList){
    var currentId = productList[objectNumber].id;   
    if (theDatabaseList.some(obj => obj.id === currentId)) {
        // Do what you need to do with the matching value here
        objectsFound.push(currentId);
    }
}
console.log(objectsFound);

An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var objectsFound = [];

for(var i = 0; i < Object.keys(productList).length; i++){
        for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
        if(productList[i].id === theDatabaseList[j].id){
            objectsFound.push(productList[i].id);
        }       
    }
}
console.log(objectsFound);

To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.

var vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    } 
];

for(var ojectNumbers in vendors){
    if(vendors[ojectNumbers].Name === 'Magenic'){
        console.log('object contains Magenic');
    }
}

Format bytes to kilobytes, megabytes, gigabytes

I succeeded with following function,

    function format_size($size) {
        $mod = 1024;
        $units = explode(' ','B KB MB GB TB PB');
        for ($i = 0; $size > $mod; $i++) {
            $size /= $mod;
        }
        return round($size, 2) . ' ' . $units[$i];
    }

Debug vs Release in CMake

// CMakeLists.txt : release

set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)

// CMakeLists.txt : debug

set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

Google maps Places API V3 autocomplete - select first option on enter

Here is a solution that does not make a geocoding request that may return an incorrect result: http://jsfiddle.net/amirnissim/2D6HW/

It simulates a down-arrow keypress whenever the user hits return inside the autocomplete field. The ? event is triggered before the return event so it simulates the user selecting the first suggestion using the keyboard.

Here is the code (tested on Chrome and Firefox) :

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script>
    var pac_input = document.getElementById('searchTextField');

    (function pacSelectFirst(input) {
        // store the original event binding function
        var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;

        function addEventListenerWrapper(type, listener) {
            // Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
            // and then trigger the original listener.
            if (type == "keydown") {
                var orig_listener = listener;
                listener = function(event) {
                    var suggestion_selected = $(".pac-item-selected").length > 0;
                    if (event.which == 13 && !suggestion_selected) {
                        var simulated_downarrow = $.Event("keydown", {
                            keyCode: 40,
                            which: 40
                        });
                        orig_listener.apply(input, [simulated_downarrow]);
                    }

                    orig_listener.apply(input, [event]);
                };
            }

            _addEventListener.apply(input, [type, listener]);
        }

        input.addEventListener = addEventListenerWrapper;
        input.attachEvent = addEventListenerWrapper;

        var autocomplete = new google.maps.places.Autocomplete(input);

    })(pac_input);
</script>

Jquery sortable 'change' event element position

This works for me:

start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
update: function (event, ui) {
        var start_pos = ui.item.data('start_pos');
        var end_pos = ui.item.index();
        //$('#sortable li').removeClass('highlights');
    }

Converting any string into camel case

you can use this solution:

_x000D_
_x000D_
String.prototype.toCamelCase = function(){_x000D_
  return this.replace(/\s(\w)/ig, function(all, letter){return letter.toUpperCase();})_x000D_
             .replace(/(^\w)/, function($1){return $1.toLowerCase()});_x000D_
};_x000D_
_x000D_
console.log('Equipment className'.toCamelCase());
_x000D_
_x000D_
_x000D_

How can I write data in YAML format in a file?

Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

produces:

A: a
B:
  C: c
  D: d
  E: e

jQuery UI Dialog with ASP.NET button postback

Primarily it's because jQuery moves the dialog outside of the form tags using the DOM. Move it back inside the form tags and it should work fine. You can see this by inspecting the element in Firefox.

Unix command to check the filesize

ls -lh file.txt | awk '{ print $5 }'

Which characters make a URL invalid?

In your supplementary question you asked if www.example.com/file[/].html is a valid URL.

That URL isn't valid because a URL is a type of URI and a valid URI must have a scheme like http: (see RFC 3986).

If you meant to ask if http://www.example.com/file[/].html is a valid URL then the answer is still no because the square bracket characters aren't valid there.

The square bracket characters are reserved for URLs in this format: http://[2001:db8:85a3::8a2e:370:7334]/foo/bar (i.e. an IPv6 literal instead of a host name)

It's worth reading RFC 3986 carefully if you want to understand the issue fully.

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

Adding the following block of code in web.config solves my problem

 <system.net>
    <defaultProxy enabled="false" >
    </defaultProxy>
  </system.net>

how to set font size based on container size?

It cannot be accomplished with css font-size

Assuming that "external factors" you are referring to could be picked up by media queries, you could use them - adjustments will likely have to be limited to a set of predefined sizes.

Difference between `constexpr` and `const`

I don't think any of the answers really make it clear exactly what side effects it has, or indeed, what it is.

constexpr and const at namespace/file-scope are identical when initialised with a literal or expression; but with a function, const can be initialised by any function, but constexpr initialised by a non-constexpr (a function that isn't marked with constexpr or a non constexpr expression) will generate a compiler error. Both constexpr and const are implicitly internal linkage for variables (well actually, they don't survive to get to the linking stage if compiling -O1 and stronger, and static doesn't force the compiler to emit an internal (local) linker symbol for const or constexpr when at -O1 or stronger; the only time it does this is if you take the address of the variable. const and constexpr will be an internal symbol unless expressed with extern i.e. extern constexpr/const int i = 3; needs to be used). On a function, constexpr makes the function permanently never reach the linking stage (regardless of extern or inline in the definition or -O0 or -Ofast), whereas const never does, and static and inline only have this effect on -O1 and above. When a const/constexpr variable is initialised by a constexpr function, the load is always optimised out with any optimisation flag, but it is never optimised out if the function is only static or inline, or if the variable is not a const/constexpr.

Standard compilation (-O0)

#include<iostream>
constexpr int multiply (int x, int y)
{

  return x * y;
}

extern const int val = multiply(10,10);
int main () {
  std::cout << val;
} 

compiles to

val:
        .long   100  //extra external definition supplied due to extern

main:
        push    rbp
        mov     rbp, rsp
        mov     esi, 100 //substituted in as an immediate
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
        mov     eax, 0
        pop     rbp
        ret

__static_initialization_and_destruction_0(int, int):
        . 
        . 
        . 

However

#include<iostream>
const int multiply (int x, int y)
{

  return x * y;
}

const int val = multiply(10,10); //constexpr is an error
int main () {
  std::cout << val;
}

Compiles to

multiply(int, int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     DWORD PTR [rbp-8], esi
        mov     eax, DWORD PTR [rbp-4]
        imul    eax, DWORD PTR [rbp-8]
        pop     rbp
        ret

main:
        push    rbp
        mov     rbp, rsp
        mov     eax, DWORD PTR val[rip]
        mov     esi, eax
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
        mov     eax, 0
        pop     rbp
        ret

__static_initialization_and_destruction_0(int, int):
        . 
        . 
        . 
        mov     esi, 10
        mov     edi, 10
        call    multiply(int, int)
        mov     DWORD PTR val[rip], eax

This clearly shows that constexpr causes the initialisation of the const/constexpr file-scope variable to occur at compile time and produce no global symbol, whereas not using it causes initialisation to occur before main at runtime.

Compiling using -Ofast

Even -Ofast doesn't optimise out the load! https://godbolt.org/z/r-mhif, so you need constexpr


constexpr functions can also be called from inside other constexpr functions for the same result. constexpr on a function also prevents use of anything that can't be done at compile time in the function; for instance, a call to the << operator on std::cout.

constexpr at block scope behaves the same in that it produces an error if initialised by a non-constexpr function; the value is also substituted in immediately.

In the end, its main purpose is like C's inline function, but it is only effective when the function is used to initialise file-scope variables (which functions cannot do on C, but they can on C++ because it allows dynamic initialisation of file-scope variables), except the function cannot export a global/local symbol to the linker as well, even using extern/static, which you could with inline on C; block-scope variable assignment functions can be inlined simply using an -O1 optimisation without constexpr on C and C++.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

As noted in the official documentation, simply apply the class(es) btn btn-link:

<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>

For example, with the code you have provided:

_x000D_
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<form action="..." method="post">_x000D_
  <div class="row-fluid">_x000D_
    <!-- Navigation for the form -->_x000D_
    <div class="span3">_x000D_
      <ul class="nav nav-tabs nav-stacked">_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 1">Link 1</button>_x000D_
        </li>_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 2">Link 2</button>_x000D_
        </li>_x000D_
        <!-- ... -->_x000D_
      </ul>_x000D_
    </div>_x000D_
    <!-- The actual form -->_x000D_
    <div class="span9">_x000D_
      <!-- ... -->_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

http://localhost/ not working on Windows 7. What's the problem?

Yea, this was a pain for me as well.

So what i did was find the "Start Wampserver", just hit the start button and type it in.

Then right click on it , select properties. I set it to run in XP servive pack 3 on the capatability tab. I also checked the box "Run this program as an administrator".

Then I right clicked the WAMPSERVER on the System Tray, and re-started all services. This worked perfect for me, hope this will help you as well.

Rob

What is the difference between const and readonly in C#?

Const: Absolute constant value during the application life time.

Readonly: It can be changed in running time.

jQuery datepicker to prevent past date

Give zero to mindate and it'll disabale past dates.

$( "#datepicker" ).datepicker({ minDate: 0});

Live example

read more here

How to send password securely over HTTP?

I would use a server-side and client-side Diffie-Hellman key exchange system with AJAX or multiple form submits(I recommend the former), although I don't see any good implementations thereof on the internet. Remember that a JS library can always be corrupted or changed by MITM. Local storage can be used to help combat this, to an extent.

Converting newline formatting from Mac to Windows

  1. Install dos2unix with homebrew
  2. Run find ./ -type f -exec dos2unix {} \; to recursively convert all line-endings within current folder

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

How can I combine two HashMap objects containing the same types?

    HashMap<Integer,String> hs1 = new HashMap<>();
    hs1.put(1,"ram");
    hs1.put(2,"sita");
    hs1.put(3,"laxman");
    hs1.put(4,"hanuman");
    hs1.put(5,"geeta");

    HashMap<Integer,String> hs2 = new HashMap<>();
    hs2.put(5,"rat");
    hs2.put(6,"lion");
    hs2.put(7,"tiger");
    hs2.put(8,"fish");
    hs2.put(9,"hen");

    HashMap<Integer,String> hs3 = new HashMap<>();//Map is which we add

    hs3.putAll(hs1);
    hs3.putAll(hs2);

    System.out.println(" hs1 : " + hs1);
    System.out.println(" hs2 : " + hs2);
    System.out.println(" hs3 : " + hs3);

Duplicate items will not be added(that is duplicate keys) as when we will print hs3 we will get only one value for key 5 which will be last value added and it will be rat. **[Set has a property of not allowing the duplicate key but values can be duplicate]

Capture screenshot of active window?

KvanTTT's code worked great. I extended it a bit to allow a little more flexibility on save format, as well as the ability to save by hWnd, .NET Control/Form. You can get a bitmap or save to file, with a few options.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MosaiqPerformanceMonitor {
     public enum CaptureMode {
          Screen, Window
     }

     public static class ScreenCapturer {
          [DllImport("user32.dll")]
          private static extern IntPtr GetForegroundWindow();

          [DllImport("user32.dll")]
          private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

          [StructLayout(LayoutKind.Sequential)]
          private struct Rect {
                public int Left;
                public int Top;
                public int Right;
                public int Bottom;
          }

          [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
          public static extern IntPtr GetDesktopWindow();

          /// <summary> Capture Active Window, Desktop, Window or Control by hWnd or .NET Contro/Form and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, CaptureMode mode = CaptureMode.Window, ImageFormat format = null) {
                ImageSave(filename, format, Capture(mode));
          }

          /// <summary> Capture a specific window (or control) and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="handle">hWnd (handle) of the window to capture</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, IntPtr handle, ImageFormat format = null) {
                ImageSave(filename, format, Capture(handle));
          }

          /// <summary> Capture a specific window (or control) and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="c">Object to capture</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, Control c, ImageFormat format = null) {
                ImageSave(filename, format, Capture(c));
          }
          /// <summary> Capture the active window (default) or the desktop and return it as a bitmap </summary>
          /// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
          public static Bitmap Capture(CaptureMode mode = CaptureMode.Window) {
                return Capture(mode == CaptureMode.Screen ? GetDesktopWindow() : GetForegroundWindow());
          }

          /// <summary> Capture a .NET Control, Form, UserControl, etc. </summary>
          /// <param name="c">Object to capture</param>
          /// <returns> Bitmap of control's area </returns>
          public static Bitmap Capture(Control c) {
                return Capture(c.Handle);
          }


          /// <summary> Capture a specific window and return it as a bitmap </summary>
          /// <param name="handle">hWnd (handle) of the window to capture</param>
          public static Bitmap Capture(IntPtr handle) {
                Rectangle bounds;
                var rect = new Rect();
                GetWindowRect(handle, ref rect);
                bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
                CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);

                var result = new Bitmap(bounds.Width, bounds.Height);
                using (var g = Graphics.FromImage(result))
                     g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);

                return result;
          }

          /// <summary> Position of the cursor relative to the start of the capture </summary>
          public static Point CursorPosition;


          /// <summary> Save an image to a specific file </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          /// <param name="image">Image to save.  Usually a BitMap, but can be any
          /// Image.</param>
          static void ImageSave(string filename, ImageFormat format, Image image) {
                format = format ?? ImageFormat.Png;
                if (!filename.Contains("."))
                     filename = filename.Trim() + "." + format.ToString().ToLower();

                if (!filename.Contains(@"\"))
                     filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ?? @"C:\Temp", filename);

                filename = filename.Replace("%NOW%", DateTime.Now.ToString("[email protected]"));
                image.Save(filename, format);
          }
     }
}

How to configure XAMPP to send mail from localhost?

I tried many ways to send a mail from XAMPP Localhost, but since XAMPP hasn't SSL Certificate, my email request blocked by Gmail or similar SMTP Service providers.

Then I used MailHog for local smtp server, what you need to do is just run it. localhost:1025 is for smtp server, localhost:8025 is for mail server, where you can check the emails you sent.

here is my code:

    require_once "src/PHPMailer.php";
    require_once "src/SMTP.php";
    require_once "src/Exception.php";

    $mail = new PHPMailer\PHPMailer\PHPMailer();

      //Server settings
    $mail->SMTPDebug = 3;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'localhost';                    // Set the SMTP server to send through
    $mail->Port       = 1025;                                    // TCP port to connect to
    // $mail->Username   = '';                     // SMTP username
    // $mail->Password   = '';                               // SMTP password
    // $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    // $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');     // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }

MailHog Github Repository link

How to handle change of checkbox using jQuery?

$('#myForm').on('change', 'input[type=checkbox]', function() {
    this.checked ? this.value = 'apple' : this.value = 'pineapple';
});

Hibernate JPA Sequence (non-Id)

I run in the same situation like you and I also didn't find any serious answers if it is basically possible to generate non-id propertys with JPA or not.

My solution is to call the sequence with a native JPA query to set the property by hand before persisiting it.

This is not satisfying but it works as a workaround for the moment.

Mario

How to save picture to iPhone photo library?

The simplest way is:

UIImageWriteToSavedPhotosAlbum(myUIImage, nil, nil, nil);

For Swift, you can refer to Saving to the iOS photo library using swift

Best way to center a <div> on a page vertically and horizontally?

Here is a script i wrote a while back (it is written using the jQuery library):

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
        return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};

How do I strip all spaces out of a string in PHP?

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

Excel - programm cells to change colour based on another cell

  1. Select cell B3 and click the Conditional Formatting button in the ribbon and choose "New Rule".
  2. Select "Use a formula to determine which cells to format"
  3. Enter the formula: =IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE), and choose to fill green when this is true
  4. Create another rule and enter the formula =IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE) and choose to fill red when this is true.

More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF formula to return true or false based on the values of any cells.

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

how to set value of a input hidden field through javascript?

You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value=""> to the beginning.

What is "android.R.layout.simple_list_item_1"?

android.R.layout.simple_list_item_1, this is row layout file in your res/layout folder which contains the corresponding design for your row in listview. Now we just bind the array list items to the row layout by using mylistview.setadapter(aa);

Is it possible to have multiple styles inside a TextView?

As stated, use TextView.setText(Html.fromHtml(String))

And use these tags in your Html formatted string:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>

http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

How to set up a cron job to run an executable every hour?

0 * * * * cd folder_containing_exe && ./exe_name

should work unless there is something else that needs to be setup for the program to run.

How to select bottom most rows?

All you need to do is reverse your ORDER BY. Add or remove DESC to it.

unique combinations of values in selected columns in pandas data frame and count

Placing @EdChum's very nice answer into a function count_unique_index. The unique method only works on pandas series, not on data frames. The function below reproduces the behavior of the unique function in R:

unique returns a vector, data frame or array like x but with duplicate elements/rows removed.

And adds a count of the occurrences as requested by the OP.

df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],                                                                                             
                    'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})                                                                                               
def count_unique_index(df, by):                                                                                                                                                 
    return df.groupby(by).size().reset_index().rename(columns={0:'count'})                                                                                                      

count_unique_index(df1, ['A','B'])                                                                                                                                              
     A    B  count                                                                                                                                                                  
0   no   no      1                                                                                                                                                                  
1   no  yes      2                                                                                                                                                                  
2  yes   no      4                                                                                                                                                                  
3  yes  yes      3

Format numbers in thousands (K) in Excel

Non-Americans take note! If you use Excel with "." as 1000 separator, you need to replace the "," with a "." in the formula, such as:

[>=1000]€ #.##0." K";[<=-1000]-€ #.##0." K";0

The code above will display € 62.123 as "€ 62 K".

How to make Bootstrap 4 cards the same height in card-columns?

jsfiddle

Just add the height you want with CSS, example:

.card{
    height: 350px;
}

You will have to add your own CSS.

If you check the documentation, this is for Masonry style - the point of that is they are not all the same height.

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

Jenkins / Hudson environment variables

Running the command with environment variable set is also effective. Of course, you have to do it for each command you run, but you probably have a job script, so you probably only have one command per build. My job script is a python script that uses the environment to decide which python to use, so I still needed to put /usr/local/bin/python2.7 in its path:

PATH=/usr/local/bin <my-command>

Using :: in C++

The :: are used to dereference scopes.

const int x = 5;

namespace foo {
  const int x = 0;
}

int bar() {
  int x = 1;
  return x;
}

struct Meh {
  static const int x = 2;
}

int main() {
  std::cout << x; // => 5
  {
    int x = 4;
    std::cout << x; // => 4
    std::cout << ::x; // => 5, this one looks for x outside the current scope
  }
  std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
  std::cout << foo::x; // => 0, use the definition of x inside foo
  std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}

unrelated: cout and cin are not functions, but instances of stream objects.

EDIT fixed as Keine Lust suggested

how to release localhost from Error: listen EADDRINUSE

One possible solution that worked for me was simply to close the window in browser where I had the corresponding "http://localhost:3000/" script running.

Pass correct "this" context to setTimeout callback?

There are ready-made shortcuts (syntactic sugar) to the function wrapper @CMS answered with. (Below assuming that the context you want is this.tip.)


ECMAScript 2015 (all common browsers and smartphones, Node.js 5.0.0+)

For virtually all javascript development (in 2020) you can use fat arrow functions, which are part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification.

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value [...].

(param1, param2, ...rest) => { statements }

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(() => { this.tip.destroy(); }, 1000);
}

ECMAScript 5 (older browsers and smartphones, Node.js) and Prototype.js

If you target browser compatible with ECMA-262, 5th edition (ECMAScript 5) or Node.js, which (in 2020) means all common browsers as well as older browsers, you could use Function.prototype.bind. You can optionally pass any function arguments to create partial functions.

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Again, in your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(this.tip.destroy.bind(this.tip), 1000);
}

The same functionality has also been implemented in Prototype (any other libraries?).

Function.prototype.bind can be implemented like this if you want custom backwards compatibility (but please observe the notes).


jQuery

If you are already using jQuery 1.4+, there's a ready-made function for explicitly setting the this context of a function.

jQuery.proxy(): Takes a function and returns a new one that will always have a particular context.

$.proxy(function, context[, additionalArguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}

Underscore.js, lodash

It's available in Underscore.js, as well as lodash, as _.bind(...)1,2

bind Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application.

_.bind(function, object, [*arguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}

Mysql Compare two datetime fields

The query you want to show as an example is:

SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';

04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.

If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.

To make things a bit clearer, try this:

SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;

That will show you the date, and its 12hr time.

Is it wrong to place the <script> tag after the </body> tag?

Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.

SQL-Server: The backup set holds a backup of a database other than the existing

First create a blank database of the same name. Then go for the restore option

Under Options on the left pane don't forget to select

  • Overwrite the existing database
  • Preserve the replication settings

enter image description here

That's it

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

How to pass data to view in Laravel?

For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way

In the controller, you define the variables you want to pass as global and you attribute the values to these variables.

Example global $variable; $variable = 1;

And now in the view, at the top, simply do

<?php global $variable;?>

Then you can now call your variable from any where in the view for example

{{$variable}}

hope this helps someone.

Adding a right click menu to an item

Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.

cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));

Rails 3 execute custom sql query without a model

Maybe try this:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)

How do I parse JSON in Android?

Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.

Get your JSON:

Assume you have a json string

String result = "{\"someKey\":\"someValue\"}";

Create a JSONObject:

JSONObject jObject = new JSONObject(result);

If your json string is an array, e.g.:

String result = "[{\"someKey\":\"someValue\"}]"

then you should use JSONArray as demonstrated below and not JSONObject

To get a specific string

String aJsonString = jObject.getString("STRINGNAME");

To get a specific boolean

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");

To get a specific integer

int aJsonInteger = jObject.getInt("INTEGERNAME");

To get a specific long

long aJsonLong = jObject.getLong("LONGNAME");

To get a specific double

double aJsonDouble = jObject.getDouble("DOUBLENAME");

To get a specific JSONArray:

JSONArray jArray = jObject.getJSONArray("ARRAYNAME");

To get the items from the array

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

I once ran into this situation and I had the dependencies in classpath. The solution was to include javax.mail and javax.activation libraries in the container's (eg. tomcat) lib folder. Using maven -set them to provided scope and it should work. You will have shared email libs in classpath for all projects.

Useful source: http://haveacafe.wordpress.com/2008/09/26/113/

Text file with 0D 0D 0A line breaks

Just saying, this is also the value (kind of...) that is returned from php upon:

<?php var_dump(urlencode(PHP_EOL)); ?> 
    // Prints: string '%0D%0A' (length=6)-- used in 5.4.24 at least

xpath find if node exists

<xsl:if test="xpath-expression">...</xsl:if>

so for example

<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

How to get value from form field in django framework?

I use django 1.7+ and python 2.7+, the solution above dose not work. And the input value in the form can be got use POST as below (use the same form above):

if form.is_valid():
  data = request.POST.get('my_form_field_name')
  print data

Hope this helps.

Format in kotlin string templates

As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format())

See Kotlin's documentation

Your code would be:

val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)

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

Use a post-build action in your project, and add the commands to copy the offending DLL. The post-build action are written as a batch script.

The output directory can be referenced as $(OutDir). The project directory is available as $(ProjDir). Try to use relative pathes where applicable, so that you can copy or move your project folder without breaking the post-build action.

Why does the 'int' object is not callable error occur when using the sum() function?

You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.

To fix this, restart your interpreter.

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168

If you shadow the sum builtin, you can get the error you are seeing

>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Also, note that sum will work fine on the set there is no need to convert it to a list

pandas get column average/mean

Do note that it needs to be in the numeric data type in the first place.

 import pandas as pd
 df['column'] = pd.to_numeric(df['column'], errors='coerce')

Next find the mean on one column or for all numeric columns using describe().

df['column'].mean()
df.describe()

Example of result from describe:

          column 
count    62.000000 
mean     84.678548 
std     216.694615 
min      13.100000 
25%      27.012500 
50%      41.220000 
75%      70.817500 
max    1666.860000

How do I copy the contents of a String to the clipboard in C#?

Using the solution showed in this question, System.Windows.Forms.Clipboard.SetText(...), results in the exception:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

To prevent this, you can add the attribute:

[STAThread]

to

static void Main(string[] args)

Is it possible to insert HTML content in XML document?

Please see this.

Text inside a CDATA section will be ignored by the parser.

http://www.w3schools.com/xml/dom_cdatasection.asp

This is will help you to understand the basics about XML

How to export query result to csv in Oracle SQL Developer?

To take an export to your local system from sql developer.

Path : C:\Source_Table_Extract\des_loan_due_dtls_src_boaf.csv

    SPOOL "Path where you want to save the file"
    SELECT /*csv*/ * FROM TABLE_NAME;

Vue.js—Difference between v-model and v-bind

v-model is for two way bindings means: if you change input value, the bound data will be changed and vice versa. But v-bind:value is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.

v-model is intended to be used with form elements. It allows you to tie the form element (e.g. a text input) with the data object in your Vue instance.

Example: https://jsfiddle.net/jamesbrndwgn/j2yb9zt1/1/

v-bind is intended to be used with components to create custom props. This allows you to pass data to a component. As the prop is reactive, if the data that’s passed to the component changes then the component will reflect this change

Example: https://jsfiddle.net/jamesbrndwgn/ws5kad1c/3/

Hope this helps you with basic understanding.

In Unix, how do you remove everything in the current directory and below it?

make sure you are in the correct directory

rm -rf *

Android get current Locale, not default

If you are using the Android Support Library you can use ConfigurationCompat instead of @Makalele's method to get rid of deprecation warnings:

Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);

or in Kotlin:

val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]

What is the difference between C and embedded C?

Embedded environment, sometime, there is no MMU, less memory, less storage space. In C programming level, almost same, cross compiler do their job.

Check if an array contains duplicate values

This should work with only one loop:

function checkIfArrayIsUnique(arr) {
    var map = {}, i, size;

    for (i = 0, size = arr.length; i < size; i++){
        if (map[arr[i]]){
            return false;
        }

        map[arr[i]] = true;
    }

    return true;
}

How do I read all classes from a Java package in the classpath?

eXtcos looks promising. Imagine you want to find all the classes that:

  1. Extend from class "Component", and store them
  2. Are annotated with "MyComponent", and
  3. Are in the “common” package.

With eXtcos this is as simple as

ClasspathScanner scanner = new ClasspathScanner();
final Set<Class> classStore = new ArraySet<Class>();

Set<Class> classes = scanner.getClasses(new ClassQuery() {
    protected void query() {
        select().
        from(“common”).
        andStore(thoseExtending(Component.class).into(classStore)).
        returning(allAnnotatedWith(MyComponent.class));
    }
});

How to zoom div content using jquery?

@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.

    var currentZoom = 1.0;

    $(document).ready(function () {
        $('#btn_ZoomIn').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
            })
        $('#btn_ZoomOut').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
            })
        $('#btn_ZoomReset').click(
            function () {
                currentZoom = 1.0
                $('#divName').animate({ 'zoom': 1 }, 'slow');
            })
    });

How can you get the Manifest Version number from the App's (Layout) XML variables?

I believe that was already answered here.

String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

OR

int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

Setting default value in select drop-down using Angularjs

Some of the scenarios, object.item would not be loaded or will be undefined.

Use ng-init

<select ng-init="object.item=2" ng-model="object.item"
ng-options="item.id as item.name for item in list"

How do you replace double quotes with a blank space in Java?

Strings are immutable, so you need to say

sInputString = sInputString("\"","");

not just the right side of the =

TypeError: string indices must be integers, not str // working with dict

I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

from itertools import chain

def involved(courses, person):
    courses_info = chain.from_iterable(x.values() for x in courses.values())
    return filter(lambda x: x['teacher'] == person, courses_info)

print involved(courses, 'Dave')

The first thing I do is getting the list of the courses and then filter by teacher's name.

Print "hello world" every X seconds

For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs.

See tutorials for Quartz scheduling.

How do I store an array in localStorage?

The localStorage and sessionStorage can only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}

Use localStorage.setObj(key, value) to save an array or object and localStorage.getObj(key) to retrieve it. The same methods work with the sessionStorage object.

If you just use the new methods to access the storage, every value will be converted to a JSON-string before saving and parsed before it is returned by the getter.

Source: http://www.acetous.de/p/152

Appending to an existing string

Can I ask why this is important?

I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.

You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

Trim to remove white space

or just use $.trim(str)

How to set timeout in Retrofit library?

I am using Retrofit 1.9 to obtain a XML.

public class ServicioConexionRetrofitXML {

    public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
    public static final long tiempoMaximoRespuestaSegundos = 60;
    public static final long tiempoMaximoLecturaSegundos = 100;
    public static final OkHttpClient clienteOkHttp = new OkHttpClient();


    private static RestAdapter.Builder builder = new RestAdapter.Builder().
            setEndpoint(API_BASE_URL).
            setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());


    public static <S> S createService(Class<S> serviceClass) {
        clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
        clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }

}

If you are using Retrofit 1.9.0 and okhttp 2.6.0, add to your Gradle file.

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    // Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
    // en conflicto.
    compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }

Note: If you need to fetch a JSON, just remove from code above.

.setConverter(new SimpleXMLConverter())

Java: Find .txt files in specified folder

You can use the listFiles() method provided by the java.io.File class.

import java.io.File;
import java.io.FilenameFilter;

public class Filter {

    public File[] finder( String dirName){
        File dir = new File(dirName);

        return dir.listFiles(new FilenameFilter() { 
                 public boolean accept(File dir, String filename)
                      { return filename.endsWith(".txt"); }
        } );

    }

}

Deny access to one specific folder in .htaccess

You can do this dynamically that way:

mkdir($dirname);
@touch($dirname . "/.htaccess");
  $f = fopen($dirname . "/.htaccess", "w");
  fwrite($f, "deny from all");
fclose($f);

Extending the User model with custom fields in Django

It's too late, but my answer is for those who search for a solution with a recent version of Django.

models.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    extra_Field_1 = models.CharField(max_length=25, blank=True)
    extra_Field_2 = models.CharField(max_length=25, blank=True)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

you can use it in templates like this:

<h2>{{ user.get_full_name }}</h2>
<ul>
  <li>Username: {{ user.username }}</li>
  <li>Location: {{ user.profile.extra_Field_1 }}</li>
  <li>Birth Date: {{ user.profile.extra_Field_2 }}</li>
</ul>

and in views.py like this:

def update_profile(request, user_id):
    user = User.objects.get(pk=user_id)
    user.profile.extra_Field_1 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...'
    user.save()

"PKIX path building failed" and "unable to find valid certification path to requested target"

For me, certificate error popped up because I had fiddler running in background and that messes up with certificate. It acts as a proxy so close that and restart eclipse.

How can I view the contents of an ElasticSearch index?

I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.

Just make sure you set cors values in elasticsearch.yml appropiate.

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

In Tkinter is there any way to make a widget not visible?

One option, as explained in another answer, is to use pack_forget or grid_forget. Another option is to use lift and lower. This changes the stacking order of widgets. The net effect is that you can hide widgets behind sibling widgets (or descendants of siblings). When you want them to be visible you lift them, and when you want them to be invisible you lower them.

The advantage (or disadvantage...) is that they still take up space in their master. If you "forget" a widget, the other widgets might readjust their size or orientation, but if you raise or lower them they will not.

Here is a simple example:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.frame = tk.Frame(self)
        self.frame.pack(side="top", fill="both", expand=True)
        self.label = tk.Label(self, text="Hello, world")
        button1 = tk.Button(self, text="Click to hide label",
                           command=self.hide_label)
        button2 = tk.Button(self, text="Click to show label",
                            command=self.show_label)
        self.label.pack(in_=self.frame)
        button1.pack(in_=self.frame)
        button2.pack(in_=self.frame)

    def show_label(self, event=None):
        self.label.lift(self.frame)

    def hide_label(self, event=None):
        self.label.lower(self.frame)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

Set default option in mat-select

On your typescript file, just assign this domain on modeSelect on Your ngOnInit() method like below:



 ngOnInit() {
        this.modeSelect = "domain";
      }

And on your html, use your select list.

<mat-form-field>
        <mat-select  [(value)]="modeSelect" placeholder="Mode">
          <mat-option value="domain">Domain</mat-option>
          <mat-option value="exact">Exact</mat-option>
        </mat-select>
      </mat-form-field>

Makefiles with source files in different directories

If the sources are spread in many folders, and it makes sense to have individual Makefiles then as suggested before, recursive make is a good approach, but for smaller projects I find it easier to list all the source files in the Makefile with their relative path to the Makefile like this:

# common sources
COMMON_SRC := ./main.cpp \
              ../src1/somefile.cpp \
              ../src1/somefile2.cpp \
              ../src2/somefile3.cpp \

I can then set VPATH this way:

VPATH := ../src1:../src2

Then I build the objects:

COMMON_OBJS := $(patsubst %.cpp, $(ObjDir)/%$(ARCH)$(DEBUG).o, $(notdir $(COMMON_SRC)))

Now the rule is simple:

# the "common" object files
$(ObjDir)/%$(ARCH)$(DEBUG).o : %.cpp Makefile
    @echo creating $@ ...
    $(CXX) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $<

And building the output is even easier:

# This will make the cbsdk shared library
$(BinDir)/$(OUTPUTBIN): $(COMMON_OBJS)
    @echo building output ...
    $(CXX) -o $(BinDir)/$(OUTPUTBIN) $(COMMON_OBJS) $(LFLAGS)

One can even make the VPATH generation automated by:

VPATH := $(dir $(COMMON_SRC))

Or using the fact that sort removes duplicates (although it should not matter):

VPATH := $(sort  $(dir $(COMMON_SRC)))

how to remove key+value from hash in javascript

You're looking for delete:

delete myhash['key2']

See the Core Javascript Guide

How to add an object to an ArrayList in Java

You have to use new operator here to instantiate. For example:

Contacts.add(new Data(name, address, contact));

Print newline in PHP in single quotes

The only escape sequence you can use in single quotes is for the single quote itself.

$foo = 'That\'s great';

The only way you could insert a new line into a string created with single quotes is to insert a literal newline

$bar = 'That\'s
cheating';

Add string in a certain position in Python

No. Python Strings are immutable.

>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

It is, however, possible to create a new string that has the inserted character:

>>> s[:4] + '-' + s[4:]
'3558-79ACB6'

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

Try This:

It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
    var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

Its not exactly what you were looking for, but may be it can help you somewhere.

std::vector versus std::array in C++

To emphasize a point made by @MatteoItalia, the efficiency difference is where the data is stored. Heap memory (required with vector) requires a call to the system to allocate memory and this can be expensive if you are counting cycles. Stack memory (possible for array) is virtually "zero-overhead" in terms of time, because the memory is allocated by just adjusting the stack pointer and it is done just once on entry to a function. The stack also avoids memory fragmentation. To be sure, std::array won't always be on the stack; it depends on where you allocate it, but it will still involve one less memory allocation from the heap compared to vector. If you have a

  • small "array" (under 100 elements say) - (a typical stack is about 8MB, so don't allocate more than a few KB on the stack or less if your code is recursive)
  • the size will be fixed
  • the lifetime is in the function scope (or is a member value with the same lifetime as the parent class)
  • you are counting cycles,

definitely use a std::array over a vector. If any of those requirements is not true, then use a std::vector.

How do I get the last day of a month?

This formula reflects @RHSeeger's thought as a simple solution to get (in this example) the last day of the 3rd month (month of date in cell A1 + 4 with the first day of that month minus 1 day):

=DATE(YEAR(A1);MONTH(A1)+4;1)-1

Very precise, inclusive February's in leap years :)

Optimistic vs. Pessimistic locking

Lot of good things have been said above about optimistic and pessimistic locking. One important point to consider is as follows:

When using optimistic locking, we need to cautious of the fact that how will application recover from these failures.

Specially in asynchronous message driven architectures, this can lead of out of order message processing or lost updates.

Failures scenarios need to be thought through.

MySQL error 2006: mysql server has gone away

I found the solution to "#2006 - MySQL server has gone away" this error. Solution is just you have to check two files

  1. config.inc.php
  2. config.sample.inc.php

Path of these files in windows is

C:\wamp64\apps\phpmyadmin4.6.4

In these two files the value of this:

$cfg['Servers'][$i]['host']must be 'localhost' .

In my case it was:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

change it to:

"$cfg['Servers'][$i]['host']" = 'localhost';

Make sure in both:

  1. config.inc.php
  2. config.sample.inc.php files it must be 'localhost'.

And last set:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

Then restart Wampserver.


To change phpmyadmin user name and password

You can directly change the user name and password of phpmyadmin through config.inc.php file

These two lines

$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';

Here you can give new user name and password. After changes save the file and restart WAMP server.

Check if a process is running or not on Windows with Python

There is a python module called wmi.

import wmi
c=wmi.WMI()
def check_process_running(str_):
    if(c.Win32_Process(name=str_)):
        print("Process is running")
    else:
        print("Process is not running")

         
check_process_running("yourprocess.exe")  

What does "Content-type: application/json; charset=utf-8" really mean?

To substantiate @deceze's claim that the default JSON encoding is UTF-8...

From IETF RFC4627:

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.

      00 00 00 xx  UTF-32BE
      00 xx 00 xx  UTF-16BE
      xx 00 00 00  UTF-32LE
      xx 00 xx 00  UTF-16LE
      xx xx xx xx  UTF-8

Shortcut to Apply a Formula to an Entire Column in Excel

If the formula already exists in a cell you can fill it down as follows:

  • Select the cell containing the formula and press CTRL+SHIFT+DOWN to select the rest of the column (CTRL+SHIFT+END to select up to the last row where there is data)
  • Fill down by pressing CTRL+D
  • Use CTRL+UP to return up

On Mac, use CMD instead of CTRL.

An alternative if the formula is in the first cell of a column:

  • Select the entire column by clicking the column header or selecting any cell in the column and pressing CTRL+SPACE
  • Fill down by pressing CTRL+D

clearing a char array c

Use:

memset(my_custom_data, 0, sizeof(my_custom_data));

Or:

memset(my_custom_data, 0, strlen(my_custom_data));

How to Call VBA Function from Excel Cells?

A Function will not work, nor is it necessary:

Sub OpenWorkbook()
    Dim r1 As Range, r2 As Range, o As Workbook
    Set r1 = ThisWorkbook.Sheets("Sheet1").Range("A1")
    Set o = Workbooks.Open(Filename:="C:\TestFolder\ABC.xlsx")
    Set r2 = ActiveWorkbook.Sheets("Sheet1").Range("B2")
    [r1] = [r2]
    o.Close
End Sub

SQL Server, division returns zero

In SQL Server direct division of two integer returns integer even if the result should be the float. There is an example below to get it across:

--1--
declare @weird_number_float float
set @weird_number_float=22/7
select @weird_number_float

--2--
declare @weird_number_decimal decimal(18,10)
set @weird_number_decimal=22/7 
select @weird_number_decimal

--3--
declare @weird_number_numeric numeric
set @weird_number_numeric=22/7 
select @weird_number_numeric

--Right way

declare @weird_number float
set @weird_number=cast(22 as float)/cast(7 as float)
select @weird_number

Just last block will return the 3,14285714285714. In spite of the second block defined with right precision the result will be 3.00000.

Fixed positioning in Mobile Safari

Here you can see what (mobile) browsers support css position fixed + there version.

http://caniuse.com/css-fixed

Find files in created between a date range

Try this:

find /var/tmp -mtime +2 -a -mtime -8 -ls

to find files older than 2 days but not older than 8 days.

DISTINCT for only one column

For Access, you can use the SQL Select query I present here:

For example you have this table:

CLIENTE|| NOMBRES || MAIL

888 || T800 ARNOLD || [email protected]

123 || JOHN CONNOR || [email protected]

125 || SARAH CONNOR ||[email protected]

And you need to select only distinct mails. You can do it with this:

SQL SELECT:

SELECT MAX(p.CLIENTE) AS ID_CLIENTE
, (SELECT TOP 1 x.NOMBRES 
    FROM Rep_Pre_Ene_MUESTRA AS x 
    WHERE x.MAIL=p.MAIL 
     AND x.CLIENTE=(SELECT MAX(l.CLIENTE) FROM Rep_Pre_Ene_MUESTRA AS l WHERE x.MAIL=l.MAIL)) AS NOMBRE, 
p.MAIL
FROM Rep_Pre_Ene_MUESTRA AS p
GROUP BY p.MAIL;

You can use this to select the maximum ID, the correspondent name to that maximum ID , you can add any other attribute that way. Then at the end you put the distinct column to filter and you only group it with that last distinct column.

This will bring you the maximum ID with the correspondent data, you can use min or any other functions and you replicate that function to the sub-queries.

This select will return:

CLIENTE|| NOMBRES || MAIL

888 || T800 ARNOLD || [email protected]

125 || SARAH CONNOR ||[email protected]

Remember to index the columns you select and the distinct column must have not numeric data all in upper case or in lower case, or else it won't work. This will work with only one registered mail as well. Happy coding!!!

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

How to inject window into a service?

To get it to work on Angular 2.1.1 I had to @Inject window using a string

  constructor( @Inject('Window') private window: Window) { }

and then mock it like this

beforeEach(() => {
  let windowMock: Window = <any>{ };
  TestBed.configureTestingModule({
    providers: [
      ApiUriService,
      { provide: 'Window', useFactory: (() => { return windowMock; }) }
    ]
  });

and in the ordinary @NgModule I provide it like this

{ provide: 'Window', useValue: window }

How to gracefully handle the SIGKILL signal in Java

There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.

By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler) method call you are also able to register a signal handler, but probably not for signals like INT or TERM as they are used by the JVM.

To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.

What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid system call.

I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.

How to log request and response body with Retrofit-Android?

Retrofit 2.0 :

UPDATE: @by Marcus Pöhls

Logging In Retrofit 2

Retrofit 2 completely relies on OkHttp for any network operation. Since OkHttp is a peer dependency of Retrofit 2, you won’t need to add an additional dependency once Retrofit 2 is released as a stable release.

OkHttp 2.6.0 ships with a logging interceptor as an internal dependency and you can directly use it for your Retrofit client. Retrofit 2.0.0-beta2 still uses OkHttp 2.5.0. Future releases will bump the dependency to higher OkHttp versions. That’s why you need to manually import the logging interceptor. Add the following line to your gradle imports within your build.gradle file to fetch the logging interceptor dependency.

compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'

You can also visit Square's GitHub page about this interceptor

Add Logging to Retrofit 2

While developing your app and for debugging purposes it’s nice to have a log feature integrated to show request and response information. Since logging isn’t integrated by default anymore in Retrofit 2, we need to add a logging interceptor for OkHttp. Luckily OkHttp already ships with this interceptor and you only need to activate it for your OkHttpClient.

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();   
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging);  // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl(API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(httpClient.build())
        .build();

We recommend to add logging as the last interceptor, because this will also log the information which you added with previous interceptors to your request.

Log Levels

Logging too much information will blow up your Android monitor, that’s why OkHttp’s logging interceptor has four log levels: NONE, BASIC, HEADERS, BODY. We’ll walk you through each of the log levels and describe their output.

further information please visit : Retrofit 2 — Log Requests and Responses

OLD ANSWER:

no logging in Retrofit 2 anymore. The development team removed the logging feature. To be honest, the logging feature wasn’t that reliable anyway. Jake Wharton explicitly stated that the logged messages or objects are the assumed values and they couldn’t be proofed to be true. The actual request which arrives at the server may have a changed request body or something else.

Even though there is no integrated logging by default, you can leverage any Java logger and use it within a customized OkHttp interceptor.

further information about Retrofit 2 please refer : Retrofit — Getting Started and Create an Android Client

Yes or No confirm box using jQuery

I've used these codes:

HTML:

<a id="delete-button">Delete</a>

jQuery:

<script>
$("#delete-button").click(function(){
    if(confirm("Are you sure you want to delete this?")){
        $("#delete-button").attr("href", "query.php?ACTION=delete&ID='1'");
    }
    else{
        return false;
    }
});
</script>

These codes works for me, but I'm not really sure if this is proper. What do you think?

Linq Query Group By and Selecting First Items

See LINQ: How to get the latest/last record with a group by clause

var firstItemsInGroup = from b in mainButtons
                 group b by b.category into g
select g.First();

I assume that mainButtons are already sorted correctly.

If you need to specify custom sort order, use OrderBy override with Comparer.

var firstsByCompareInGroups = from p in rows
        group p by p.ID into grp
        select grp.OrderBy(a => a, new CompareRows()).First();

See an example in my post "Select First Row In Group using Custom Comparer"

Error Installing Homebrew - Brew Command Not Found

You can run in terminal

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"

then install https://github.com/robbyrussell/oh-my-zsh.

When those complate run i.e pico editor pico .zshrc and past those lines:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

remember use brew doctor :)

enter image description here

What is Unicode, UTF-8, UTF-16?

UTF stands for stands for Unicode Transformation Format.Basically in today's world there are scripts written in hundreds of other languages, formats not covered by the basic ASCII used earlier. Hence, UTF came into existence.

UTF-8 has character encoding capabilities and its code unit is 8 bits while that for UTF-16 it is 16 bits.

How to check if an excel cell is empty using Apache POI?

Cell cell = row.getCell(x, Row.CREATE_NULL_AS_BLANK);

This trick helped me a lot, see if it's useful for you

How to set commands output as a variable in a batch file

FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var=%%F
)
ECHO %var%

I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.

Now if your output will contain multiple lines, you can do this

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:

$(document).on('mouseenter','[rel=tooltip]', function(){
    $(this).tooltip('show');
});

$(document).on('mouseleave','[rel=tooltip]', function(){
    $(this).tooltip('hide');
});

Spring profiles and testing

@EnableConfigurationProperties needs to be there (you also can annotate your test class), the application-localtest.yml from test/resources will be loaded. A sample with jUnit5

@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties
@ContextConfiguration(classes = {YourClasses}, initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles(profiles = "localtest")
class TestActiveProfile {

    @Test
    void testActiveProfile(){

    }
}

How can I list ALL DNS records?

I've improved Josh's answer. I've noticed that dig only shows entries already present in the queried nameserver's cache, so it's better to pull an authoritative nameserver from the SOA (rather than rely on the default nameserver). I've also disabled the filtering of wildcard IPs because usually I'm usually more interested in the correctness of the setup.

The new script takes a -x argument for expanded output and a -s NS argument to choose a specific nameserver: dig -x example.com

#!/bin/bash
set -e; set -u
COMMON_SUBDOMAINS="www mail mx a.mx smtp pop imap blog en ftp ssh login"
EXTENDED=""

while :; do case "$1" in
  --) shift; break ;;
  -x) EXTENDED=y; shift ;;
  -s) NS="$2"; shift 2 ;;
  *) break ;;
esac; done
DOM="$1"; shift
TYPE="${1:-any}"

test "${NS:-}" || NS=$(dig +short  SOA "$DOM" | awk '{print $1}')
test "$NS" && NS="@$NS"

if test "$EXTENDED"; then
  dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
  wild_ips=$(dig +short "$NS" "*.$DOM" "$TYPE" | tr '\n' '|')
  wild_ips="${wild_ips%|}"
  for sub in $COMMON_SUBDOMAINS; do
    dig +nocmd $NS "$sub.$DOM" +noall +answer "$TYPE"
  done | cat  #grep -vE "${wild_ips}"
  dig +nocmd $NS "*.$DOM" +noall +answer "$TYPE"
else
  dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
fi

Set a Fixed div to 100% width of the parent container

You can use margin for .wrap container instead of padding for .wrapper:

body{ height:20000px }
#wrapper { padding: 0%; }
#wrap{ 
    float: left;
    position: relative;
    margin: 10%;
    width: 40%; 
    background:#ccc; 
}
#fixed{ 
    position:fixed;
    width:inherit;
    padding:0px; 
    height:10px;
    background-color:#333;    
}

jsfiddle

JDBC connection to MSSQL server in windows authentication mode

For the current MS SQL JDBC driver (6.4.0) tested under Windows 7 from within DataGrip:

  1. as per documentation on authenticationScheme use fully qualified domain name as host e.g. server.your.domain not just server; the documentation also mentions the possibility to specify serverSpn=MSSQLSvc/fqdn:port@REALM, but I can not provide you with details on how to use this. When specifying a fqdn as host the spn is auto-generated.
  2. set authenticationScheme=JavaKerberos
  3. set integratedSecurity=true
  4. use your unqualified user-name (and password) to log in

As this is using JavaKerberos I would appreciate feedback on whether or not this works from outside Windows. I believe that no .dll is needed, but as I used DataGrip to create the connection I am uncertain; I would also appreciate Feedback on this!

How to check user is "logged in"?

Easiest way to check if they are authenticated is Request.User.IsAuthenticated I think (from memory)

How to create a horizontal loading progress bar?

Worked for me , can try with the same

<ProgressBar
    android:id="@+id/determinateBar"
    android:indeterminateOnly="true"
    android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
    android:indeterminateDuration="10"
    android:indeterminateBehavior="repeat"
    android:progressBackgroundTint="#208afa"
    android:progressBackgroundTintMode="multiply"
    android:minHeight="24dip"
    android:maxHeight="24dip"
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:visibility="visible"/>

how to filter out a null value from spark dataframe

df.where(df.col("friend_id").isNull)

Pass a JavaScript function as parameter

Here it's another approach :

function a(first,second)    
{        
return (second)(first);           
}     

a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world     

Writing handler for UIAlertAction

create alert, tested in xcode 9

let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)

and the function

func finishAlert(alert: UIAlertAction!)
{
}

How to get the full url in Express?

Using url.format:

var url = require('url');

This support all protocols and include port number. If you don't have a query string in your originalUrl you can use this cleaner solution:

var requrl = url.format({
    protocol: req.protocol,
    host: req.get('host'),
    pathname: req.originalUrl,
});

If you have a query string:

var urlobj = url.parse(req.originalUrl);
urlobj.protocol = req.protocol;
urlobj.host = req.get('host');
var requrl = url.format(urlobj);

PowerShell The term is not recognized as cmdlet function script file or operable program

For the benefit of searchers, there is another way you can produce this error message - by missing the $ off the script block name when calling it.

e.g. I had a script block like so:

$qa = {
    param($question, $answer)
    Write-Host "Question = $question, Answer = $answer"
}

I tried calling it using:

&qa -question "Do you like powershell?" -answer "Yes!"

But that errored. The correct way was:

&$qa -question "Do you like powershell?" -answer "Yes!"

Installing Python 3 on RHEL

Here are the steps i followed to install Python3:

yum install wget
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz  
sudo tar xvf Python-3.*   
cd Python-3.* 
sudo ./configure --prefix=/opt/python3    
sudo make   
sudo make install   
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3

$ /usr/bin/python3    
Python 3.6.0

How to upload & Save Files with Desired name

i know what went wrong you see you used "" instead of '' in this

$target_Path = $target_Path.basename( 

   "myFile.png"

);

Calculate relative time in C#

I would recommend computing this on the client side too. Less work for the server.

The following is the version that I use (from Zach Leatherman)

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 * 
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification 
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 * 
 * Licensed under the MIT license.
 */

function humane_date(date_str){
        var time_formats = [
                [60, 'just now'],
                [90, '1 minute'], // 60*1.5
                [3600, 'minutes', 60], // 60*60, 60
                [5400, '1 hour'], // 60*60*1.5
                [86400, 'hours', 3600], // 60*60*24, 60*60
                [129600, '1 day'], // 60*60*24*1.5
                [604800, 'days', 86400], // 60*60*24*7, 60*60*24
                [907200, '1 week'], // 60*60*24*7*1.5
                [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
                [3942000, '1 month'], // 60*60*24*(365/12)*1.5
                [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
                [47304000, '1 year'], // 60*60*24*365*1.5
                [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365
                [4730400000, '1 century'] // 60*60*24*365*100*1.5
        ];

        var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
                dt = new Date,
                seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
                token = ' ago',
                i = 0,
                format;

        if (seconds < 0) {
                seconds = Math.abs(seconds);
                token = '';
        }

        while (format = time_formats[i++]) {
                if (seconds < format[0]) {
                        if (format.length == 2) {
                                return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
                        } else {
                                return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
                        }
                }
        }

        // overflow for centuries
        if(seconds > 4730400000)
                return Math.round(seconds / 4730400000) + ' centuries' + token;

        return date_str;
};

if(typeof jQuery != 'undefined') {
        jQuery.fn.humane_dates = function(){
                return this.each(function(){
                        var date = humane_date(this.title);
                        if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
                                jQuery(this).text(date);
                });
        };
}

how to merge 200 csv files in Python

Updating wisty's answer for python3

fout=open("out.csv","a")
# first file:
for line in open("sh1.csv"):
    fout.write(line)
# now the rest:    
for num in range(2,201):
    f = open("sh"+str(num)+".csv")
    next(f) # skip the header
    for line in f:
         fout.write(line)
    f.close() # not really needed
fout.close()

How can I debug a HTTP POST in Chrome?

You can use Canary version of Chrome to see request payload of POST requests.

Request payload

Testing javascript with Mocha - how can I use console.log to debug a test?

You may have also put your console.log after an expectation that fails and is uncaught, so your log line never gets executed.

How do JavaScript closures work?

Maybe you should consider an object-oriented structure instead of inner functions. For example:

    var calculate = {
        number: 0,
        init: function (num) {
            this.number = num;
        },
        add: function (val) {
            this.number += val;
        },
        rem: function (val) {
            this.number -= val;
        }
    };

And read the result from the calculate.number variable, who needs "return" anyway.


//Addition
First think about scope which defines what variable you have to access to (In Javascript);

//there are two kinds of scope
Global Scope which include variable declared outside function or curly brace

let globalVariable = "foo";

one thing to keep in mind is once yo've declared a globalVariable you can use it anywhere in your code even in function;

Local Scope which include variable that are usable only in a specific part of your code

//lets break it 

function scope is when you declare a variable in a function  you can access the variable only within the function

function User(){
    let name = "foo";
    alert(name);
}
    alert(name);//error

//Block scope is when you declare a variable within a block then you can  access that variable only within a block 
{
let user = "foo";
alert(user);
}
alert(user);
//Uncaught ReferenceError: user is not defined at.....

//A Closure

function User(fname){
return function(lname){
 return fname + " " lname;
}
}
let names = User("foo");
alert(names("bar"));

//When you create a function within a function you've created a closure, in our example above since the outer function is returned the inner function got access to outer function's scope

Convert a CERT/PEM certificate to a PFX certificate

Here is how to do this on Windows without third-party tools:

  1. Import certificate to the certificate store. In Windows Explorer select "Install Certificate" in context menu. enter image description here Follow the wizard and accept default options "Local User" and "Automatically".

  2. Find your certificate in certificate store. On Windows 10 run the "Manage User Certificates" MMC. On Windows 2013 the MMC is called "Certificates". On Windows 10 by default your certificate should be under "Personal"->"Certificates" node.

  3. Export Certificate. In context menu select "Export..." menu: enter image description here

    Select "Yes, export the private key": enter image description here

    You will see that .PFX option is enabled in this case: enter image description here

    Specify password for private key.

Upload file to FTP using C#

This works for me,this method will SFTP a file to a location within your network. It uses SSH.NET.2013.4.7 library.One can just download it for free.

    //Secure FTP
    public void SecureFTPUploadFile(string destinationHost,int port,string username,string password,string source,string destination)

    {
        ConnectionInfo ConnNfo = new ConnectionInfo(destinationHost, port, username, new PasswordAuthenticationMethod(username, password));

        var temp = destination.Split('/');
        string destinationFileName = temp[temp.Count() - 1];
        string parentDirectory = destination.Remove(destination.Length - (destinationFileName.Length + 1), destinationFileName.Length + 1);


        using (var sshclient = new SshClient(ConnNfo))
        {
            sshclient.Connect();
            using (var cmd = sshclient.CreateCommand("mkdir -p " + parentDirectory + " && chmod +rw " + parentDirectory))
            {
                cmd.Execute();
            }
            sshclient.Disconnect();
        }


        using (var sftp = new SftpClient(ConnNfo))
        {
            sftp.Connect();
            sftp.ChangeDirectory(parentDirectory);
            using (var uplfileStream = System.IO.File.OpenRead(source))
            {
                sftp.UploadFile(uplfileStream, destinationFileName, true);
            }
            sftp.Disconnect();
        }
    }