Programs & Examples On #Sharpsvn

SharpSvn is a binding of the Subversion Client API for .Net 2.0-4.0+ applications contained within a set of xcopy-deployable dll's

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

Reason is as @MilicaMedic says. Alternative solution is disable all constraints, do the update and then enable the constraints again like this. Very useful when updating test data in test environments.

exec sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

update patient set id_no='7008255601088' where id_no='8008255601088'
update patient_address set id_no='7008255601088' where id_no='8008255601088'

exec sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Source:

https://stackoverflow.com/a/161410/3850405

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

on Ubuntu using PHP 5.59 :
got to `:

/etc/php5/cli/conf.d

and find your xdebug.ini in that dir, in my case is 20-xdebug.ini

and add this line `

xdebug.max_nesting_level = 200


or this

xdebug.max_nesting_level = -1

set it to -1 and you dont have to worry change the value of the nesting level.

`

SQL Server PRINT SELECT (Print a select query result)?

If you want to print more than a single result, just select rows into a temporary table, then select from that temp table into a buffer, then print the buffer:

drop table if exists #temp

-- we just want to see our rows, not how many were inserted
set nocount on

select * into #temp from MyTable

-- note: SSMS will only show 8000 chars
declare @buffer varchar(MAX) = ''

select @buffer = @buffer + Col1 + ' ' + Col2 + CHAR(10) from #temp

print @buffer

Is there an easy way to return a string repeated X number of times?

For many scenarios, this is probably the neatest solution:

public static class StringExtensions
{
    public static string Repeat(this string s, int n)
        => new StringBuilder(s.Length * n).Insert(0, s, n).ToString();
}

Usage is then:

text = "Hello World! ".Repeat(5);

This builds on other answers (particularly @c0rd's). As well as simplicity, it has the following features, which not all the other techniques discussed share:

  • Repetition of a string of any length, not just a character (as requested by the OP).
  • Efficient use of StringBuilder through storage preallocation.

Toad for Oracle..How to execute multiple statements?

  1. Just finsih all of your queries with ;
  2. Select all queries you need (inserts, selects, ...).
  3. Push or F5 or F9 both Works.

Not necessary to execute as script

Generate list of all possible permutations of a string

import java.util.*;

public class all_subsets {
    public static void main(String[] args) {
        String a = "abcd";
        for(String s: all_perm(a)) {
            System.out.println(s);
        }
    }

    public static Set<String> concat(String c, Set<String> lst) {
        HashSet<String> ret_set = new HashSet<String>();
        for(String s: lst) {
            ret_set.add(c+s);
        }
        return ret_set;
    }

    public static HashSet<String> all_perm(String a) {
        HashSet<String> set = new HashSet<String>();
        if(a.length() == 1) {
            set.add(a);
        } else {
            for(int i=0; i<a.length(); i++) {
                set.addAll(concat(a.charAt(i)+"", all_perm(a.substring(0, i)+a.substring(i+1, a.length()))));
            }
        }
        return set;
    }
}

PHP - how to create a newline character?

_x000D_
_x000D_
You Can Try This._x000D_
<?php_x000D_
   $content = str_replace(PHP_EOL, "<br>", $your_content);_x000D_
 ?>_x000D_
 _x000D_
<p><?php echo($content); ?></p>
_x000D_
_x000D_
_x000D_

The easiest way to transform collection to array?

If you use Guava in your project you can use Iterables::toArray.

Foo[] foos = Iterables.toArray(x, Foo.class);

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

Adding an identity to an existing column

In SQL 2005 and above, there's a trick to solve this problem without changing the table's data pages. This is important for large tables where touching every data page can take minutes or hours. The trick also works even if the identity column is a primary key, is part of a clustered or non-clustered index, or other gotchas which can trip up the the simpler "add/remove/rename column" solution.

Here's the trick: you can use SQL Server's ALTER TABLE...SWITCH statement to change the schema of a table without changing the data, meaning you can replace a table with an IDENTITY with an identical table schema, but without an IDENTITY column. The same trick works to add IDENTITY to an existing column.

Normally, ALTER TABLE...SWITCH is used to efficiently replace a full partition in a partitioned table with a new, empty partition. But it can also be used in non-partitioned tables too.

I've used this trick to convert, in under 5 seconds, a column of a of a 2.5 billion row table from IDENTITY to a non-IDENTITY (in order to run a multi-hour query whose query plan worked better for non-IDENTITY columns), and then restored the IDENTITY setting, again in less than 5 seconds.

Here's a code sample of how it works.

 CREATE TABLE Test
 (
   id int identity(1,1),
   somecolumn varchar(10)
 );

 INSERT INTO Test VALUES ('Hello');
 INSERT INTO Test VALUES ('World');

 -- copy the table. use same schema, but no identity
 CREATE TABLE Test2
 (
   id int NOT NULL,
   somecolumn varchar(10)
 );

 ALTER TABLE Test SWITCH TO Test2;

 -- drop the original (now empty) table
 DROP TABLE Test;

 -- rename new table to old table's name
 EXEC sp_rename 'Test2','Test';

 -- update the identity seed
 DBCC CHECKIDENT('Test');

 -- see same records
 SELECT * FROM Test; 

This is obviously more involved than the solutions in other answers, but if your table is large this can be a real life-saver. There are some caveats:

  • As far as I know, identity is the only thing you can change about your table's columns with this method. Adding/removing columns, changing nullability, etc. isn't allowed.
  • You'll need to drop foriegn keys before you do the switch and restore them after.
  • Same for WITH SCHEMABINDING functions, views, etc.
  • new table's indexes need to match exactly (same columns, same order, etc.)
  • Old and new tables need to be on the same filegroup.
  • Only works on SQL Server 2005 or later
  • I previously believed that this trick only works on the Enterprise or Developer editions of SQL Server (because partitions are only supported in Enterprise and Developer versions), but Mason G. Zhwiti in his comment below says that it also works in SQL Standard Edition too. I assume this means that the restriction to Enterprise or Developer doesn't apply to ALTER TABLE...SWITCH.

There's a good article on TechNet detailing the requirements above.

UPDATE - Eric Wu had a comment below that adds important info about this solution. Copying it here to make sure it gets more attention:

There's another caveat here that is worth mentioning. Although the new table will happily receive data from the old table, and all the new rows will be inserted following a identity pattern, they will start at 1 and potentially break if the said column is a primary key. Consider running DBCC CHECKIDENT('<newTableName>') immediately after switching. See msdn.microsoft.com/en-us/library/ms176057.aspx for more info.

If the table is actively being extended with new rows (meaning you don't have much if any downtime between adding IDENTITY and adding new rows, then instead of DBCC CHECKIDENT you'll want to manually set the identity seed value in the new table schema to be larger than the largest existing ID in the table, e.g. IDENTITY (2435457, 1). You might be able to include both the ALTER TABLE...SWITCH and the DBCC CHECKIDENT in a transaction (or not-- haven't tested this) but seems like setting the seed value manually will be easier and safer.

Obviously, if no new rows are being added to the table (or they're only added occasionally, like a daily ETL process) then this race condition won't happen so DBCC CHECKIDENT is fine.

How can I take an UIImage and give it a black border?

I use this method to add a border outside the image. You can customise the border width in boderWidth constant.

Swift 3

func addBorderToImage(image : UIImage) -> UIImage {
    let bgImage = image.cgImage
    let initialWidth = (bgImage?.width)!
    let initialHeight = (bgImage?.height)!
    let borderWidth = Int(Double(initialWidth) * 0.10);
    let width = initialWidth + borderWidth * 2
    let height = initialHeight + borderWidth * 2
    let data = malloc(width * height * 4)

    let context = CGContext(data: data,
                        width: width,
                        height: height,
                        bitsPerComponent: 8,
                        bytesPerRow: width * 4,
                        space: (bgImage?.colorSpace)!,
                        bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue);

    context?.draw(bgImage!, in: CGRect(x: CGFloat(borderWidth), y: CGFloat(borderWidth), width: CGFloat(initialWidth), height: CGFloat(initialHeight)))
    context?.setStrokeColor(UIColor.white.cgColor)
    context?.setLineWidth(CGFloat(borderWidth))
    context?.move(to: CGPoint(x: 0, y: 0))
    context?.addLine(to: CGPoint(x: 0, y: height))
    context?.addLine(to: CGPoint(x: width, y: height))
    context?.addLine(to: CGPoint(x: width, y: 0))
    context?.addLine(to: CGPoint(x: 0, y: 0))
    context?.strokePath()

    let cgImage = context?.makeImage()
    let uiImage = UIImage(cgImage: cgImage!)

    free(data)

    return uiImage;
}

JavaFX How to set scene background image

I know this is an old Question

But in case you want to do it programmatically or the java way

For Image Backgrounds; you can use BackgroundImage class

BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
        BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
          BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));

For Paint or Fill Backgrounds; you can use BackgroundFill class

BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
         new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));

Keeps your java alive && your css dead..

Using Chrome's Element Inspector in Print Preview Mode?

As of Chrome 48 (and perhaps a few versions earlier), the function seems to have moved yet again:

The first few steps are unchanged:

  1. Press F12 to bring up the developer tools

  2. Press ESC to open the console

According to the previous answers, the setting could then be found under the "Emulation" tab. As shown in the images below, it has now been moved to the "Rendering" tab, which can be brought up by clicking on the three dots to the left of the "Console" tab.

Tab selection

Setting selection

How can I get the Google cache age of any URL or web page?

its too simple, you can just type "cache:" before the URL of the page. for example if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page

this will show you the last webcache of the page.see here:

enter image description here

But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.

What is the use of the JavaScript 'bind' method?

The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:

   window.color = "red"; 
   var o = { color: "blue" }; 
   function sayColor(){ 
       alert(this.color); 
   } 
   var objectSayColor = sayColor.bind(o); 
   objectSayColor(); //blue 

Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.

Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS

Java: how can I split an ArrayList in multiple small ArrayLists?

You can also use FunctionalJava library - there is partition method for List. This lib has its own collection types, you can convert them to java collections back and forth.

import fj.data.List;

java.util.List<String> javaList = Arrays.asList("a", "b", "c", "d" );

List<String> fList = Java.<String>Collection_List().f(javaList);

List<List<String> partitions = fList.partition(2);

What is a clean, Pythonic way to have multiple constructors in Python?

I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.

class Gouda(Cheese):
    def __init__(self):
        super(Gouda).__init__(num_holes=10)


class Parmesan(Cheese):
    def __init__(self):
        super(Parmesan).__init__(num_holes=15) 

How to reference a file for variables using Bash?

even shorter using the dot:

#!/bin/bash
. CONFIG_FILE

sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:
=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?

Stretch and scale CSS background

An additional tip for SolidSmile's cheat is to scale (the proportionate re-sizing) by setting a width and using auto for height.

Ex:

#background {
    width: 500px;
    height: auto;
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

How to refresh datagrid in WPF

Bind you Datagrid to an ObservableCollection, and update your collection instead.

File URL "Not allowed to load local resource" in the Internet Browser

For people do not like to modify chrome's security options, we can simply start a python http server from directory which contains your local file:

python -m SimpleHTTPServer

and for python 3:

python3 -m http.server

Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt

2D character array initialization in C

How to create an array size 5 containing pointers to characters:

char *array_of_pointers[ 5 ];        //array size 5 containing pointers to char
char m = 'm';                        //character value holding the value 'm'
array_of_pointers[0] = &m;           //assign m ptr into the array position 0.
printf("%c", *array_of_pointers[0]); //get the value of the pointer to m

How to create a pointer to an array of characters:

char (*pointer_to_array)[ 5 ];        //A pointer to an array containing 5 chars
char m = 'm';                         //character value holding the value 'm'
*pointer_to_array[0] = m;             //dereference array and put m in position 0
printf("%c", (*pointer_to_array)[0]); //dereference array and get position 0

How to create an 2D array containing pointers to characters:

char *array_of_pointers[5][2];          
//An array size 5 containing arrays size 2 containing pointers to char

char m = 'm';                           
//character value holding the value 'm'

array_of_pointers[4][1] = &m;           
//Get position 4 of array, then get position 1, then put m ptr in there.

printf("%c", *array_of_pointers[4][1]); 
//Get position 4 of array, then get position 1 and dereference it.

How to create a pointer to an 2D array of characters:

char (*pointer_to_array)[5][2];
//A pointer to an array size 5 each containing arrays size 2 which hold chars

char m = 'm';                            
//character value holding the value 'm'

(*pointer_to_array)[4][1] = m;           
//dereference array, Get position 4, get position 1, put m there.

printf("%c", (*pointer_to_array)[4][1]); 
//dereference array, Get position 4, get position 1

To help you out with understanding how humans should read complex C/C++ declarations read this: http://www.programmerinterview.com/index.php/c-cplusplus/c-declarations/

How to rename a table in SQL Server?

Nothing worked from proposed here .. So just pored the data into new table

SELECT * 
INTO [acecodetable].['PSCLineReason']
FROM [acecodetable].['15_PSCLineReason'];

maybe will be useful for someone..

In my case it didn't recognize the new schema also the dbo was the owner..

UPDATE

EXECUTE sp_rename N'[acecodetable].[''TradeAgreementClaim'']', N'TradeAgreementClaim';

Worked for me. I found it from the script generated automatically when updating the PK for one of the tables. This way it recognized the new schema as well..

ssh: The authenticity of host 'hostname' can't be established

Ideally, you should create a self-managed certificate authority. Start with generating a key pair: ssh-keygen -f cert_signer

Then sign each server's public host key: ssh-keygen -s cert_signer -I cert_signer -h -n www.example.com -V +52w /etc/ssh/ssh_host_rsa_key.pub

This generates a signed public host key: /etc/ssh/ssh_host_rsa_key-cert.pub

In /etc/ssh/sshd_config, point the HostCertificate to this file: HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub

Restart the sshd service: service sshd restart

Then on the SSH client, add the following to ~/.ssh/known_hosts: @cert-authority *.example.com ssh-rsa AAAAB3Nz...cYwy+1Y2u/

The above contains:

  • @cert-authority
  • The domain *.example.com
  • The full contents of the public key cert_signer.pub

The cert_signer public key will trust any server whose public host key is signed by the cert_signer private key.

Although this requires a one-time configuration on the client side, you can trust multiple servers, including those that haven't been provisioned yet (as long as you sign each server, that is).

For more details, see this wiki page.

ActiveMQ or RabbitMQ or ZeroMQ or

About ZeroMQ aka 0MQ, as you might already know, it's the one that will get you the most messages per seconds (they were about 4 millions per sec on their ref server last time I checked), but as you might also already know, the documentation is non existent. You will have a hard time finding how to start the server(s), let alone how to use them. I guess that's partly why no one contributed about 0MQ yet.

Have fun!

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

We are using master-master replication technique of MySQL and if one MySQL server say 1 is removed from the network it reconnects itself after the connection are restored and all the records that were committed in the in the server 2 which was in the network are transferred to the server 1 which has lost the connection after restoration. Slave thread in the MySQL retries to connect to its master after every 60 sec by default. This property can be changed as MySQL ha a flag "master_connect_retry=5" where 5 is in sec. This means that we want a retry after every 5 sec.

But you need to make sure that the server which lost the connection show not make any commit in the database as you get duplicate Key error Error code: 1062

How do I change the hover over color for a hover over table in Bootstrap?

This is for bootstrap v4 compiled via grunt or some other task runner

You would need to change $table-hover-bg to set the highlight on hover

$table-cell-padding:            .75rem !default;
$table-sm-cell-padding:         .3rem !default;

$table-bg:                      transparent !default;
$table-accent-bg:               rgba(0,0,0,.05) !default;
$table-hover-bg:                rgba(0,0,0,.075) !default;
$table-active-bg:               $table-hover-bg !default;

$table-border-width:            $border-width !default;
$table-border-color:            $gray-lighter !default;

Getting Java version at runtime

Here is the answer from @mvanle, converted to Scala: scala> val Array(javaVerPrefix, javaVerMajor, javaVerMinor, _, _) = System.getProperty("java.runtime.version").split("\\.|_|-b") javaVerPrefix: String = 1 javaVerMajor: String = 8 javaVerMinor: String = 0

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.

Try installing the required verison.

If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.

also remove the lines

 <fork>true</fork>
     <executable>${JAVA_1_7_HOME}/bin/javac</executable>

from the pom.xml

Enabling/installing GD extension? --without-gd

If You're using php5.6 and Ubuntu 18.04 Then run these two commands in your terminal your errors will be solved definitely.

sudo apt-get install php5.6-gd

then restart your apache server by this command.

 sudo service apache2 restart

Print a file's last modified date in Bash

Isn't the 'date' command much simpler? No need for awk, stat, etc.

date -r <filename>

Also, consider looking at the man page for date formatting; for example with common date and time format:

date -r <filename> "+%m-%d-%Y %H:%M:%S"

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.

What is the use of GO in SQL Server Management Studio & Transact SQL?

It is a batch terminator, you can however change it to whatever you want alt text

Parse HTML table to Python list?

Sven Marnach excellent solution is directly translatable into ElementTree which is part of recent Python distributions:

from xml.etree import ElementTree as ET

s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""

table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print(dict(zip(headers, values)))

same output as Sven Marnach's answer...

How to restore the permissions of files and directories within git if they have been modified?

Try git config core.fileMode false

From the git config man page:

core.fileMode

If false, the executable bit differences between the index and the working copy are ignored; useful on broken filesystems like FAT. See git-update-index(1).

The default is true, except git-clone(1) or git-init(1) will probe and set core.fileMode false if appropriate when the repository is created.

How to recover stashed uncommitted changes

On mac this worked for me:

git stash list(see all your stashs)

git stash list

git stash apply (just the number that you want from your stash list)

like this:

git stash apply 1

"Undefined reference to" template class constructor

You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.

When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.

Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:

  • To move the definition to the .h file
  • Add explicit instantiations in the .cpp file.
  • #include the .cpp file defining the template at the .cpp file using the template.

Each of them have their pros and cons,

Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.

Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.

While including cpp files is confusing at the same time shares the problems of both above approaches.

I find first method the easiest to follow and implement and hence advocte using it.

How to Display blob (.pdf) in an AngularJS app

I faced difficulties using "window.URL" with Opera Browser as it would result to "undefined". Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):

$http.post(postUrl, data, {responseType: 'arraybuffer'})
.success(success).error(failed);

function success(data) {
   openPDF(data.data, "myPDFdoc.pdf");
};

function failed(error) {...};

function openPDF(resData, fileName) {
    var ieEDGE = navigator.userAgent.match(/Edge/g);
    var ie = navigator.userAgent.match(/.NET/g); // IE 11+
    var oldIE = navigator.userAgent.match(/MSIE/g); 

    var blob = new window.Blob([resData], { type: 'application/pdf' });

    if (ie || oldIE || ieEDGE) {
       window.navigator.msSaveBlob(blob, fileName);
    }
    else {
       var reader = new window.FileReader();
       reader.onloadend = function () {
          window.location.href = reader.result;
       };
       reader.readAsDataURL(blob);
    }
}

Let me know if it helped! :)

Is a Java hashmap search really O(1)?

A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate.

pcollision = n / capacity

So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.

O(n) = O(k * n)

We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions.

pcollision x 2 = (n / capacity)2

This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to

pcollision x k = (n / capacity)k

And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.

We talk about this by saying that the hash-map has O(1) access with high probability

How do I get today's date in C# in mm/dd/yyyy format?

DateTime.Now.Date.ToShortDateString()

is culture specific.

It is best to stick with:

DateTime.Now.ToString("d/MM/yyyy");

Expanding a parent <div> to the height of its children

Using something like self-clearing div is perfect for a situation like this. Then you'll just use a class on the parent... like:

<div id="parent" class="clearfix">

Padding or margin value in pixels as integer using jQuery

You could also extend the jquery framework yourself with something like:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

$("#myObject").margin().top

JavaScript: changing the value of onclick with or without jQuery

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

You also said:

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

top nav bar blocking top content of the page

Add this:

.navbar {
  position: relative;
}

How to change the datetime format in pandas

Below is the code worked for me, And we need to be very careful for format. Below link will be definitely useful for knowing your exiting format and changing into desired format(Follow strftime() and strptime() Format Codes on below link):

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.

data['date_new_format'] = pd.to_datetime(data['date_to_be_changed'] , format='%b-%y')

How can I get the name of an object in Python?

I ran into this page while wondering the same question.

As others have noted, it's simple enough to just grab the __name__ attribute from a function in order to determine the name of the function. It's marginally trickier with objects that don't have a sane way to determine __name__, i.e. base/primitive objects like basestring instances, ints, longs, etc.

Long story short, you could probably use the inspect module to make an educated guess about which one it is, but you would have to probably know what frame you're working in/traverse down the stack to find the right one. But I'd hate to imagine how much fun this would be trying to deal with eval/exec'ed code.

% python2 whats_my_name_again.py
needle => ''b''
['a', 'b']
[]
needle => '<function foo at 0x289d08ec>'
['c']
['foo']
needle => '<function bar at 0x289d0bfc>'
['f', 'bar']
[]
needle => '<__main__.a_class instance at 0x289d3aac>'
['e', 'd']
[]
needle => '<function bar at 0x289d0bfc>'
['f', 'bar']
[]
%

whats_my_name_again.py:

#!/usr/bin/env python

import inspect

class a_class:
    def __init__(self):
        pass

def foo():
    def bar():
        pass

    a = 'b'
    b = 'b'
    c = foo
    d = a_class()
    e = d
    f = bar

    #print('globals', inspect.stack()[0][0].f_globals)
    #print('locals', inspect.stack()[0][0].f_locals)

    assert(inspect.stack()[0][0].f_globals == globals())
    assert(inspect.stack()[0][0].f_locals == locals())

    in_a_haystack = lambda: value == needle and key != 'needle'

    for needle in (a, foo, bar, d, f, ):
        print("needle => '%r'" % (needle, ))
        print([key for key, value in locals().iteritems() if in_a_haystack()])
        print([key for key, value in globals().iteritems() if in_a_haystack()])


foo()

How can I remove specific rules from iptables?

Use -D command, this is how man page explains it:

-D, --delete chain rule-specification
-D, --delete chain rulenum
    Delete  one  or more rules from the selected chain.  
    There are two versions of this command: 
    the rule can be specified as a number in the chain (starting at 1 for the first rule) or a rule to match.

Do realize this command, like all other command(-A, -I) works on certain table. If you'are not working on the default table(filter table), use -t TABLENAME to specify that target table.

Delete a rule to match

iptables -D INPUT -i eth0 -p tcp --dport 443 -j ACCEPT

Note: This only deletes the first rule matched. If you have many rules matched(this can happen in iptables), run this several times.

Delete a rule specified as a number

iptables -D INPUT 2

Other than counting the number you can list the line-number with --line-number parameter, for example:

iptables -t nat -nL --line-number

How many times a substring occurs

def count_substring(string, sub_string):
    inc = 0
    for i in range(0, len(string)):
        slice_object = slice(i,len(sub_string)+i)
        count = len(string[slice_object])
        if(count == len(sub_string)):
            if(sub_string == string[slice_object]):
                inc = inc + 1
    return inc

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)

How do I search a Perl array for a matching string?

For just a boolean match result or for a count of occurrences, you could use:

use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
    my $count=map {m/^$str$/i} @foo;
    if ($count) {
        print "I found '$str' $count time(s) in '$patterns'\n";
    } else {
        print "I could not find '$str' in the pattern list\n"
    };
}

Output:

I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'

Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.

For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:

enter image description here

Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.

enter image description here

Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.

Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.

Is there an effective tool to convert C# code to Java code?

C# has a few more features than Java. Take delegates for example: Many very simple C# applications use delegates, while the Java folks figures that the observer pattern was sufficient. So, in order for a tool to convert a C# application which uses delegates it would have to translate the structure from using delegates to an implementation of the observer pattern. Another problem is the fact that C# methods are not virtual by default while Java methods are. Additionally, Java doesn't have a way to make methods non virtual. This creates another problem: an application in C# could leverage non virtual method behavior through polymorphism in a way the does not translate directly to Java. If you look around you will probably find that there are lots of tools to convert Java to C# since it is a simpler language (please don't flame me I didn't say worse I said simpler); however, you will find very few if any decent tools that convert C# to Java.

I would recommend changing your approach to converting from Java to C# as it will create fewer headaches in the long run. Db4Objects recently released their internal tool which they use to convert Db4o into C# to the public. It is called Sharpen. If you register with their site you can view this link with instructions on how to use Sharpen: http://developer.db4o.com/Resources/view.aspx/Reference/Sharpen/How_To_Setup_Sharpen

(I've been registered with them for a while and they're good about not spamming)

could not extract ResultSet in hibernate

For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:

CREATE TABLE IF NOT EXISTS `task`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `teaching_hours` DECIMAL(5,2) DEFAULT NULL,
    `isActive` BOOLEAN DEFAULT FALSE,
    `is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You must be very careful cause isActive column will translate to isactive. So in your Entity class is should be like this:

 @Basic
 @Column(name = "isactive", nullable = true)
 public boolean isActive() {
     return isActive;
 }
 public void setActive(boolean active) {
     isActive = active;
 }

That was my problem at least that got me your error

This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post

WCF gives an unsecured or incorrectly secured fault error

In my case, there are two problems that will throw this exception.

Note that, my environment uses Single Sign On (or STS if you prefer) to authenticate a user through ASP.NET MVC site. MVC site in turn makes a service call to my service endpoint by passing bearer token which it requested from STS server with Bootstrap token previously. The error I got was when I made a service call from MVC site.

  1. The WCF service wasn't configured as a relying party in my SSO (or STS if you prefer).

  2. Service's configuration wasn't configured properly. Particularly on audienceUris node of system.identityModel. It must exactly match the service endpoint url.

    <system.identityModel>
        <identityConfiguration>
            <audienceUris>
                <add value="https://localhost/IdpExample.YService/YService.svc" />
            </audienceUris>
            ....
        </identityConfiguration>
    </system.identityModel>
    

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

A simple case that generates this error message:

In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]

TypeError: only integer scalar arrays can be converted to a scalar index

Some variations that work:

In [9]: [1,2,3,4,5][np.array(1)]     # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]    
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])

Basic python list indexing is more restrictive than numpy's:

In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list

edit

Looking again at

indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)

indices is a 1d array of integers - but it certainly isn't scalar. It's an array of 50000 integers. List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.

Change color of Button when Mouse is over

As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.

How to use after we created the ButtonEx-class:

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfEx="clr-namespace:WpfExtensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
    </Grid>
</Window>

ButtonEx.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfExtensions
{
    /// <summary>
    /// Standard button with extensions
    /// </summary>
    public partial class ButtonEx : Button
    {
        readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;

        public ButtonEx()
        {
            InitializeComponent();
        }

        public Brush HoverBackground
        {
            get { return (Brush)GetValue(HoverBackgroundProperty); }
            set { SetValue(HoverBackgroundProperty, value); }
        }
        public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
          "HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
    }
}

ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button

<Button x:Class="WpfExtensions.ButtonEx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
            x:Name="buttonExtension">
    <Button.Resources>
        <Style x:Key="FocusVisual">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
        <SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
        <SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
        <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
        <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
        <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
        <SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
        <SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
        <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
    </Button.Resources>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
            <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                            <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsDefaulted" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                            </Trigger>
                            <Trigger Property="IsPressed" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                                <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

Changing capitalization of filenames in Git

This Python snippet will git mv --force all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force.

Modify it to your liking. I just figured I'd share :)

import os
import re

searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']
os.chdir(searchDir)

for root, dirs, files in os.walk(searchDir):
    dirs[:] = [d for d in dirs if d not in exclude]
    for f in files:
        if re.match(r'[A-Z]', f):
            fullPath = os.path.join(root, f)
            fullPathLower = os.path.join(root, f[0].lower() + f[1:])
            command = 'git mv --force ' + fullPath + ' ' + fullPathLower
            print(command)
            os.system(command)

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I thought I had this configured but it turns out I set the URL in the wrong place. I followed the URL provided in the Google error page and added my URL here. Stupid mistake from my part, but easily done. Hope this helps

JUnit Eclipse Plugin?

JUnit is part of Eclipse Java Development Tools (JDT). So, either install the JDT via Software Updates or download and install Eclipse IDE for Java Developers (actually, I'd recommend installing Eclipse IDE for Java EE Developers if you want a complete built-in environment for server side development).

You add it to a project by right clicking the project in the Package Explorer and selecting Build Path -> Add Libraries... Then simply select JUnit and click Next >.

Trigger function when date is selected with jQuery UI datepicker

$(".datepicker").datepicker().on("changeDate", function(e) {
   console.log("Date changed: ", e.date);
});

show icon in actionbar/toolbar with AppCompat-v7 21

toolbar.setLogo(resize(logo, (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._120sdp) + ""), (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._35sdp) + "")));


public Drawable resize(Drawable image, int width, int height)
{
    Bitmap b = ((BitmapDrawable) image).getBitmap();
    Bitmap bitmapResized = Bitmap.createScaledBitmap(b, width, height, false);
    return new BitmapDrawable(getResources(), bitmapResized);
}

Reading int values from SqlDataReader

TxtFarmerSize.Text = (int)reader[3];

Enabling WiFi on Android Emulator

Wifi is not available on the emulator if you are using below of API level 25.

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

More Information: https://developer.android.com/studio/run/emulator.html#wifi

Generate class from database table

slightly modified from top reply:

declare @TableName sysname = 'HistoricCommand'

declare @Result varchar(max) = '[System.Data.Linq.Mapping.Table(Name = "' + @TableName + '")]
public class Dbo' + @TableName + '
{'

select @Result = @Result + '
    [System.Data.Linq.Mapping.Column(Name = "' + t.ColumnName + '", IsPrimaryKey = ' + pkk.ISPK + ')]
    public ' + ColumnType + NullableSign + ' ' + t.ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id         
    where object_id = object_id(@TableName) 
) t, 
(
                SELECT c.name  AS 'ColumnName', CASE WHEN dd.pk IS NULL THEN 'false' ELSE 'true' END ISPK           
                FROM        sys.columns c
                    JOIN    sys.tables  t   ON c.object_id = t.object_id    
                    LEFT JOIN (SELECT   K.COLUMN_NAME , C.CONSTRAINT_TYPE as pk  
                        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K 
                            LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                        ON K.TABLE_NAME = C.TABLE_NAME
                            AND K.CONSTRAINT_NAME = C.CONSTRAINT_NAME
                            AND K.CONSTRAINT_CATALOG = C.CONSTRAINT_CATALOG
                            AND K.CONSTRAINT_SCHEMA = C.CONSTRAINT_SCHEMA            
                        WHERE K.TABLE_NAME = @TableName) as dd
                     ON dd.COLUMN_NAME = c.name
                 WHERE       t.name = @TableName            
            ) pkk
where pkk.ColumnName = t.ColumnName
order by ColumnId

set @Result = @Result  + '
}'

print @Result

which makes output needed for full LINQ in C# declaration

[System.Data.Linq.Mapping.Table(Name = "HistoricCommand")]
public class DboHistoricCommand
{
    [System.Data.Linq.Mapping.Column(Name = "HistoricCommandId", IsPrimaryKey = true)]
    public int HistoricCommandId { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "PHCloudSoftwareInstanceId", IsPrimaryKey = true)]
    public int PHCloudSoftwareInstanceId { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "CommandType", IsPrimaryKey = false)]
    public int CommandType { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "InitiatedDateTime", IsPrimaryKey = false)]
    public DateTime InitiatedDateTime { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "CompletedDateTime", IsPrimaryKey = false)]
    public DateTime CompletedDateTime { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "WasSuccessful", IsPrimaryKey = false)]
    public bool WasSuccessful { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message", IsPrimaryKey = false)]
    public string Message { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "ResponseData", IsPrimaryKey = false)]
    public string ResponseData { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message_orig", IsPrimaryKey = false)]
    public string Message_orig { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message_XX", IsPrimaryKey = false)]
    public string Message_XX { get; set; }

}

Downloading a Google font and setting up an offline site that uses it

just download the font and extract it in a folder. then link that font. the below code worked for me properly.

body { 
  color: #000; 
  font-family:'Open Sans';
  src:url(../../font/Open_Sans/OpenSans-Light.ttf); 
}

How can I implement a tree in Python?

If someone needs a simpler way to do it, a tree is only a recursively nested list (since set is not hashable) :

[root, [child_1, [[child_11, []], [child_12, []]], [child_2, []]]]

Where each branch is a pair: [ object, [children] ]
and each leaf is a pair: [ object, [] ]

But if you need a class with methods, you can use anytree.

How do you find out the type of an object (in Swift)?

Depends on the use case. But let's assume you want to do something useful with your "variable" types. The Swift switch statement is very powerful and can help you get the results you're looking for...

    let dd2 = ["x" : 9, "y" : "home9"]
    let dds = dd2.filter {
        let eIndex = "x"
        let eValue:Any = 9
        var r = false

        switch eValue {
        case let testString as String:
            r = $1 == testString
        case let testUInt as UInt:
            r = $1 == testUInt
        case let testInt as Int:
            r = $1 == testInt
        default:
            r = false
        }

        return r && $0 == eIndex
    }

In this case, have a simple dictionary that contains key/value pairs that can be UInt, Int or String. In the .filter() method on the dictionary, I need to make sure I test for the values correctly and only test for a String when it's a string, etc. The switch statement makes this simple and safe! By assigning 9 to the variable of type Any, it makes the switch for Int execute. Try changing it to:

   let eValue:Any = "home9"

..and try it again. This time it executes the as String case.

How to install trusted CA certificate on Android device?

If you have a rooted device, you can use a Magisk Module to move User Certs to System so it will be Trusted Certificate

https://github.com/yochananmarqos/Move-Certificates

How to replace a whole line with sed?

sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file

Best XML parser for Java

I wouldn't recommended this is you've got a lot of "thinking" in your app, but using XSLT could be better (and potentially faster with XSLT-to-bytecode compilation) than Java manipulation.

Regex how to match an optional character

You can make the single letter optional by adding a ? after it as:

([A-Z]{1}?)

The quantifier {1} is redundant so you can drop it.

CSS Font "Helvetica Neue"

You can use http://www.fontsquirrel.com/fontface/generator to encode any font for websites. It'll generate the code to include the font.

I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).

See: http://www.truetype-typography.com/ttalias.htm

Hope that helps...

How to block until an event is fired in c#

You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:

ManualResetEvent oSignalEvent = new ManualResetEvent(false);

void SecondThread(){
    //DoStuff
    oSignalEvent.Set();
}

void Main(){
    //DoStuff
    //Call second thread
    System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
    oSecondThread.Start();

    oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
    oSignalEvent.Reset();
    //Do more stuff
}

Android Studio: Plugin with id 'android-library' not found

In later versions, the plugin has changed name to:

apply plugin: 'com.android.library'

And as already mentioned by some of the other answers, you need the gradle tools in order to use it. Using 3.0.1, you have to use the google repo, not mavenCentral or jcenter:

buildscript {
    repositories {
        ...
        //In IntelliJ or older versions of Android Studio
        //maven {
        //   url 'https://maven.google.com'
        //}
        google()//in newer versions of Android Studio
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

How to check if an environment variable exists and get its value?

All the answers worked. However, I had to add the variables that I needed to get to the sudoers files as follows:

sudo visudo
Defaults env_keep += "<var1>, <var2>, ..., <varn>"

Spring Rest POST Json RequestBody Content type not supported

I had the same issue. Root cause was using custom deserializer without default constructor.

Return 0 if field is null in MySQL

You can use coalesce(column_name,0) instead of just column_name. The coalesce function returns the first non-NULL value in the list.

I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select to the insert/update.

This amortises the cost assuming your database is read more often than written (and most of them are).

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

Editor's note: this is a very dangerous approach, if you are using a version of PHP old enough to use it. It opens your code to man-in-the-middle attacks and removes one of the primary purposes of an encrypted connection. The ability to do this has been removed from modern versions of PHP because it is so dangerous. The only reason this has been upvoted 70 time is because people are lazy. DO NOT DO THIS.


I know it's a (very) old question and it's about command line, but when I searched Google for "SSL: no alternative certificate subject name matches target host name", this was the first hit.

It took me a good while to figure out the answer so hope this saves someone a lot of time! In PHP add this to your cUrl setopts:

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

p.s: this should be a temporary solution. Since this is a certificate error, best thing is to have the certificate fixed ofcourse!

Regex date validation for yyyy-mm-dd

You can use this regex to get the yyyy-MM-dd format:

((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])

You can find example for date validation: How to validate date with regular expression.

Row Offset in SQL Server

You can use ROW_NUMBER() function to get what you want:

SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t
WHERE RowNr BETWEEN 10 AND 20

How to create user for a db in postgresql?

Create the user with a password :

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

Then grant the user rights on a specific database :

http://www.postgresql.org/docs/current/static/sql-grant.html

Example :

grant all privileges on database db_name to someuser;

What's the difference between a single precision and double precision floating point operation?

As to the question "Can the ps3 and xbxo 360 pull off double precision floating point operations or only single precision and in generel use is the double precision capabilities made use of (if they exist?)."

I believe that both platforms are incapable of double floating point. The original Cell processor only had 32 bit floats, same with the ATI hardware which the XBox 360 is based on (R600). The Cell got double floating point support later on, but I'm pretty sure the PS3 doesn't use that chippery.

Specifying java version in maven - differences between properties and compiler plugin

How to specify the JDK version?

Use any of three ways: (1) Spring Boot feature, or use Maven compiler plugin with either (2) source & target or (3) with release.

Spring Boot

  1. <java.version> is not referenced in the Maven documentation.
    It is a Spring Boot specificity.
    It allows to set the source and the target java version with the same version such as this one to specify java 1.8 for both :

    1.8

Feel free to use it if you use Spring Boot.

maven-compiler-plugin with source & target

  1. Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties are equivalent.

That is indeed :

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

is equivalent to :

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

maven-compiler-plugin with release instead of source & target

  1. The maven-compiler-plugin 3.6 and later versions provide a new way :

    org.apache.maven.plugins maven-compiler-plugin 3.8.0 9

You could also declare just :

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time it will not work as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release : a new JVM standard option that we could pass from Java 9 :

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.


Which is the best way to specify the JDK version?

The first way (<java.version>) is allowed only if you use Spring Boot.

For Java 8 and below :

About the two other ways : valuing the maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin, you can use one or the other. It changes nothing in the facts since finally the two solutions rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

From Java 9 :

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

What happens if the version differs between the JDK in JAVA_HOME and which one specified in the pom.xml?

It is not a problem if the JDK referenced by the JAVA_HOME is compatible with the version specified in the pom but to ensure a better cross-compilation compatibility think about adding the bootstrap JVM option with as value the path of the rt.jar of the target version.

An important thing to consider is that the source and the target version in the Maven configuration should not be superior to the JDK version referenced by the JAVA_HOME.
A older version of the JDK cannot compile with a more recent version since it doesn't know its specification.

To get information about the source, target and release supported versions according to the used JDK, please refer to java compilation : source, target and release supported versions.


How handle the case of JDK referenced by the JAVA_HOME is not compatible with the java target and/or source versions specified in the pom?

For example, if your JAVA_HOME refers to a JDK 1.7 and you specify a JDK 1.8 as source and target in the compiler configuration of your pom.xml, it will be a problem because as explained, the JDK 1.7 doesn't know how to compile with.
From its point of view, it is an unknown JDK version since it was released after it.
In this case, you should configure the Maven compiler plugin to specify the JDK in this way :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <compilerVersion>1.8</compilerVersion>      
        <fork>true</fork>
        <executable>D:\jdk1.8\bin\javac</executable>                
    </configuration>
</plugin>

You could have more details in examples with maven compiler plugin.


It is not asked but cases where that may be more complicated is when you specify source but not target. It may use a different version in target according to the source version. Rules are particular : you can read about them in the Cross-Compilation Options part.


Why the compiler plugin is traced in the output at the execution of the Maven package goal even if you don't specify it in the pom.xml?

To compile your code and more generally to perform all tasks required for a maven goal, Maven needs tools. So, it uses core Maven plugins (you recognize a core Maven plugin by its groupId : org.apache.maven.plugins) to do the required tasks : compiler plugin for compiling classes, test plugin for executing tests, and so for... So, even if you don't declare these plugins, they are bound to the execution of the Maven lifecycle.
At the root dir of your Maven project, you can run the command : mvn help:effective-pom to get the final pom effectively used. You could see among other information, attached plugins by Maven (specified or not in your pom.xml), with the used version, their configuration and the executed goals for each phase of the lifecycle.

In the output of the mvn help:effective-pom command, you could see the declaration of these core plugins in the <build><plugins> element, for example :

...
<plugin>
   <artifactId>maven-clean-plugin</artifactId>
   <version>2.5</version>
   <executions>
     <execution>
       <id>default-clean</id>
       <phase>clean</phase>
       <goals>
         <goal>clean</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
 <plugin>
   <artifactId>maven-resources-plugin</artifactId>
   <version>2.6</version>
   <executions>
     <execution>
       <id>default-testResources</id>
       <phase>process-test-resources</phase>
       <goals>
         <goal>testResources</goal>
       </goals>
     </execution>
     <execution>
       <id>default-resources</id>
       <phase>process-resources</phase>
       <goals>
         <goal>resources</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
 <plugin>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.1</version>
   <executions>
     <execution>
       <id>default-compile</id>
       <phase>compile</phase>
       <goals>
         <goal>compile</goal>
       </goals>
     </execution>
     <execution>
       <id>default-testCompile</id>
       <phase>test-compile</phase>
       <goals>
         <goal>testCompile</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
  ...

You can have more information about it in the introduction of the Maven lifeycle in the Maven documentation.

Nevertheless, you can declare these plugins when you want to configure them with other values as default values (for example, you did it when you declared the maven-compiler plugin in your pom.xml to adjust the JDK version to use) or when you want to add some plugin executions not used by default in the Maven lifecycle.

get data from mysql database to use in javascript

Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,

$result = mysql_query("SELECT field_name, field_value
                       FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
  $to_encode[] = $row;
}
echo json_encode($to_encode);

If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().

Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then

<!DOCTYPE html>
<html>
  <head>
    <title>That's about it</title>
  </head>
  <body>
    <form>
      <input type="text" id="field1" />
      <input type="text" id="field2" />
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  <script>
    $.getJSON('data.php', function(data) {
      $.each(data, function(fieldName, fieldValue) {
        $("#" + fieldName).val(fieldValue);
      });
    });
  </script>
</html>

That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.

git: patch does not apply

git apply --reverse --reject example.patch

When you created a patch file with the branch names reversed:

ie. git diff feature_branch..master instead of git diff master..feature_branch

MySQL: NOT LIKE

I don't know why

cfg_name_unique NOT LIKE '%categories%' 

still returns those two values, but maybe exclude them explicit:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%'
    AND developer_configurations_cms.cfg_name_unique NOT IN ('categories_posts', 'categories_news')

Use cell's color as condition in if statement (function)

I don't believe there's any way to get a cell's color from a formula. The closest you can get is the CELL formula, but (at least as of Excel 2003), it doesn't return the cell's color.

It would be pretty easy to implement with VBA:

Public Function myColor(r As Range) As Integer
    myColor = r.Interior.ColorIndex
End Function

Then in the worksheet:

=mycolor(A1)

Chart.js v2 hide dataset labels

new Chart('idName', {
      type: 'typeChar',
      data: data,
      options: {
        legend: {
          display: false
        }
      }
    });

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

How do I avoid the specification of the username and password at every git push?

If you already have your SSH keys set up and are still getting the password prompt, make sure your repo URL is in the form

git+ssh://[email protected]/username/reponame.git

as opposed to

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

To see your repo URL, run:

git remote show origin

You can change the URL with git remote set-url like so:

git remote set-url origin git+ssh://[email protected]/username/reponame.git

Github: error cloning my private repository

I faced this while git pull. For mine edited the global git config file that fixed problem.

Goto your home folder and open .gitconfig file. Usually C:\Users\.gitconfig

If the file is not there create it

[http]
sslcainfo = E:\systools\git-1.8.5.2\bin\curl-ca-bundle.crt

There you have to given your own git installation path. I have used portable version of git here.

Then git clone / pull it will work.

Get full query string in C# ASP.NET

I have tested your example, and while Request.QueryString is not convertible to a string neither implicit nor explicit still the .ToString() method returns the correct result.

Further more when concatenating with a string using the "+" operator as in your example it will also return the correct result (because this behaves as if .ToString() was called).

As such there is nothing wrong with your code, and I would suggest that your issue was because of a typo in your code writing "Querystring" instead of "QueryString".

And this makes more sense with your error message since if the problem is that QueryString is a collection and not a string it would have to give another error message.

How can I disable notices and warnings in PHP within the .htaccess file?

It is probably not the best thing to do. You need to at least check out your PHP error log for things going wrong ;)

# PHP error handling for development servers
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /home/path/public_html/domain/PHP_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

How to vertically align text inside a flexbox?

It's depend on your li height just call one more thing line height

_x000D_
_x000D_
* {
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100%;
}

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  align-self: center;
  background: silver;
  width: 100%;
  height:50px;line-height:50px;
}
_x000D_
<ul>
  <li>This is the text</li>
</ul>
_x000D_
_x000D_
_x000D_

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Just my two sends here

I was facing this issue with datetimes so what I did is this:

const moment = require('moment-timezone')

const date = moment.tz('America/Bogota').format()

Then save date to db to be able to compare it from some query.


To install moment-timezone

npm i moment-timezone

Python pandas insert list into a cell

I've got a solution that's pretty simple to implement.

Make a temporary class just to wrap the list object and later call the value from the class.

Here's a practical example:

  1. Let's say you want to insert list object into the dataframe.
df = pd.DataFrame([
    {'a': 1},
    {'a': 2},
    {'a': 3},
])

df.loc[:, 'b'] = [
    [1,2,4,2,], 
    [1,2,], 
    [4,5,6]
] # This works. Because the list has the same length as the rows of the dataframe

df.loc[:, 'c'] = [1,2,4,5,3] # This does not work. 

>>> ValueError: Must have equal len keys and value when setting with an iterable

## To force pandas to have list as value in each cell, wrap the list with a temporary class.

class Fake(object):
    def __init__(self, li_obj):
        self.obj = li_obj

df.loc[:, 'c'] = Fake([1,2,5,3,5,7,]) # This works. 

df.c = df.c.apply(lambda x: x.obj) # Now extract the value from the class. This works. 

Creating a fake class to do this might look like a hassle but it can have some practical applications. For an example you can use this with apply when the return value is list.

Pandas would normally refuse to insert list into a cell but if you use this method, you can force the insert.

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

Reference excel worksheet by name?

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

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

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

Here is the correct way:

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

How to print to console using swift playground?

In Xcode 6.3 and later (including Xcode 7 and 8), console output appears in the Debug area at the bottom of the playground window (similar to where it appears in a project). To show it:

  • Menu: View > Debug Area > Show Debug Area (??Y)

  • Click the middle button of the workspace-layout widget in the toolbar

    workspace layout widget

  • Click the triangle next to the timeline at the bottom of the window

    triangle for console

Anything that writes to the console, including Swift's print statement (renamed from println in Swift 2 beta) shows up there.


In earlier Xcode 6 versions (which by now you probably should be upgrading from anyway), show the Assistant editor (e.g. by clicking the little circle next to a bit in the output area). Console output appears there.

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

jQuery issue - #<an Object> has no method

This problem can also arise if you include jQuery more than once.

Android - drawable with rounded corners at the top only

Try giving these values:

 <corners android:topLeftRadius="6dp" android:topRightRadius="6dp"
         android:bottomLeftRadius="0.1dp" android:bottomRightRadius="0.1dp"/>

Note that I have changed 0dp to 0.1dp.

EDIT: See Aleks G comment below for a cleaner version

Has Windows 7 Fixed the 255 Character File Path Limit?

Workarounds are not solutions, therefore the answer is "No".

Still looking for workarounds, here are possible solutions: http://support.code42.com/CrashPlan/Latest/Troubleshooting/Windows_File_Paths_Longer_Than_255_Characters

Server.Transfer Vs. Response.Redirect

Response.Redirect simply sends a message (HTTP 302) down to the browser.

Server.Transfer happens without the browser knowing anything, the browser request a page, but the server returns the content of another.

java.util.Date vs java.sql.Date

The only time to use java.sql.Date is in a PreparedStatement.setDate. Otherwise, use java.util.Date. It's telling that ResultSet.getDate returns a java.sql.Date but it can be assigned directly to a java.util.Date.

Pie chart with jQuery

jqPlot looks pretty good and it is open source.

Here's a link to the most impressive and up-to-date jqPlot examples.

Using getResources() in non-activity class

here is my answer:

public class WigetControl {
private Resources res;

public WigetControl(Resources res) 
{
    this.res = res;
}

public void setButtonDisable(Button mButton)
{
    mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
    mButton.setEnabled(false);
}

}

and the call can be like this:

        WigetControl control = new WigetControl(getResources());
        control.setButtonDisable(btNext);

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

#!/usr/bin/python

# encoding=utf8

Try This to starting of python file

How to use random in BATCH script?

set /a number=%random% %% [maximum]-[minimum]

example "

set /a number=%random% %% 100-50

will give a random number between 100 and 50. Be sure to only use one percentage sign as the operand if you are not using the line in a batch script!

PHP Error: Function name must be a string

Try square braces with your $_COOKIE, not parenthesis. Like this:

<?php
if ($_COOKIE['CaptchaResponseValue'] == "false")
{
    header('Location: index.php');
    return;
}
?>

I also corrected your location header call a little too.

What is the default initialization of an array in Java?

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\u0000' (whose decimal equivalent is 0).

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

Types in Objective-C on iOS

Note that you can also use the C99 fixed-width types perfectly well in Objective-C:

#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform

The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h and inttypes.h to be useful.

CSS pseudo elements in React

Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):

https://stackoverflow.com/a/42000085

<span class="something" datacustomattribute="">
  Hello
</span>
.something::before {
  content: attr(datascustomattribute);
  position: absolute;
}

Note that the datacustomattribute must start with data and be all lowercase to satisfy React.

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

python NameError: global name '__file__' is not defined

If you're exec'ing a file via command line, you can use this hack

import traceback

def get_this_filename():
    try:
        raise NotImplementedError("No error")
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        filename = traceback.extract_tb(exc_traceback)[-1].filename
    return filename

This worked for me in the UnrealEnginePython console, calling py.exec myfile.py

Nginx not running with no error message

1. Check for your configuration files by running the aforementioned command: sudo nginx -t.

2. Check for port conflicts. For instance, if apache2 (ps waux | grep apache2) or any other service is using the same ports configured for nginx (say port 80) the service will not start and will fail silently (err... the cousin of my friend had this problem...)

What does 'foo' really mean?

See: RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.

Quoting only the relevant definitions from that RFC for brevity:

  1. Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).

  2. First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]

Adding background image to div using CSS

To use an image for body background in CSS

body {
  background-image: url("image.jpg");
}

Which is the preferred way to concatenate a string in Python?

If you are concatenating a lot of values, then neither. Appending a list is expensive. You can use StringIO for that. Especially if you are building it up over a lot of operations.

from cStringIO import StringIO
# python3:  from io import StringIO

buf = StringIO()

buf.write('foo')
buf.write('foo')
buf.write('foo')

buf.getvalue()
# 'foofoofoo'

If you already have a complete list returned to you from some other operation, then just use the ''.join(aList)

From the python FAQ: What is the most efficient way to concatenate many strings together?

str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

chunks = []
for s in my_strings:
    chunks.append(s)
result = ''.join(chunks)

(another reasonably efficient idiom is to use io.StringIO)

To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

result = bytearray()
for b in my_bytes_objects:
    result += b

Edit: I was silly and had the results pasted backwards, making it look like appending to a list was faster than cStringIO. I have also added tests for bytearray/str concat, as well as a second round of tests using a larger list with larger strings. (python 2.7.3)

ipython test example for large lists of strings

try:
    from cStringIO import StringIO
except:
    from io import StringIO

source = ['foo']*1000

%%timeit buf = StringIO()
for i in source:
    buf.write(i)
final = buf.getvalue()
# 1000 loops, best of 3: 1.27 ms per loop

%%timeit out = []
for i in source:
    out.append(i)
final = ''.join(out)
# 1000 loops, best of 3: 9.89 ms per loop

%%timeit out = bytearray()
for i in source:
    out += i
# 10000 loops, best of 3: 98.5 µs per loop

%%timeit out = ""
for i in source:
    out += i
# 10000 loops, best of 3: 161 µs per loop

## Repeat the tests with a larger list, containing
## strings that are bigger than the small string caching 
## done by the Python
source = ['foo']*1000

# cStringIO
# 10 loops, best of 3: 19.2 ms per loop

# list append and join
# 100 loops, best of 3: 144 ms per loop

# bytearray() +=
# 100 loops, best of 3: 3.8 ms per loop

# str() +=
# 100 loops, best of 3: 5.11 ms per loop

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;

:- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

OR

mysql> SELECT student_name,
    ->     GROUP_CONCAT(DISTINCT test_score
    ->               ORDER BY test_score DESC SEPARATOR ' ')
    ->     FROM student
    ->     GROUP BY student_name;

href image link download on click

Simple Code for image download with an image clicking using php

<html>
<head>
    <title> Download-Button </title>
</head>
<body>
    <p> Click the image ! You can download! </p>
    <?php
    $image =  basename("http://localhost/sc/img/logo.png"); // you can here put the image path dynamically 
    //echo $image;
    ?>
    <a download="<?php echo $image; ?>" href="http://localhost/sc/img/logo.png" title="Logo title">
        <img alt="logo" src="http://localhost/sc/img/logo.png">
    </a>
</body>

How can I set response header on express.js assets

There is at least one middleware on npm for handling CORS in Express: cors. [see @mscdex answer]

This is how to set custom response headers, from the ExpressJS DOC

res.set(field, [value])

Set header field to value

res.set('Content-Type', 'text/plain');

or pass an object to set multiple fields at once.

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  'ETag': '12345'
})

Aliased as

res.header(field, [value])

How to display a "busy" indicator with jQuery?

The jQuery documentation recommends doing something like the following:

$( document ).ajaxStart(function() {
  $( "#loading" ).show();
}).ajaxStop(function() {
  $( "#loading" ).hide();
});

Where #loading is the element with your busy indicator in it.

References:

How can I change the font-size of a select option?

We need a trick here...

Normal select-dropdown things won't accept styles. BUT. If there's a "size" parameter in the tag, almost any CSS will apply. With this in mind, I've created a fiddle that's practically equivalent to a normal select tag, plus the value can be edited manually like a ComboBox in visual languages (unless you put readonly in the input tag).

A simplified example:

<style>

    /* only these 2 lines are truly required */
    .stylish span {position:relative;}
    .stylish select {position:absolute;left:0px;display:none}

    /* now you can style the hell out of them */
    .stylish input    { ... }
    .stylish select   { ... }
    .stylish option   { ... }
    .stylish optgroup { ... }

</style>
...
<div class="stylish">
    <label> Choose your superhero: </label>
    <span>
        <input onclick="$(this).closest('div').find('select').slideToggle(110)">
        <br>
        <select size=15 onclick="$(this).hide().closest('div').find('input').val($(this).find('option:selected').text());">

            <optgroup label="Fantasy"></optgroup>
            <option value="gandalf">Gandalf</option>
            <option value="harry">Harry Potter</option>
            <option value="jon">Jon Snow</option>

            <optgroup label="Comics"></optgroup>
            <option value="tony">Tony Stark</option>
            <option value="steve">Steven Rogers</option>
            <option value="natasha">Natasha Romanova</option>

        </select>
    </span>
    <!--

        For the sake of simplicity, I used jQuery here.
        Today it's easy to do the same without it, now
        that we have querySelector(), closest(), etc.

    -->
</div>

A live example:

https://jsfiddle.net/7ac9us70/1052/

Note 1: Sorry for the gradients & all fancy stuff, no they're not necessary, yes I'm showing off, I know, hashtag onlyhuman, hashtag notproud.

Note 2: Those <optgroup> tags don't encapsulate the options belonging under them as they normally should; this is intentional. It's better for the styling (the well-mannered way would be a lot less stylable), and yes this is painless and works in every browser.

C# Break out of foreach loop after X number of items

Why not just use a regular for loop?

for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
    ListViewItem lvi = listView.Items[i];
}

Updated to resolve bug pointed out by Ruben and Pragmatrix.

to remove first and last element in array

You can use Array.prototype.reduce().

Code:

_x000D_
_x000D_
const fruits = ['Banana', 'Orange', 'Apple', 'Mango'],_x000D_
      result = fruits.reduce((a, c, i, array) => 0 === i || array.length - 1 === i ? a : [...a, c], []);_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

.trim() in JavaScript not working in IE

var res = function(str){
    var ob; var oe;
    for(var i = 0; i < str.length; i++){
        if(str.charAt(i) != " " && ob == undefined){ob = i;}
        if(str.charAt(i) != " "){oe = i;}
    }
    return str.substring(ob,oe+1);
}

Dialog to pick image from gallery or from camera

You can implement this code to select image from gallery or camera :-

private ImageView imageview;
private Button btnSelectImage;
private Bitmap bitmap;
private File destination = null;
private InputStream inputStreamImg;
private String imgPath = null;
private final int PICK_IMAGE_CAMERA = 1, PICK_IMAGE_GALLERY = 2;

Now on button click event, you can able to call your method of select Image. This is inside activity's onCreate.

imageview = (ImageView) findViewById(R.id.imageview);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);

//OnbtnSelectImage click event...
btnSelectImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });

Outside of your activity's oncreate.

// Select image from camera and gallery
private void selectImage() {
    try {
        PackageManager pm = getPackageManager();
        int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
        if (hasPerm == PackageManager.PERMISSION_GRANTED) {
            final CharSequence[] options = {"Take Photo", "Choose From Gallery","Cancel"};
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
            builder.setTitle("Select Option");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take Photo")) {
                        dialog.dismiss();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, PICK_IMAGE_CAMERA);
                    } else if (options[item].equals("Choose From Gallery")) {
                        dialog.dismiss();
                        Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        } else
            Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    inputStreamImg = null;
    if (requestCode == PICK_IMAGE_CAMERA) {
        try {
            Uri selectedImage = data.getData();
            bitmap = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);

            Log.e("Activity", "Pick from Camera::>>> ");

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            destination = new File(Environment.getExternalStorageDirectory() + "/" +
                    getString(R.string.app_name), "IMG_" + timeStamp + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            imgPath = destination.getAbsolutePath();
            imageview.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (requestCode == PICK_IMAGE_GALLERY) {
        Uri selectedImage = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
            Log.e("Activity", "Pick from Gallery::>>> ");

            imgPath = getRealPathFromURI(selectedImage);
            destination = new File(imgPath.toString());
            imageview.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Audio.Media.DATA};
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Atlast, finally add the camera and write external storage permission to AndroidManifest.xml

It works for me greatly, hope it will also works for you.

Count all values in a matrix greater than a value

This is very straightforward with boolean arrays:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

How to read a value from the Windows registry

Typically the register key and value are constants in the program. If so, here is an example how to read a DWORD registry value Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled:

#include <windows.h>

DWORD val;
DWORD dataSize = sizeof(val);
if (ERROR_SUCCESS == RegGetValueA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\FileSystem", "LongPathsEnabled", RRF_RT_DWORD, nullptr /*type not required*/, &val, &dataSize)) {
  printf("Value is %i\n", val);
  // no CloseKey needed because it is a predefined registry key
}
else {
  printf("Error reading.\n");
}

To adapt for other value types, see https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea for complete spec.

Twitter Bootstrap - add top space between rows

Just simply use this bs3-upgrade helper for spacings and text aligment...

https://github.com/studija/bs3-upgrade

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

How to change font in ipython notebook

The new location of the theme file is: ~/.jupyter/custom/custom.css

How to add a right button to a UINavigationController?

There is a default system button for "Refresh":

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] 
                            initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                            target:self action:@selector(refreshClicked:)] autorelease];
    self.navigationItem.rightBarButtonItem = refreshButton;

}

- (IBAction)refreshClicked:(id)sender {

}

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.

This two threads explain it better:

How do I parse a string into a number with Dart?

In Dart 2 int.tryParse is available.

It returns null for invalid inputs instead of throwing. You can use it like this:

int val = int.tryParse(text) ?? defaultValue;

Sort array by value alphabetically php

asort() - Maintains key association: yes.

sort() - Maintains key association: no.

Source: http://php.net/manual/en/array.sorting.php

jquery smooth scroll to an anchor?

I used the plugin Smooth Scroll, at http://plugins.jquery.com/smooth-scroll/. With this plugin all you need to include is a link to jQuery and to the plugin code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>

(the links need to have the class smoothScroll to work).

Another feature of Smooth Scroll is that the ancor name is not displayed in the URL!

Get width in pixels from element with style set with %?

Not a single answer does what was asked in vanilla JS, and I want a vanilla answer so I made it myself.

clientWidth includes padding and offsetWidth includes everything else (jsfiddle link). What you want is to get the computed style (jsfiddle link).

function getInnerWidth(elem) {
    return parseFloat(window.getComputedStyle(elem).width);
}

EDIT: getComputedStyle is non-standard, and can return values in units other than pixels. Some browsers also return a value which takes the scrollbar into account if the element has one (which in turn gives a different value than the width set in CSS). If the element has a scrollbar, you would have to manually calculate the width by removing the margins and paddings from the offsetWidth.

function getInnerWidth(elem) {
    var style = window.getComputedStyle(elem);
    return elem.offsetWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - parseFloat(style.borderLeft) - parseFloat(style.borderRight) - parseFloat(style.marginLeft) - parseFloat(style.marginRight);
}

With all that said, this is probably not an answer I would recommend following with my current experience, and I would resort to using methods that don't rely on JavaScript as much.

Trigger insert old values- values that was updated

    createTRIGGER [dbo].[Table] ON [dbo].[table] 
FOR UPDATE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);
    declare @old_v varchar(100)

    select @empid=i.Col_Name1 from inserted i;  
    select @empname=i.Col_Name2  from inserted i;   
    select @empsal=i.Col_Name2 from inserted i;
    select @old_v=d.Col_Name from deleted d

    if update(Col_Name1)
        set @audit_action='Updated Record -- After Update Trigger.';
    if update(Col_Name2)
        set @audit_action='Updated Record -- After Update Trigger.';

    insert into Employee_Test_Audit1(Col_name1,Col_name2,Col_name3,Col_name4,Col_name5,Col_name6(Old_values)) 
    values(@empid,@empname,@empsal,@audit_action,getdate(),@old_v);

    PRINT '----AFTER UPDATE Trigger fired-----.'

How to develop Desktop Apps using HTML/CSS/JavaScript?

I know for there's Fluid and Prism (there are others, that's the one I used to use) that let you load a website into what looks like a standalone app.

In Chrome, you can create desktop shortcuts for websites. (you do that from within Chrome, you can't/shouldn't package that with your app) Chrome Frame is different:

Google Chrome Frame is a plug-in designed for Internet Explorer based on the open-source Chromium project; it brings Google Chrome's open web technologies to Internet Explorer.

You'd need to have some sort of wrapper like that for your webapp, and then the rest is the web technologies you're used to. You can use HTML5 local storage to store data while the app is offline. I think you might even be able to work with SQLite.

I don't know how you would go about accessing OS specific features, though. What I described above has the same limitations as any "regular" website. Hopefully this gives you some sort of guidance on where to start.

Drop all tables whose names begin with a certain string

You may need to modify the query to include the owner if there's more than one in the database.

DECLARE @cmd varchar(4000)
DECLARE cmds CURSOR FOR
SELECT 'drop table [' + Table_Name + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Name LIKE 'prefix%'

OPEN cmds
WHILE 1 = 1
BEGIN
    FETCH cmds INTO @cmd
    IF @@fetch_status != 0 BREAK
    EXEC(@cmd)
END
CLOSE cmds;
DEALLOCATE cmds

This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run.

I know that if I were going to do this against a production database, I'd be as careful as possible.

Edit Code sample fixed.

Duplicate / Copy records in the same MySQL table

Slight variation, main difference being to set the primary key field ("varname") to null, which produces a warning but works. By setting the primary key to null, the auto-increment works when inserting the record in the last statement.

This code also cleans up previous attempts, and can be run more than once without problems:

DELETE FROM `tbl` WHERE varname="primary key value for new record";
DROP TABLE tmp;
CREATE TEMPORARY TABLE tmp SELECT * FROM `tbl` WHERE varname="primary key value for old record";
UPDATE tmp SET varname=NULL;
INSERT INTO `tbl` SELECT * FROM tmp;

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

Post-increment and pre-increment within a 'for' loop produce same output

Well, this is simple. The above for loops are semantically equivalent to

int i = 0;
while(i < 5) {
    printf("%d", i);
    i++;
}

and

int i = 0;
while(i < 5) {
    printf("%d", i);
    ++i;
}

Note that the lines i++; and ++i; have the same semantics FROM THE PERSPECTIVE OF THIS BLOCK OF CODE. They both have the same effect on the value of i (increment it by one) and therefore have the same effect on the behavior of these loops.

Note that there would be a difference if the loop was rewritten as

int i = 0;
int j = i;
while(j < 5) {
    printf("%d", i);
    j = ++i;
}

int i = 0;
int j = i;
while(j < 5) {
    printf("%d", i);
    j = i++;
}

This is because in first block of code j sees the value of i after the increment (i is incremented first, or pre-incremented, hence the name) and in the second block of code j sees the value of i before the increment.

What is the difference between HAVING and WHERE in SQL?

Where clause is used to filter out rows from all over the database. But Having clause is used to filter out rows from a specific group of database. Having clause can also help in aggregate function like min/max/average

for more detail.. what's the difference between WHERE and HAVING what is the difference between WHERE and HAVING

Adding a favicon to a static HTML page

I know its older post but still posting for someone like me. This worked for me

<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />

put your favicon icon on root directory..

How to define relative paths in Visual Studio Project?

By default, all paths you define will be relative. The question is: relative to what? There are several options:

  1. Specifying a file or a path with nothing before it. For example: "mylib.lib". In that case, the file will be searched at the Output Directory.
  2. If you add "..\", the path will be calculated from the actual path where the .sln file resides.

Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

.png files are nice, but .ico files provide alpha-channel transparency, too, plus they give you backwards compatibility.

Have a look at which type StackOverflow uses for example (note that it's transparent):

<link rel="shortcut icon" href="http://sstatic.net/so/favicon.ico"> 
<link rel="apple-touch-icon" href="http://sstatic.net/so/apple-touch-icon.png"> 

The apple-itouch thingy is for iphone users that make a shortcut to a website.

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

wordpress users add line:

@ini_set('memory_limit', '-1');

in wp-settings.php which you can find in the wordpress installed root folder

Bash scripting missing ']'

Change

if [ -s "p1"];  #line 13

into

if [ -s "p1" ];  #line 13

note the space.

Initial bytes incorrect after Java AES/CBC decryption

Looks to me like you are not dealing properly with your Initialization Vector (IV). It's been a long time since I last read about AES, IVs and block chaining, but your line

IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());

does not seem to be OK. In the case of AES, you can think of the initialization vector as the "initial state" of a cipher instance, and this state is a bit of information that you can not get from your key but from the actual computation of the encrypting cipher. (One could argue that if the IV could be extracted from the key, then it would be of no use, as the key is already given to the cipher instance during its init phase).

Therefore, you should get the IV as a byte[] from the cipher instance at the end of your encryption

  cipherOutputStream.close();
  byte[] iv = encryptCipher.getIV();

and you should initialize your Cipher in DECRYPT_MODE with this byte[] :

  IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

Then, your decryption should be OK. Hope this helps.

How to get min, seconds and milliseconds from datetime.now() in python?

time.second helps a lot put that at the top of your python.

YouTube API to fetch all videos on a channel

Using API version 2, which is deprecated, the URL for uploads (of channel UCqAEtEr0A0Eo2IVcuWBfB9g) is:

https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads

There is an API version 3.

Getting list of tables, and fields in each, in a database

Get list of all the tables and the fields in database:

Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_CATALOG Like 'DatabaseName'

Get list of all the fields in table:

Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_CATALOG Like 'DatabaseName' And TABLE_NAME Like 'TableName' 

Using group by on multiple columns

Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.

The GROUP BY clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:

-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

-- GROUP BY with two parameters:
SELECT
    column_name1,
    column_name2,
    AGGREGATE_FUNCTION(column_name3)
FROM
    table_name
GROUP BY
    column_name1,
    column_name2;

Remember this order:

  1. SELECT (is used to select data from a database)

  2. FROM (clause is used to list the tables)

  3. WHERE (clause is used to filter records)

  4. GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)

  5. HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)

  6. ORDER BY (keyword is used to sort the result-set)

You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.

Aggregate Functions are:

MIN() returns the smallest value in a given column

MAX() returns the maximum value in a given column.

SUM() returns the sum of the numeric values in a given column

AVG() returns the average value of a given column

COUNT() returns the total number of values in a given column

COUNT(*) returns the number of rows in a table

SQL script examples about using aggregate functions:

Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING clause and the GROUP BY clause to accomplish this:

SELECT 
    orderId, SUM(unitPrice * qty) Total
FROM
    OrderDetails
GROUP BY orderId
HAVING Total > 950;

Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT function and the GROUP BY, ORDER BY clauses and ASC:

SELECT 
    customerId, COUNT(*)
FROM
    Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;

Retrieve the category that has an average Unit Price greater than $10, using AVG function combine with GROUP BY and HAVING clauses:

SELECT 
    categoryName, AVG(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;

Getting the less expensive product by each category, using the MIN function in a subquery:

SELECT categoryId,
       productId,
       productName,
       unitPrice
FROM Products p1
WHERE unitPrice = (
                SELECT MIN(unitPrice)
                FROM Products p2
                WHERE p2.categoryId = p1.categoryId)

The following statement groups rows with the same values in both categoryId and productId columns:

SELECT 
    categoryId, categoryName, productId, SUM(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

Android offline documentation and sample codes

here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.

https://dl-ssl.google.com/android/repository/docs-17_r02.zip   (129 MB)

Close virtual keyboard on button press

This solution works perfect for me:

private void showKeyboard(EditText editText) {
    editText.requestFocus();
    editText.setFocusableInTouchMode(true);
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    editText.setSelection(editText.getText().length());
}

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

Reading HTML content from a UIWebView

if you want to extract the contents of an already-loaded UIWebView, -stringByEvaluatingJavaScriptFromString. For example:

NSString  *html = [webView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];

How to sort in mongoose?

As of October 2020, to fix your issue you should add .exec() to the call. don't forget that if you want to use this data outside of the call you should run something like this inside of an async function.

let post = await callQuery();

async function callQuery() {
      return Post.find().sort(['updatedAt', 1].exec();
}

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

How to run a command in the background and get no output?

If you want to run the script in a linux kickstart you have to run as below .

sh /tmp/script.sh > /dev/null 2>&1 < /dev/null &

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

I had this problem, too.

Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.

  1. I checked all of the solutions mentioned on this question. The class name and build action were correct.
  2. I Cleaned my Solution and rebuilt. Another error appeared. "Error CS2001: Source file '.cs' could not be found"
  3. I found this answer and followed the steps.
  4. I reloaded the project and cleaned/rebuilt again.
  5. My solution builds without errors and my application works now.

How to add message box with 'OK' button?

I think there may be problem that you haven't added click listener for ok positive button.

dlgAlert.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          //dismiss the dialog  
        }
    });

How do I format a number to a dollar amount in PHP

Note that in PHP 7.4, money_format() function is deprecated. It can be replaced by the intl NumberFormatter functionality, just make sure you enable the php-intl extension. It's a small amount of effort and worth it as you get a lot of customizability.

$f = new NumberFormatter("en", NumberFormatter::CURRENCY);
$f->formatCurrency(12345, "USD"); // Outputs "$12,345.00"

The fast way that will still work for 7.4 is as mentioned by Darryl Hein:

'$' . number_format($money, 2);

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Tomcat: How to find out running tomcat version

Open your tomcat home page (Usually localhost:8080)

You will see something like this:

enter image description here

How to disable HTML links

Bootstrap 4.1 provides a class named disabled and aria-disabled="true" attribute.

example"

<a href="#" 
        class="btn btn-primary btn-lg disabled" 
        tabindex="-1" 
        role="button" aria-disabled="true"
>
    Primary link
</a>

More is on getbootstrap.com

So if you want to make it dynamically, and you don't want to care if it is button or ancor than in JS script you need something like that

   let $btn=$('.myClass');
   $btn.attr('disabled', true);
   if ($btn[0].tagName == 'A'){
        $btn.off();
        $btn.addClass('disabled');
        $btn.attr('aria-disabled', true);
   }

But be carefull

The solution only works on links with classes btn btn-link.

Sometimes bootstrap recommends using card-link class, in this case solution will not work.

matplotlib colorbar for scatter

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.

Creating the dataset

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Plot

enter image description here

java.lang.NoClassDefFoundError: Could not initialize class XXX

Just several days ago, I met the same question just like yours. All code runs well on my local machine, but turns out error(noclassdeffound&initialize). So I post my solution, but I don't know why, I merely advance a possibility. I hope someone know will explain this.@John Vint Firstly, I'll show you my problem. My code has static variable and static block both. When I first met this problem, I tried John Vint's solution, and tried to catch the exception. However, I caught nothing. So I thought it is because the static variable(but now I know they are the same thing) and still found nothing. So, I try to find the difference between the linux machine and my computer. Then I found that this problem happens only when several threads run in one process(By the way, the linux machine has double cores and double processes). That means if there are two tasks(both uses the code which has static block or variables) run in the same process, it goes wrong, but if they run in different processes, both of them are ok. In the Linux machine, I use

mvn -U clean  test -Dtest=path 

to run a task, and because my static variable is to start a container(or maybe you initialize a new classloader), so it will stay until the jvm stop, and the jvm stops only when all the tasks in one process stop. Every task will start a new container(or classloader) and it makes the jvm confused. As a result, the error happens. So, how to solve it? My solution is to add a new command to the maven command, and make every task go to the same container.

-Dxxx.version=xxxxx #sorry can't post more

Maybe you have already solved this problem, but still hope it will help others who meet the same problem.

How do I use InputFilter to limit characters in an EditText in Android?

It is possible to use setOnKeyListener. In this method, we can customize the input edittext !

How can I mix LaTeX in with Markdown?

Hey, this might not be the most ideal solution, but it works for me. I ended up creating a Python-Markdown LaTeX extension.

https://github.com/justinvh/Markdown-LaTeX

It adds support for inline math and text expressions using a $math$ and %text% syntax. The extension is a preprocessor that will use latex/dvipng to generate pngs for the respective equations/text and then base64 encode the data to inline the images directly, rather than have external images.

The data is then put in a simple-delimited cache file that encodes the expression to the base64 representation. This limits the number of times latex actually has to be run.

Here is an example:

%Hello, world!% This is regular text, but this: $y = mx + b$ is not.

The output:

$ markdown -x latex test.markdown
<p><img class='latex-inline math-false' alt='Hello, world!' id='Helloworld' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFwAAAAQBAMAAABpWwV8AAAAMFBMVEX///8iIiK6urpUVFTu7u6YmJgQEBDc3NxERESqqqqIiIgyMjJ2dnZmZmbMzMwAAAAbX03YAAAAAXRSTlMAQObYZgAAAVpJREFUKM9jYICDOgb2BwzYAVji8AQg8fb/PZ79u4AMvv0Mrz/gUA6W8F7AmcLAsJuBYT7Y1PcMfLiUgyWYF/B8Z2DYAVReABKrZ2DHpZwdopzrA0nKOeHKj66CKOcKPQJWwJo2NVFhfwCQyymhYwCUYD0avIApgYFh2927/QUcE3gDwMpvMhRCDJzNMIPhKZg7UW8DUOIMg9sCPgGo6e8ZODeAlAP9xLEArNy/IIwhAMx9D3IM+3cgi70BqnxZaNQFkHJWAQbeBrByjgURExaAuc9AyjnB5hjAlEO9ygVXzrplpskEMPchQvkBmGMcGApgjjkAVs7yhyWVAcwFK2f/AlJeAI0m5gMsEK+aMhQ6aDuA1DcDIZirBg7IOwxlB5g2QBJBF8OZVUz95hqfC3hOXWGYrwBSHskwk4EByGXab8QAlOBaGizFKYAtUlgUGEgBTCSpZnDCLQUA+y6MXeYnPDgAAAAASUVORK5CYII='> This is regular text, but this: <img class='latex-inline math-true' alt='y = mx + b' id='ymxb' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFIAAAAOBAMAAABOTlYkAAAAMFBMVEX///9ERETu7u4yMjK6urp2dnZUVFSIiIjMzMwQEBDc3NwiIiJmZmaYmJiqqqoAAADS00rKAAAAAXRSTlMAQObYZgAAAOtJREFUKM9jYCAACsCk4wYGgiABTLInEKuS+QGxKvkVGBj47jBwI8tcffI84e45BoZ7GVcLECo9751iWLeSoRPITBQEggMMDBy9sxj2MDgz8DIE8yCpPMxwjWFBGUMMkpFcbAEMvxjKGLgYxIE8NkHBiYIyQMY+hmoGhi0Mdsi2czawbGCQBTJ+ILvzE0MaA9MHIIWwnWE9A+sBpk8LGDgmMCnAVXJNYPgCJHhRQvUiA/cDXoECZx4DXoSZTBtYgaaEPw5AVnkOGBRc5xTcbsReQrL9+nWwyxbgC88DcJZ+QygDcYD1+QPiFAIAtLA8KPZOGFEAAAAASUVORK5CYII='> is not.</p>

As you can see it is a verbose output, but that really isn't an issue since you're already using Markdown :)

iOS 9 not opening Instagram app with URL SCHEME

This is a new security feature of iOS 9. Watch WWDC 2015 Session 703 for more information.

Any app built with SDK 9 needs to provide a LSApplicationQueriesSchemes entry in its plist file, declaring which schemes it attempts to query.

<key>LSApplicationQueriesSchemes</key>
<array>
 <string>urlscheme</string>
 <string>urlscheme2</string>
 <string>urlscheme3</string>
 <string>urlscheme4</string>
</array> 

ImportError: No module named psycopg2

Recently faced this issue on my production server. I had installed pyscopg2 using

sudo pip install psycopg2

It worked beautifully on my local, but had me for a run on my ec2 server.

sudo python -m pip install psycopg2

The above command worked for me there. Posting here just in case it would help someone in future.

How to get the last five characters of a string using Substring() in C#?

// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One. 

string sub = input.Substring(6, 5);
Console.WriteLine("Substring: {0}", sub); //You'll get output: Three

'AND' vs '&&' as operator

Since and has lower precedence than = you can use it in condition assignment:

if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false

How to open a link in new tab (chrome) using Selenium WebDriver?

I checked with below code and it works fine for me. I found answer from here.

    driver = new ChromeDriver();
    driver.manage().window().maximize();
            
    String baseUrl = "http://www.google.co.uk/";
    driver.get(baseUrl);
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

    ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1)); //switches to new tab
    driver.get("https://www.facebook.com");
    
    driver.switchTo().window(tabs.get(0)); // switch back to main screen        
    driver.get("https://www.news.google.com");

How to get the caller class in Java

i am using the following method to get the caller for a specific class from the stacktrace:

package test.log;

public class CallerClassTest {

    public static void main(final String[] args) {
        final Caller caller = new Caller(new Callee());
        caller.execute();
    }

    private static class Caller {

        private final Callee c;

        public Caller(final Callee c) {
            this.c = c;
        }

        void execute() {
            c.call();
        }
    }

    static class Callee {

        void call() {
            System.out.println(getCallerClassName(this.getClass()));
        }
    }

    /**
     * Searches the current threads stacktrace for the class that called the given class. Returns {@code null} if the
     * calling class could not be found.
     * 
     * @param clazz
     *            the class that has been called
     * 
     * @return the caller that called the class or {@code null}
     */
    public static String getCallerClassName(final Class<?> clazz) {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        final String className = clazz.getName();
        boolean classFound = false;
        for (int i = 1; i < stackTrace.length; i++) {
            final StackTraceElement element = stackTrace[i];
            final String callerClassName = element.getClassName();
            // check if class name is the requested class
            if (callerClassName.equals(className)) classFound = true;
            else if (classFound) return callerClassName;
        }
        return null;
    }

}

Checking if type == list in python

Although not as straightforward as isinstance(x, list) one could use as well:

this_is_a_list=[1,2,3]
if type(this_is_a_list) == type([]):
    print("This is a list!")

and I kind of like the simple cleverness of that

Display Last Saved Date on worksheet

There is no built in function with this capability. The close would be to save the file in a folder named for the current date and use the =INFO("directory") function.

Does JavaScript pass by reference?

Objects are always pass by reference and primitives by value. Just keep that parameter at the same address for objects.

Here's some code to illustrate what I mean (try it in a JavaScript sandbox such as https://js.do/).

Unfortunately you can't only retain the address of the parameter; you retain all the original member values as well.

a = { key: 'bevmo' };
testRetain(a);
document.write(' after function ');
document.write(a.key);


function testRetain (b)
{
    document.write(' arg0 is ');
    document.write(arguments[0].key);
    b.key = 'passed by reference';
    var retain = b; // Retaining the original address of the parameter

    // Address of left set to address of right, changes address of parameter
    b = {key: 'vons'}; // Right is a new object with a new address
    document.write(' arg0 is ');
    document.write(arguments[0].key);

    // Now retrieve the original address of the parameter for pass by reference
    b = retain;
    document.write(' arg0 is ');
    document.write(arguments[0].key);
}

Result:

arg0 is bevmo arg0 is vons arg0 is passed by reference after function passed by reference

Pure CSS scroll animation

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

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

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

Hope that helps,

Ed

Understanding implicit in Scala

WARNING: contains sarcasm judiciously! YMMV...

Luigi's answer is complete and correct. This one is only to extend it a bit with an example of how you can gloriously overuse implicits, as it happens quite often in Scala projects. Actually so often, you can probably even find it in one of the "Best Practice" guides.

object HelloWorld {
  case class Text(content: String)
  case class Prefix(text: String)

  implicit def String2Text(content: String)(implicit prefix: Prefix) = {
    Text(prefix.text + " " + content)
  }

  def printText(text: Text): Unit = {
    println(text.content)
  }

  def main(args: Array[String]): Unit = {
    printText("World!")
  }

  // Best to hide this line somewhere below a pile of completely unrelated code.
  // Better yet, import its package from another distant place.
  implicit val prefixLOL = Prefix("Hello")
}

Comparing arrays for equality in C++

Array is not a primitive type, and the arrays belong to different addresses in the C++ memory.

How to create a horizontal loading progress bar?

Just add a STYLE line and your progress becomes horizontal:

<ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progress"
        android:layout_centerHorizontal="true"      
        android:layout_centerVertical="true"      
        android:max="100" 
        android:progress="45"/>

How to retrieve a module's path?

This was trivial.

Each module has a __file__ variable that shows its relative path from where you are right now.

Therefore, getting a directory for the module to notify it is simple as:

os.path.dirname(__file__)

Hadoop cluster setup - java.net.ConnectException: Connection refused

Make sure HDFS is online. Start it by $HADOOP_HOME/sbin/start-dfs.sh Once you do that, your test with telnet localhost 9001should work.

How to resolve a Java Rounding Double issue

See responses to this question. Essentially what you are seeing is a natural consequence of using floating point arithmetic.

You could pick some arbitrary precision (significant digits of your inputs?) and round your result to it, if you feel comfortable doing that.