Programs & Examples On #Vix

VIX is an API for writing scripts to automate VMware's virtual machine operations and run programs that manipulate files within guest operating systems.

The server principal is not able to access the database under the current security context in SQL Server MS 2012

In my case, the message was caused by a synonym which inadvertently included the database name in the "object name". When I restored the database under a new name, the synonym still pointed to the old DB name. Since the user did not have permissions in the old DB, the message appeared. To fix, I dropped and recreated the synonym without qualifying the object name with the database name:

    USE [new_db]
GO

/****** Object:  Synonym [dbo].[synTable]    Script Date: 10/15/2015 9:45:01 AM ******/
DROP SYNONYM [dbo].[synTable]
GO

/****** Object:  Synonym [dbo].[synTable]    Script Date: 10/15/2015 9:45:01 AM ******/
CREATE SYNONYM [dbo].[synTable] FOR [dbo].[tTheRealTable]
GO

Export DataTable to Excel File

Working code for Excel Export

 try
        {
            DataTable dt = DS.Tables[0];
            string attachment = "attachment; filename=log.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dc in dt.Columns)
            {
                Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }
        catch (Exception Ex)
        { }

Resize image in PHP

You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.

composer require tinify/tinify

After that, your code is as follows.

require_once("vendor/autoload.php");

\Tinify\setKey("YOUR_API_KEY");

$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
    "method" => "fit",
    "width" => 150,
    "height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image

I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng

C++11 thread-safe queue

According to the standard condition_variables are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout (since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.

The details are specified in the standard §30.5.1 [thread.condition.condvar]:

—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.

...

Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Angular 2 @ViewChild annotation returns undefined

In my case, I knew the child component would always be present, but wanted to alter the state prior to the child initializing to save work.

I choose to test for the child until it appeared and make changes immediately, which saved me a change cycle on the child component.

export class GroupResultsReportComponent implements OnInit {

    @ViewChild(ChildComponent) childComp: ChildComponent;

    ngOnInit(): void {
        this.WhenReady(() => this.childComp, () => { this.childComp.showBar = true; });
    }

    /**
     * Executes the work, once the test returns truthy
     * @param test a function that will return truthy once the work function is able to execute 
     * @param work a function that will execute after the test function returns truthy
     */
    private WhenReady(test: Function, work: Function) {
        if (test()) work();
        else setTimeout(this.WhenReady.bind(window, test, work));
    }
}

Alertnatively, you could add a max number of attempts or add a few ms delay to the setTimeout. setTimeout effectively throws the function to the bottom of the list of pending operations.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Right click on your folder on your server or local machine and give full permissions to

IIS_IUSRS

that's it.

ORA-12154 could not resolve the connect identifier specified

I have an Entity Framework web application that works on my local machine, but this error appears when pushed to another environment. There are other non-Entity Framework applications that work, and I'm able to connect with sqlplus.

Using sysinternals Process Monitor shows that tns names file is not being loaded correctly:

tnsnames.ora status NAME NOT FOUND

Following the documentation I tried to add a section giving the location of the tnsnames file like so:

<configuration>

  <configSections>
    <section name="oracle.manageddataaccess.client"
      type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
  </configSections>
  
  <oracle.manageddataaccess.client>
    <version number="*">
      <settings>
        <setting name="TNS_ADMIN" value="C:\Oracle\product\12.1.0\client_1\Network\Admin"/>
      </settings>
    </version>
  </oracle.manageddataaccess.client>
  
<configuration>

However, this resulted in an immediate 500 server error.

Further investigation showed that the dll I was packaging with the web application was version 4.122.1.0, while the Oracle client environment installed on the machine was 4.121.2.0. As explained in the Oracle EntityFramework package documentation

Note: If your application is a web application and the above entry was added to a web.config and the same config section handler for "oracle.manageddataaccess.client" also exists in machine.config but the "Version" attribute values are different, an error message of "There is a duplicate 'oracle.manageddataaccess.client' section defined." may be observed at runtime. If so, the config section handler entry in the machine.config for "oracle.manageddataaccess.client" has to be removed from the machine.config for the web application to not encounter this error. But given that there may be other applications on the machine that depended on this entry in the machine.config, this config section handler entry may need to be moved to all of the application's .NET config file on that machine that depend on it.

I attempted to add a separate version section in the .NET machine.config without success (there existed a section for version 4.121.2.0 and I added a section for version 4.122.1.0). After I removed the "oracle.manageddataaccess.client" section from the machine.config, the above addition to the web.config resolved ORA-12154.

Solution #1 summary:

  1. Remove "oracle.manageddataaccess.client" from .NET machine.config
  2. Give TNS_ADMIN configuration setting in web.config as above

Solution 2

While researching this problem I found that the TNS_ADMIN environmental variable was not set. I created a new environmental variable called TNS_ADMIN and set the value to "C:\Oracle\product\12.1.0\client_1\Network\Admin". I removed the web.config changes, and removed the "oracle.manageddataaccess.client" section from .NET machine.config, but still received ORA-12154. Only after I restarted the machine did this resolve the issue.

Solution #2 summary:

  1. Create a new environmental variable called TNS_ADMIN and set the value to "C:\Oracle\product\12.1.0\client_1\Network\Admin"
  2. Restart machine

Solution 3

I added an entry for the correct version in the registry and this resolved the issue:

HKLM\Software\Wow6432Node\Oracle\ODP.NET.Managed\4.121.2.0  

The name of the key is TNS_ADMIN and this points to the folder containing the tnsnames file:

C:\Oracle\product\12.1.0\client_1\network 

Not the C:\Oracle\product\12.1.0\client_1\network\admin folder.

How do I create batch file to rename large number of files in a folder?

You don't need a batch file, just do this from powershell :

powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"

Convert an integer to a byte array

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

select command denied to user ''@'' for table ''

This problem is a basically generated after join condition are wrong database name in your join query. So please check the your select query in join table name after database.

Then solve it for example its correct ans ware

string g = " SELECT `emptable`.`image` , `applyleave`.`id` , `applyleave`.`empid` , `applyleave`.`empname` , `applyleave`.`dateapply` , `applyleave`.`leavename` , `applyleave`.`fromdate` , `applyleave`.`todate` , `applyleave`.`resion` , `applyleave`.`contact` , `applyleave`.`leavestatus` , `applyleave`.`username` , `applyleave`.`noday` FROM `DataEMP_ems`.`applyleave` INNER JOIN `DataEMP_ems`.`emptable` ON ( `applyleave`.`empid` = `emptable`.`empid` ) WHERE ( `applyleave`.`leavestatus` = 'panding' ) ";

The join table is imputable and applyleave on the same database but online database name is diffrent then given error on this problem.

How to evaluate http response codes from bash/shell script?

Although the accepted response is a good answer, it overlooks failure scenarios. curl will return 000 if there is an error in the request or there is a connection failure.

url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic

Note: this goes a little beyond the requested 500 status check to also confirm that curl can even connect to the server (i.e. returns 000).

Create a function from it:

failureCode() {
    local url=${1:-http://localhost:8080}
    local code=${2:-500}
    local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
    [[ $status == ${code} ]] || [[ $status == 000 ]]
}

Test getting a 500:

failureCode http://httpbin.org/status/500 && echo need to restart

Test getting error/connection failure (i.e. 000):

failureCode http://localhost:77777 && echo need to start

Test not getting a 500:

failureCode http://httpbin.org/status/400 || echo not a failure

Setting the target version of Java in ant javac

Both source and target should be specified. I recommend providing ant defaults, that way you do not need to specify source/target attribute for every javac task:

<property name="ant.build.javac.source" value="1.5"/>
<property name="ant.build.javac.target" value="1.5"/>

See Java cross-compiling notes for more information.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

rpm -qa openssl yum clean all && yum update "openssl*" lsof -n | grep ssl | grep DEL cd /usr/src wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz tar -zxf openssl-1.0.1g.tar.gz cd openssl-1.0.1g ./config --prefix=/usr --openssldir=/usr/local/openssl shared ./config make make test make install cd /usr/src rm -rf openssl-1.0.1g.tar.gz rm -rf openssl-1.0.1g

and

openssl version

How to Set a Custom Font in the ActionBar Title?

Try using This

TextView headerText= new TextView(getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
headerText.setLayoutParams(lp);
headerText.setText("Welcome!");
headerText.setTextSize(20);
headerText.setTextColor(Color.parseColor("#FFFFFF"));
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/wesfy_regular.ttf");
headerText.setTypeface(tf);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(headerText);

Easy way to use variables of enum types as string in C?

The technique from Making something both a C identifier and a string? can be used here.

As usual with such preprocessor stuff, writing and understanding the preprocessor part can be hard, and includes passing macros to other macros and involves using # and ## operators, but using it is real easy. I find this style very useful for long enums, where maintaining the same list twice can be really troublesome.

Factory code - typed only once, usually hidden in the header:

enumFactory.h:

// expansion macro for enum value definition
#define ENUM_VALUE(name,assign) name assign,

// expansion macro for enum to string conversion
#define ENUM_CASE(name,assign) case name: return #name;

// expansion macro for string to enum conversion
#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;

/// declare the access function and define enum values
#define DECLARE_ENUM(EnumType,ENUM_DEF) \
  enum EnumType { \
    ENUM_DEF(ENUM_VALUE) \
  }; \
  const char *GetString(EnumType dummy); \
  EnumType Get##EnumType##Value(const char *string); \

/// define the access function names
#define DEFINE_ENUM(EnumType,ENUM_DEF) \
  const char *GetString(EnumType value) \
  { \
    switch(value) \
    { \
      ENUM_DEF(ENUM_CASE) \
      default: return ""; /* handle input error */ \
    } \
  } \
  EnumType Get##EnumType##Value(const char *str) \
  { \
    ENUM_DEF(ENUM_STRCMP) \
    return (EnumType)0; /* handle input error */ \
  } \

Factory used

someEnum.h:

#include "enumFactory.h"
#define SOME_ENUM(XX) \
    XX(FirstValue,) \
    XX(SecondValue,) \
    XX(SomeOtherValue,=50) \
    XX(OneMoreValue,=100) \

DECLARE_ENUM(SomeEnum,SOME_ENUM)

someEnum.cpp:

#include "someEnum.h"
DEFINE_ENUM(SomeEnum,SOME_ENUM)

The technique can be easily extended so that XX macros accepts more arguments, and you can also have prepared more macros to substitute for XX for different needs, similar to the three I have provided in this sample.

Comparison to X-Macros using #include / #define / #undef

While this is similar to X-Macros others have mentioned, I think this solution is more elegant in that it does not require #undefing anything, which allows you to hide more of the complicated stuff is in the factory the header file - the header file is something you are not touching at all when you need to define a new enum, therefore new enum definition is a lot shorter and cleaner.

Using Address Instead Of Longitude And Latitude With Google Maps API

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests

Access index of last element in data frame

You want .iloc with double brackets.

import pandas as pd
df = pd.DataFrame({"date": range(10, 64, 8), "not_date": "fools"})
df.index += 17
df.iloc[[0,-1]][['date']]

You give .iloc a list of indexes - specifically the first and last, [0, -1]. That returns a dataframe from which you ask for the 'date' column. ['date'] will give you a series (yuck), and [['date']] will give you a dataframe.

Passing the argument to CMAKE via command prompt

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

How much should a function trust another function

My 2 cents.

This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.

On the other hand if its some client I don't control then it is a good idea to do thorough error checking.

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

What is the difference between class and instance methods?

Like the other answers have said, instance methods operate on an object and has access to its instance variables, while a class method operates on a class as a whole and has no access to a particular instance's variables (unless you pass the instance in as a parameter).

A good example of an class method is a counter-type method, which returns the total number of instances of a class. Class methods start with a +, while instance ones start with an -. For example:

static int numberOfPeople = 0;

@interface MNPerson : NSObject {
     int age;  //instance variable
}

+ (int)population; //class method. Returns how many people have been made.
- (id)init; //instance. Constructs object, increments numberOfPeople by one.
- (int)age; //instance. returns the person age
@end

@implementation MNPerson
- (id)init{
    if (self = [super init]){
          numberOfPeople++;
          age = 0;
    }    
    return self;
}

+ (int)population{ 
     return numberOfPeople;
}

- (int)age{
     return age;
}

@end

main.m:

MNPerson *micmoo = [[MNPerson alloc] init];
MNPerson *jon = [[MNPerson alloc] init];
NSLog(@"Age: %d",[micmoo age]);
NSLog(@"%Number Of people: %d",[MNPerson population]);

Output: Age: 0 Number Of people: 2

Another example is if you have a method that you want the user to be able to call, sometimes its good to make that a class method. For example, if you have a class called MathFunctions, you can do this:

+ (int)square:(int)num{ 
      return num * num;
}

So then the user would call:

[MathFunctions square:34];

without ever having to instantiate the class!

You can also use class functions for returning autoreleased objects, like NSArray's

+ (NSArray *)arrayWithObject:(id)object

That takes an object, puts it in an array, and returns an autoreleased version of the array that doesn't have to be memory managed, great for temperorary arrays and what not.

I hope you now understand when and/or why you should use class methods!!

What is the difference between smoke testing and sanity testing?

Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.

Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.

In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.

What is the difference between UTF-8 and Unicode?

Let me use an example to illustrate this topic:

A chinese character:      ?
it's unicode value:       U+6C49
convert 6C49 to binary:   01101100 01001001

Nothing magical so far, it's very simple. Now, let's say we decide to store this character on our hard drive. To do that, we need to store the character in binary format. We can simply store it as is '01101100 01001001'. Done!

But wait a minute, is '01101100 01001001' one character or two characters? You knew this is one character because I told you, but when a computer reads it, it has no idea. So we need some sort of "encoding" to tell the computer to treat it as one.

This is where the rules of 'UTF-8' comes in: http://www.fileformat.info/info/unicode/utf8.htm

Binary format of bytes in sequence

1st Byte    2nd Byte    3rd Byte    4th Byte    Number of Free Bits   Maximum Expressible Unicode Value
0xxxxxxx                                                7             007F hex (127)
110xxxxx    10xxxxxx                                (5+6)=11          07FF hex (2047)
1110xxxx    10xxxxxx    10xxxxxx                  (4+6+6)=16          FFFF hex (65535)
11110xxx    10xxxxxx    10xxxxxx    10xxxxxx    (3+6+6+6)=21          10FFFF hex (1,114,111)

According to the table above, if we want to store this character using the 'UTF-8' format, we need to prefix our character with some 'headers'. Our chinese character is 16 bits long (count the binary value yourself), so we will use the format on row 3 as it provides enough space:

Header  Place holder    Fill in our Binary   Result         
1110    xxxx            0110                 11100110
10      xxxxxx          110001               10110001
10      xxxxxx          001001               10001001

Writing out the result in one line:

11100110 10110001 10001001

This is the UTF-8 (binary) value of the chinese character! (confirm it yourself: http://www.fileformat.info/info/unicode/char/6c49/index.htm)

Summary

A chinese character:      ?
it's unicode value:       U+6C49
convert 6C49 to binary:   01101100 01001001
embed 6C49 as UTF-8:      11100110 10110001 10001001

P.S. If you want to learn this topic in python, click here

Setting up SSL on a local xampp/apache server

You can enable SSL on XAMPP by creating self signed certificates and then installing those certificates. Type the below commands to generate and move the certificates to ssl folders.

openssl genrsa -des3 -out server.key 1024

openssl req -new -key server.key -out server.csr

cp server.key server.key.org

openssl rsa -in server.key.org -out server.key

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

cp server.crt /opt/lampp/etc/ssl.crt/domainname.crt

cp server.key /opt/lampp/etc/ssl.key/domainname.key

(Use sudo with each command if you are not the super user)

Now, Check that mod_ssl is enabled in [XAMPP_HOME]/etc/httpd.conf:

LoadModule ssl_module modules/mod_ssl.so

Add a virtual host, in this example "localhost.domainname.com" by editing [XAMPP_HOME]/etc/extra/httpd-ssl.conf as follows:

<virtualhost 127.0.1.4:443>
    ServerName localhost.domainname.com
    ServerAlias localhost.domainname.com *.localhost.domainname.com
    ServerAdmin admin@localhost

    DocumentRoot "/opt/lampp/htdocs/"

    DirectoryIndex index.php

    ErrorLog /opt/lampp/logs/domainname.local.error.log
    CustomLog /opt/lampp/logs/domainname.local.access.log combined

    SSLEngine on
    SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
    SSLCertificateFile /opt/lampp/etc/ssl.crt/domainname.crt
    SSLCertificateKeyFile /opt/lampp/etc/ssl.key/domainname.key

    <directory /opt/lampp/htdocs/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Order allow,deny
            Allow from all
    </directory>
    BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
</virtualhost>

Add the following entry to /etc/hosts:

127.0.1.4 localhost.domainname.com

Now, try installing the certificate/ try importing certificate to browser. I have checked this and this worked on Ubuntu.

How to downgrade or install an older version of Cocoapods

Several notes:

Make sure you first get a list of all installed versions. I actually had the version I wanted to downgrade to already installed, but ended up uninstalling that as well. To see the list of all your versions do:

sudo gem list cocoapods

Then when you want to delete a version, specify that version.

sudo gem uninstall cocoapods -v 1.6.2

You could remove the version specifier -v 1.6.2 and that would delete all versions:

You may try all this and still see that the Cocoapods you expected is still installed. If that's the case then it might be because Cocoaposa is stored in a different directory.

sudo gem uninstall -n /usr/local/bin cocoapods -v 1.6.2

Then you will have to also install it in a different directory, otherwise you may get an error saying You don't have write permissions for the /usr/bin directory

sudo gem install -n /usr/local/bin cocoapods -v 1.6.1

To check which version is your default do:

pod --version

For more on the directory problem see here

Is it bad practice to use break to exit a loop in Java?

Good lord no. Sometimes there is a possibility that something can occur in the loop that satisfies the overall requirement, without satisfying the logical loop condition. In that case, break is used, to stop you cycling around a loop pointlessly.

Example

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
       //you've found the item. Let's stop.
       item = array[x];
       break; 
    }
}

What makes more sense in this example. Continue looping to 10 every time, even after you've found it, or loop until you find the item and stop? Or to put it into real world terms; when you find your keys, do you keep looking?

Edit in response to comment

Why not set x to 11 to break the loop? It's pointless. We've got break! Unless your code is making the assumption that x is definitely larger than 10 later on (and it probably shouldn't be) then you're fine just using break.

Edit for the sake of completeness

There are definitely other ways to simulate break. For example, adding extra logic to your termination condition in your loop. Saying that it is either loop pointlessly or use break isn't fair. As pointed out, a while loop can often achieve similar functionality. For example, following the above example..

while(x < 10 && item == null)
{
    if(array[x].equals("Item I am looking for"))
    {
        item = array[x];
    }

    x++;
}

Using break simply means you can achieve this functionality with a for loop. It also means you don't have to keep adding in conditions into your termination logic, whenever you want the loop to behave differently. For example.

for(int x = 0; x < 10; x++)
{
   if(array[x].equals("Something that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("Something else that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("This is what I want"))
   {
       item = array[x];
   }
}

Rather than a while loop with a termination condition that looks like this:

while(x < 10 && !array[x].equals("Something that will make me want to cancel") && 
                !array[x].equals("Something else that will make me want to cancel"))

converting a javascript string to a html object

Had the same issue. I used a dirty trick like so:

var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;

Now, you can add styles the way you like:

htmlObject.style.marginTop = something;

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

How to make MySQL handle UTF-8 properly

Your answer is you can configure by MySql Settings. In My Answer may be something gone out of context but this is also know is help for you.
how to configure Character Set and Collation.

For applications that store data using the default MySQL character set and collation (latin1, latin1_swedish_ci), no special configuration should be needed. If applications require data storage using a different character set or collation, you can configure character set information several ways:

  • Specify character settings per database. For example, applications that use one database might require utf8, whereas applications that use another database might require sjis.
  • Specify character settings at server startup. This causes the server to use the given settings for all applications that do not make other arrangements.
  • Specify character settings at configuration time, if you build MySQL from source. This causes the server to use the given settings for all applications, without having to specify them at server startup.

The examples shown here for your question to set utf8 character set , here also set collation for more helpful(utf8_general_ci collation`).

Specify character settings per database

  CREATE DATABASE new_db
  DEFAULT CHARACTER SET utf8
  DEFAULT COLLATE utf8_general_ci;

Specify character settings at server startup

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

Specify character settings at MySQL configuration time

shell> cmake . -DDEFAULT_CHARSET=utf8 \
           -DDEFAULT_COLLATION=utf8_general_ci

To see the values of the character set and collation system variables that apply to your connection, use these statements:

SHOW VARIABLES LIKE 'character_set%';
SHOW VARIABLES LIKE 'collation%';

This May be lengthy answer but there is all way, you can use. Hopeful my answer is helpful for you. for more information http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html

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

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

How to use BOOLEAN type in SELECT statement

You can definitely get Boolean value from a SELECT query, you just can't use a Boolean data-type.

You can represent a Boolean with 1/0.

CASE WHEN (10 > 0) THEN 1  ELSE 0 END (It can be used in SELECT QUERY)

SELECT CASE WHEN (10 > 0) THEN 1  ELSE 0 END AS MY_BOOLEAN_COLUMN
  FROM DUAL

Returns, 1 (in Hibernate/Mybatis/etc 1 is true). Otherwise, you can get printable Boolean values from a SELECT.

SELECT CASE WHEN (10 > 0) THEN 'true' ELSE 'false' END AS MY_BOOLEAN_COLUMN
 FROM DUAL

This returns the string 'true'.

When is "java.io.IOException:Connection reset by peer" thrown?

It can also mean that the server is completely inaccessible - I was getting this when trying to hit a server that was offline

My client was configured to connect to localhost:3000, but no server was running on that port.

Select records from today, this week, this month php mysql

Current month:

SELECT * FROM jokes WHERE YEAR(date) = YEAR(NOW()) AND MONTH(date)=MONTH(NOW());

Current week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date) = WEEKOFYEAR(NOW());

Current day:

SELECT * FROM jokes WHERE YEAR(date) = YEAR(NOW()) AND MONTH(date) = MONTH(NOW()) AND DAY(date) = DAY(NOW());

This will select only current month, really week and really only today :-)

View google chrome's cached pictures

You can make a bookmark with this as the url:

javascript:
var cached_anchors = $$('a');
for (var i in cached_anchors) {
    var ca = cached_anchors[i];
    if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {
        var a = document.createElement('a');
        a.href = ca.innerHTML;
        a.target = '_blank';

        var img = document.createElement('img');
        img.src = ca.innerHTML;
        img.style.maxHeight = '100px';

        a.appendChild(img);
        document.getElementsByTagName('body')[0].appendChild(a);
    }
}
document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]);
void(0);

Then just go to chrome://cache and then click your bookmark and it'll show you all the images.

How to make a new line or tab in <string> XML (eclipse/android)?

Use \t to add tab and \n for new line, here is a simple example below.

<string name="list_with_tab_tag">\tbanana\torange\tblueberry\tmango</string>
<string name="sentence_with_new_line_tag">This is the first sentence\nThis is the second scentence\nThis is the third sentence</string>

Java: how to import a jar file from command line

you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".

Getting checkbox values on submit

foreach is the best way to get array of values.

here the example code: html code:

<form action="send.php" method="post">
    Red<input type="checkbox" name="color[]" id="color" value="red">
    Green<input type="checkbox" name="color[]" id="color" value="green">
    Blue<input type="checkbox" name="color[]" id="color" value="blue">
    Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
    Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
    Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
    Black<input type="checkbox" name="color[]" id="color" value="black">
    <input type="submit" value="submit">
</form>

phpcode:

<?php

$name = $POST['color'];



foreach ($name as $color){ 
    echo $color."<br />";
}

?>

Index of element in NumPy array

You can use the function numpy.nonzero(), or the nonzero() method of an array

import numpy as np

A = np.array([[2,4],
          [6,2]])
index= np.nonzero(A>1)
       OR
(A>1).nonzero()

Output:

(array([0, 1]), array([1, 0]))

First array in output depicts the row index and second array depicts the corresponding column index.

How to use Class<T> in Java?

Using the generified version of class Class allows you, among other things, to write things like

Class<? extends Collection> someCollectionClass = someMethod();

and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.

PHP absolute path to root

This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php

<?php 
## DEFINE ROOTPATH
$check_data_exist = ""; 

$i_surf = 0;

// looking for mainpath.php at the aktiv folder or higher folder

while (!file_exists($check_data_exist."mainpath.php")) {
  $check_data_exist .= "../"; 
  $i_surf++;
  // max 7 folder deep
  if ($i_surf == 7) { 
   return false;
  }
}

define("MAINPATH", ($check_data_exist ? $check_data_exist : "")); 
?>

For me is that the best and easiest way to find them. ^^

Getting current date and time in JavaScript

I needed to figure this out for a slate in after effects. Here's what I came up with after taking elements from a few different sources -- Formatting is MM/DD/YYYY HH:MM AM/PM

D = new Date(Date(00));
M = D.getMonth()+1;
H = D.getHours();
Mi = D.getMinutes();

N = "AM"
if (H >= 12)
N = "PM"
if (H > 12)
{
H = H-12
}

amtOfZeroes = 2;
isNeg = false;

if (M < 0)
{
M = Math.abs(M);
isNeg = true;
}
Mo = Math.round(M) + "";
while(Mo.length < amtOfZeroes)
{

Mo = "0" + Mo; 
}
if (isNeg)
Mo = "-" + Mo;

if (H < 0)
{
H = Math.abs(H);
isNeg = true;
}
Ho = Math.round(H) + "";
while(Ho.length < amtOfZeroes)
{
Ho = "0" + Ho; 
}
if (isNeg)
Ho = "-" + Ho;

if (Mi < 0)
{
Mi = Math.abs(Mi);
isNeg = true;
}
Min = Math.round(Mi) + "";
while(Min.length < amtOfZeroes)
{
Min = "0" + Min; 
}
if (isNeg)
Min = "-" + Min;

T = Ho + ":" + (Min)

Mo + "/" + D.getDate() + "/" + D.getFullYear() + "  " + T + " " + N

Disable Rails SQL logging in console

In case someone wants to actually knock out SQL statement logging (without changing logging level, and while keeping the logging from their AR models):

The line that writes to the log (in Rails 3.2.16, anyway) is the call to debug in lib/active_record/log_subscriber.rb:50.

That debug method is defined by ActiveSupport::LogSubscriber.

So we can knock out the logging by overwriting it like so:

module ActiveSupport
  class LogSubscriber
    def debug(*args, &block)
    end
  end
end

Date in mmm yyyy format in postgresql

SELECT TO_CHAR(NOW(), 'Mon YYYY');

JavaScript - Get Portion of URL Path

window.location.href.split('/');

Will give you an array containing all the URL parts, which you can access like a normal array.

Or an ever more elegant solution suggested by @Dylan, with only the path parts:

window.location.pathname.split('/');

How do I encrypt and decrypt a string in python?

Try this:

Python Cryptography Toolkit (pycrypto) is required

$ pip install pycrypto

Code:

from Crypto.Cipher import AES
from base64 import b64encode, b64decode


class Crypt:

    def __init__(self, salt='SlTKeYOpHygTYkP3'):
        self.salt = salt.encode('utf8')
        self.enc_dec_method = 'utf-8'

    def encrypt(self, str_to_enc, str_key):
        try:
            aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
            hx_enc = aes_obj.encrypt(str_to_enc.encode('utf8'))
            mret = b64encode(hx_enc).decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Encryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Encryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

    def decrypt(self, enc_str, str_key):
        try:
            aes_obj = AES.new(str_key.encode('utf8'), AES.MODE_CFB, self.salt)
            str_tmp = b64decode(enc_str.encode(self.enc_dec_method))
            str_dec = aes_obj.decrypt(str_tmp)
            mret = str_dec.decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Decryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Decryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

Usage:

        test_crpt = Crypt()
        test_text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""

        test_key = 'MyKey4TestingYnP'
        test_enc_text = test_crpt.encrypt(test_text, test_key)
        test_dec_text = test_crpt.decrypt(test_enc_text, test_key)
        print(f'Encrypted:{test_enc_text}  Decrypted:{test_dec_text}')

how to delete the content of text file without deleting itself

Just write:

FileOutputStream writer = new FileOutputStream("file.txt");

Embed website into my site

Put content from other site in iframe

<iframe src="/othersiteurl" width="100%" height="300">
  <p>Your browser does not support iframes.</p>
</iframe>

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

How do you check in python whether a string contains only numbers?

you can use str.isdigit() method or str.isnumeric() method

'mat-form-field' is not a known element - Angular 5 & Material2

You're trying to use the MatFormFieldComponent in SearchComponent but you're not importing the MatFormFieldModule (which exports MatFormFieldComponent); you only export it.

Your MaterialModule needs to import it.

@NgModule({
  imports: [
    MatFormFieldModule,
  ],
  exports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
  ],
  declarations: [
    SearchComponent,
  ],
})
export class MaterialModule { }

Explaining Python's '__enter__' and '__exit__'

This is called context manager and I just want to add that similar approaches exist for other programming languages. Comparing them could be helpful in understanding the context manager in python. Basically, a context manager is used when we are dealing with some resources (file, network, database) that need to be initialized and at some point, tear downed (disposed). In Java 7 and above we have automatic resource management that takes the form of:

//Java code
try (Session session = new Session())
{
  // do stuff
}

Note that Session needs to implement AutoClosable or one of its (many) sub-interfaces.

In C#, we have using statements for managing resources that takes the form of:

//C# code
using(Session session = new Session())
{
  ... do stuff.
}

In which Session should implement IDisposable.

In python, the class that we use should implement __enter__ and __exit__. So it takes the form of:

#Python code
with Session() as session:
    #do stuff

And as others pointed out, you can always use try/finally statement in all the languages to implement the same mechanism. This is just syntactic sugar.

How to view AndroidManifest.xml from APK file?

The file needs to be decompiled (or deodex'd not sure which one). But here's another way to do it:

-Download free Tickle My Android tool on XDA: https://forum.xda-developers.com/showthread.php?t=1633333https://forum.xda-developers.com/showthread.php?t=1633333
-Unzip
-Copy APK into \_WorkArea1\_in\ folder
-Open "Tickle My Android.exe"
-Theming Menu
-Decompile Files->Any key to continue (ignore warning)
-Decompile Files->1->[Enter]->y[Enter]
-Wait for it to decompile in new window... Done when new window closes
-Decompiled/viewable files will be here: \_WorkArea3\_working\[App]\

Meaning of $? (dollar question mark) in shell scripts

Minimal POSIX C exit status example

To understand $?, you must first understand the concept of process exit status which is defined by POSIX. In Linux:

  • when a process calls the exit system call, the kernel stores the value passed to the system call (an int) even after the process dies.

    The exit system call is called by the exit() ANSI C function, and indirectly when you do return from main.

  • the process that called the exiting child process (Bash), often with fork + exec, can retrieve the exit status of the child with the wait system call

Consider the Bash code:

$ false
$ echo $?
1

The C "equivalent" is:

false.c

#include <stdlib.h> /* exit */

int main(void) {
    exit(1);
}

bash.c

#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */

int main(void) {
    if (fork() == 0) {
        /* Call false. */
        execl("./false", "./false", (char *)NULL);
    }
    int status;
    /* Wait for a child to finish. */
    wait(&status);
    /* Status encodes multiple fields,
     * we need WEXITSTATUS to get the exit status:
     * http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
     **/
    printf("$? = %d\n", WEXITSTATUS(status));
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash

Output:

$? = 1

In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $? to the exit status of the forked process.

Note: for built-in commands like echo, a process need not be spawned, and Bash just sets $? to 0 to simulate an external process.

Standards and documentation

POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :

? Expands to the decimal exit status of the most recent pipeline (see Pipelines).

man bash "Special Parameters":

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]

? Expands to the exit status of the most recently executed foreground pipeline.

ANSI C and POSIX then recommend that:

  • 0 means the program was successful

  • other values: the program failed somehow.

    The exact value could indicate the type of failure.

    ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?

Bash uses exit status for if

In Bash, we often use the exit status $? implicitly to control if statements as in:

if true; then
  :
fi

where true is a program that just returns 0.

The above is equivalent to:

true
result=$?
if [ $result = 0 ]; then
  :
fi

And in:

if [ 1 = 1 ]; then
  :
fi

[ is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ] its arguments, see also: Difference between single and double square brackets in Bash

How to get object length

Also can be done in this way:

Object.entries(obj).length

For example:

let obj = { a: 1, b: 2, };
console.log(Object.entries(obj).length); //=> 2
// Object.entries(obj) => [ [ 'a', 1 ], [ 'b', 2 ] ]

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

ORA-01861: literal does not match format string

A simple view like this was giving me the ORA-01861 error when executed from Entity Framework:

create view myview as 
select * from x where x.initialDate >= '01FEB2021'

Just did something like this to fix it:

create view myview as 
select * from x where x.initialDate >= TO_DATE('2021-02-01', 'YYYY-MM-DD')

I think the problem is EF date configuration is not the same as Oracle's.

Sort a Custom Class List<T>

You can use linq:

var q = from tag in Week orderby Convert.ToDateTime(tag.date) select tag;
List<cTag> Sorted = q.ToList()

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Apply function to all elements of collection through LINQ

For collections that do not support ForEach you can use static ForEach method in Parallel class:

var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 };
Parallel.ForEach(_your_collection_, options, x => x._Your_Method_());

Get first letter of a string from column

Cast the dtype of the col to str and you can perform vectorised slicing calling str:

In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df

Out[29]:
   First  Second new_col
0    123     234       1
1     22    4353       2
2     32     355       3
3    453     453       4
4     45     345       4
5    453     453       4
6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

bootstrap responsive table content wrapping

use it in css external file.

.td-table
{
word-wrap: break-word;
word-break: break-all;  
white-space: normal !important;
text-align: justify;
}

Should I use 'has_key()' or 'in' on Python dicts?

According to python docs:

has_key() is deprecated in favor of key in d.

Java program to get the current date without timestamp

Here is full Example of it.But you have to cast Sting back to Date.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format MM dd yyyy HH:mm:ss.SSSSSS
public class TestDateExample {

    public static void main(String args[]) throws ParseException {
        SimpleDateFormat changeFormat = new SimpleDateFormat("MM dd yyyy HH:mm:ss.SSSSSS");
         Date thisDate = new Date();//changeFormat.parse("10 07 2012"); 
         System.out.println("Current Date : " + thisDate);
         changeFormat.format(thisDate); 
        System.out.println("----------------------------"); 
        System.out.println("After applying formating :");
        String strDateOutput = changeFormat.format(thisDate);
        System.out.println(strDateOutput);

    }

}

Eaxmple

Using BeautifulSoup to extract text without tags

I think you could solve this with .strip() in gazpacho:

Input:

html = """\
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""

Code:

soup = Soup(html)
text = soup.find("p").strip(whitespace=False) # to keep \n characters intact
lines = [
    line.strip()
    for line in text.split("\n")
    if line != ""
]
data = dict([line.split(": ") for line in lines])

Output:

print(data)
# {'YOB': '1987',
#  'RACE': 'WHITE',
#  'GENDER': 'FEMALE',
#  'HEIGHT': "5'05''",
#  'WEIGHT': '118',
#  'EYE COLOR': 'GREEN',
#  'HAIR COLOR': 'BROWN'}

Github "Updates were rejected because the remote contains work that you do not have locally."

If you are using Visual S2019, Create a new local branch as shown in following, and then push the changes to the repo.

VS2019 local branch

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

How about

sudo yum install php-mysql

or

sudo apt-get install php5-mysql

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

UPDATE multiple tables in MySQL using LEFT JOIN

UPDATE `Table A` a
SET a.`text`=(
        SELECT group_concat(b.`B-num`,' from ',b.`date` SEPARATOR ' / ') 
        FROM `Table B` b WHERE (a.`A-num`=b.`A-num`)
)

Hiding user input on terminal in Linux script

Here's a variation on @SiegeX's excellent *-printing solution for bash with support for backspace added; this allows the user to correct their entry with the backspace key (delete key on a Mac), as is typically supported by password prompts:

#!/usr/bin/env bash

password=''
while IFS= read -r -s -n1 char; do
  [[ -z $char ]] && { printf '\n'; break; } # ENTER pressed; output \n and break.
  if [[ $char == $'\x7f' ]]; then # backspace was pressed
      # Remove last char from output variable.
      [[ -n $password ]] && password=${password%?}
      # Erase '*' to the left.
      printf '\b \b' 
  else
    # Add typed char to output variable.
    password+=$char
    # Print '*' in its stead.
    printf '*'
  fi
done

Note:

  • As for why pressing backspace records character code 0x7f: "In modern systems, the backspace key is often mapped to the delete character (0x7f in ASCII or Unicode)" https://en.wikipedia.org/wiki/Backspace
  • \b \b is needed to give the appearance of deleting the character to the left; just using \b moves the cursor to the left, but leaves the character intact (nondestructive backspace). By printing a space and moving back again, the character appears to have been erased (thanks, The "backspace" escape character '\b' in C, unexpected behavior?).

In a POSIX-only shell (e.g., sh on Debian and Ubuntu, where sh is dash), use the stty -echo approach (which is suboptimal, because it prints nothing), because the read builtin will not support the -s and -n options.

SET NAMES utf8 in MySQL?

Getting encoding right is really tricky - there are too many layers:

  • Browser
  • Page
  • PHP
  • MySQL

The SQL command "SET CHARSET utf8" from PHP will ensure that the client side (PHP) will get the data in utf8, no matter how they are stored in the database. Of course, they need to be stored correctly first.

DDL definition vs. real data

Encoding defined for a table/column doesn't really mean that the data are in that encoding. If you happened to have a table defined as utf8 but stored as differtent encoding, then MySQL will treat them as utf8 and you're in trouble. Which means you have to fix this first.

What to check

You need to check in what encoding the data flow at each layer.

  • Check HTTP headers, headers.
  • Check what's really sent in body of the request.
  • Don't forget that MySQL has encoding almost everywhere:
    • Database
    • Tables
    • Columns
    • Server as a whole
    • Client
      Make sure that there's the right one everywhere.

Conversion

If you receive data in e.g. windows-1250, and want to store in utf-8, then use this SQL before storing:

SET NAMES 'cp1250';

If you have data in DB as windows-1250 and want to retreive utf8, use:

SET CHARSET 'utf8';

Few more notes:

  • Don't rely on too "smart" tools to show the data. E.g. phpMyAdmin does (was doing when I was using it) encoding really bad. And it goes through all the layers so it's hard to find out.
  • Also, Internet Explorer had really stupid behavior of "guessing" the encoding based on weird rules.
  • Use simple editors where you can switch encoding. I recommend MySQL Workbench.

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

How can I use an http proxy with node.js http.Client?

Basically you don't need an explicit proxy support. Proxy protocol is pretty simple and based on the normal HTTP protocol. You just need to use your proxy host and port when connecting with HTTPClient. Example (from node.js docs):

var http = require('http');
var google = http.createClient(3128, 'your.proxy.host');
var request = google.request('GET', '/',
  {'host': 'www.google.com'});
request.end();
...

So basically you connect to your proxy but do a request to "http://www.google.com".

How to convert any date format to yyyy-MM-dd

You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:

string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

Here, SourceDate is variable in which you will get selected date.

Find running median from a stream of integers

If we want to find the median of the n most recently seen elements, this problem has an exact solution that only needs the n most recently seen elements to be kept in memory. It is fast and scales well.

An indexable skiplist supports O(ln n) insertion, removal, and indexed search of arbitrary elements while maintaining sorted order. When coupled with a FIFO queue that tracks the n-th oldest entry, the solution is simple:

class RunningMedian:
    'Fast running median with O(lg n) updates where n is the window size'

    def __init__(self, n, iterable):
        self.it = iter(iterable)
        self.queue = deque(islice(self.it, n))
        self.skiplist = IndexableSkiplist(n)
        for elem in self.queue:
            self.skiplist.insert(elem)

    def __iter__(self):
        queue = self.queue
        skiplist = self.skiplist
        midpoint = len(queue) // 2
        yield skiplist[midpoint]
        for newelem in self.it:
            oldelem = queue.popleft()
            skiplist.remove(oldelem)
            queue.append(newelem)
            skiplist.insert(newelem)
            yield skiplist[midpoint]

Here are links to complete working code (an easy-to-understand class version and an optimized generator version with the indexable skiplist code inlined):

Reading a registry key in C#

string InstallPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\AppPath", "Installed", null);    
if (InstallPath != null)
{
    // Do stuff
}

That code should get your value. You'll need to be

using Microsoft.Win32;

for that to work though.

How do I create a foreign key in SQL Server?

Like you, I don't usually create foreign keys by hand, but if for some reason I need the script to do so I usually create it using ms sql server management studio and before saving then changes, I select Table Designer | Generate Change Script

Efficient way to do batch INSERTS with JDBC

This is a mix of the two previous answers:

  PreparedStatement ps = c.prepareStatement("INSERT INTO employees VALUES (?, ?)");

  ps.setString(1, "John");
  ps.setString(2,"Doe");
  ps.addBatch();

  ps.clearParameters();
  ps.setString(1, "Dave");
  ps.setString(2,"Smith");
  ps.addBatch();

  ps.clearParameters();
  int[] results = ps.executeBatch();

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

How to stop event propagation with inline onclick attribute?

There are two ways to get the event object from inside a function:

  1. The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
  2. The window.event object in Internet Explorer (<=8)

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:

function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:

onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

How to add fonts to create-react-app based projects?

Here are some ways of doing this:

1. Importing font

For example, for using Roboto, install the package using

yarn add typeface-roboto

or

npm install typeface-roboto --save

In index.js:

import "typeface-roboto";

There are npm packages for a lot of open source fonts and most of Google fonts. You can see all fonts here. All the packages are from that project.

2. For fonts hosted by Third party

For example Google fonts, you can go to fonts.google.com where you can find links that you can put in your public/index.html

screenshot of fonts.google.com

It'll be like

<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

or

<style>
    @import url('https://fonts.googleapis.com/css?family=Montserrat');
</style>

3. Downloading the font and adding it in your source code.

Download the font. For example, for google fonts, you can go to fonts.google.com. Click on the download button to download the font.

Move the font to fonts directory in your src directory

src
|
`----fonts
|      |
|      `-Lato/Lato-Black.ttf
|       -Lato/Lato-BlackItalic.ttf
|       -Lato/Lato-Bold.ttf
|       -Lato/Lato-BoldItalic.ttf
|       -Lato/Lato-Italic.ttf
|       -Lato/Lato-Light.ttf
|       -Lato/Lato-LightItalic.ttf
|       -Lato/Lato-Regular.ttf
|       -Lato/Lato-Thin.ttf
|       -Lato/Lato-ThinItalic.ttf
|
`----App.css

Now, in App.css, add this

@font-face {
  font-family: 'Lato';
  src: local('Lato'), url(./fonts/Lato-Regular.otf) format('opentype');
}

@font-face {
    font-family: 'Lato';
    font-weight: 900;
    src: local('Lato'), url(./fonts/Lato-Bold.otf) format('opentype');
}

@font-face {
    font-family: 'Lato';
    font-weight: 900;
    src: local('Lato'), url(./fonts/Lato-Black.otf) format('opentype');
}

For ttf format, you have to mention format('truetype'). For woff, format('woff')

Now you can use the font in classes.

.modal-title {
    font-family: Lato, Arial, serif;
    font-weight: black;
}

4. Using web-font-loader package

Install package using

yarn add webfontloader

or

npm install webfontloader --save

In src/index.js, you can import this and specify the fonts needed

import WebFont from 'webfontloader';

WebFont.load({
   google: {
     families: ['Titillium Web:300,400,700', 'sans-serif']
   }
});

Wait for page load in Selenium

driver.asserts().assertElementFound("Page was not loaded",
By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT);

How to validate date with format "mm/dd/yyyy" in JavaScript?

var date = new Date(date_string)

returns the literal 'Invalid Date' for any invalid date_string.

Note: Please see the comment's below.

How to add a margin to a table row <tr>

Because margin is ignored on tr, I usually use a workaround, by setting a transparent border-bottom or border-top and setting the background-clip property to padding-box so the background-color does not get painted underneath the border.

table {
   border-collapse: collapse; /* [1] */
}

th, td {
  border-bottom: 5px solid transparent; /* [2] */
  background-color: gold; /* [3] */
  background-clip: padding-box; /* [4] */
}
  1. Makes sure cells share a common border, but is completely optional. The solution works without it.
  2. The 5px value represents the margin that you want to achieve
  3. Sets the background-color of your row/cell
  4. Makes sure the background get not painted underneath the border

see a demo here: http://codepen.io/meodai/pen/MJMVNR?editors=1100

background-clip is supported in all modern browser. (And IE9+)

Alternatively you could use a border-spacing. But this will not work with border-collapse set to collapse.

Declare a const array

A .NET Framework v4.5+ solution that improves on tdbeckett's answer:

using System.Collections.ObjectModel;

// ...

public ReadOnlyCollection<string> Titles { get; } = new ReadOnlyCollection<string>(
  new string[] { "German", "Spanish", "Corrects", "Wrongs" }
);

Note: Given that the collection is conceptually constant, it may make sense to make it static to declare it at the class level.

The above:

  • Initializes the property's implicit backing field once with the array.

    • Note that { get; } - i.e., declaring only a property getter - is what makes the property itself implicitly read-only (trying to combine readonly with { get; } is actually a syntax error).

    • Alternatively, you could just omit the { get; } and add readonly to create a field instead of a property, as in the question, but exposing public data members as properties rather than fields is a good habit to form.

  • Creates an array-like structure (allowing indexed access) that is truly and robustly read-only (conceptually constant, once created), both with respect to:

    • preventing modification of the collection as a whole (such as by removing or adding elements, or by assigning a new collection to the variable).
    • preventing modification of individual elements.
      (Even indirect modification isn't possible - unlike with an IReadOnlyList<T> solution, where a (string[]) cast can be used to gain write access to the elements, as shown in mjepsen's helpful answer.
      The same vulnerability applies to the IReadOnlyCollection<T> interface, which, despite the similarity in name to class ReadOnlyCollection, does not even support indexed access, making it fundamentally unsuitable for providing array-like access.)

setting multiple column using one update

UPDATE some_table 
   SET this_column=x, that_column=y 
   WHERE something LIKE 'them'

Nth word in a string variable

A file containing some statements :

cat test.txt

Result :

This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement

So, to print the 4th word of this statement type :

cat test.txt |awk '{print $4}'

Output :

1st
2nd
3rd
4th
5th

Change header text of columns in a GridView

On your asp.net page add the gridview

<asp:GridView ID="GridView1" onrowdatabound="GridView1_RowDataBound" >
</asp:GridView>

Create a method protected void method in your c# class called GridView1_RowDataBound

as

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Text = "HeaderText";
    }
}

Everything should be working fine.

How to add text inside the doughnut chart using Chart.js?

Here is cleaned up and combined example of above solutions - responsive (try to resize the window), supports animation self-aligning, supports tooltips

https://jsfiddle.net/cmyker/u6rr5moq/

_x000D_
_x000D_
Chart.types.Doughnut.extend({_x000D_
    name: "DoughnutTextInside",_x000D_
    showTooltip: function() {_x000D_
        this.chart.ctx.save();_x000D_
        Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);_x000D_
        this.chart.ctx.restore();_x000D_
    },_x000D_
    draw: function() {_x000D_
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);_x000D_
_x000D_
        var width = this.chart.width,_x000D_
            height = this.chart.height;_x000D_
_x000D_
        var fontSize = (height / 114).toFixed(2);_x000D_
        this.chart.ctx.font = fontSize + "em Verdana";_x000D_
        this.chart.ctx.textBaseline = "middle";_x000D_
_x000D_
        var text = "82%",_x000D_
            textX = Math.round((width - this.chart.ctx.measureText(text).width) / 2),_x000D_
            textY = height / 2;_x000D_
_x000D_
        this.chart.ctx.fillText(text, textX, textY);_x000D_
    }_x000D_
});_x000D_
_x000D_
var data = [{_x000D_
    value: 30,_x000D_
    color: "#F7464A"_x000D_
}, {_x000D_
    value: 50,_x000D_
    color: "#E2EAE9"_x000D_
}, {_x000D_
    value: 100,_x000D_
    color: "#D4CCC5"_x000D_
}, {_x000D_
    value: 40,_x000D_
    color: "#949FB1"_x000D_
}, {_x000D_
    value: 120,_x000D_
    color: "#4D5360"_x000D_
}];_x000D_
_x000D_
var DoughnutTextInsideChart = new Chart($('#myChart')[0].getContext('2d')).DoughnutTextInside(data, {_x000D_
    responsive: true_x000D_
});
_x000D_
<html>_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>_x000D_
<body>_x000D_
    <canvas id="myChart"></canvas>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

UPDATE 17.06.16:

Same functionality but for chart.js version 2:

https://jsfiddle.net/cmyker/ooxdL2vj/

_x000D_
_x000D_
var data = {_x000D_
  labels: [_x000D_
    "Red",_x000D_
    "Blue",_x000D_
    "Yellow"_x000D_
  ],_x000D_
  datasets: [_x000D_
    {_x000D_
      data: [300, 50, 100],_x000D_
      backgroundColor: [_x000D_
        "#FF6384",_x000D_
        "#36A2EB",_x000D_
        "#FFCE56"_x000D_
      ],_x000D_
      hoverBackgroundColor: [_x000D_
        "#FF6384",_x000D_
        "#36A2EB",_x000D_
        "#FFCE56"_x000D_
      ]_x000D_
    }]_x000D_
};_x000D_
_x000D_
Chart.pluginService.register({_x000D_
  beforeDraw: function(chart) {_x000D_
    var width = chart.chart.width,_x000D_
        height = chart.chart.height,_x000D_
        ctx = chart.chart.ctx;_x000D_
_x000D_
    ctx.restore();_x000D_
    var fontSize = (height / 114).toFixed(2);_x000D_
    ctx.font = fontSize + "em sans-serif";_x000D_
    ctx.textBaseline = "middle";_x000D_
_x000D_
    var text = "75%",_x000D_
        textX = Math.round((width - ctx.measureText(text).width) / 2),_x000D_
        textY = height / 2;_x000D_
_x000D_
    ctx.fillText(text, textX, textY);_x000D_
    ctx.save();_x000D_
  }_x000D_
});_x000D_
_x000D_
var chart = new Chart(document.getElementById('myChart'), {_x000D_
  type: 'doughnut',_x000D_
  data: data,_x000D_
  options: {_x000D_
   responsive: true,_x000D_
    legend: {_x000D_
      display: false_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>_x000D_
<canvas id="myChart"></canvas>
_x000D_
_x000D_
_x000D_

ffmpeg usage to encode a video to H264 codec format

I believe you have libx264 installed and configured with ffmpeg to convert video to h264... Then you can try with -vcodec libx264... The -format option is for showing available formats, this is not a conversion option I think...

How to declare empty list and then add string in scala?

Maybe you can use ListBuffers in scala to create empty list and add strings later because ListBuffers are mutable. Also all the List functions are available for the ListBuffers in scala.

import scala.collection.mutable.ListBuffer 

val dm = ListBuffer[String]()
dm: scala.collection.mutable.ListBuffer[String] = ListBuffer()
dm += "text1"
dm += "text2"
dm = ListBuffer(text1, text2)

if you want you can convert this to a list by using .toList

Enable/Disable Anchor Tags using AngularJS

For people not wanting a complicated answer, I used Ng-If to solve this for something similar:

<div style="text-align: center;">
 <a ng-if="ctrl.something != null" href="#" ng-click="ctrl.anchorClicked();">I'm An Anchor</a>
 <span ng-if="ctrl.something == null">I'm just text</span>
</div>

How to Deep clone in javascript

This is the deep cloning method I use, I think it Great, hope you make suggestions

function deepClone (obj) {
    var _out = new obj.constructor;

    var getType = function (n) {
        return Object.prototype.toString.call(n).slice(8, -1);
    }

    for (var _key in obj) {
        if (obj.hasOwnProperty(_key)) {
            _out[_key] = getType(obj[_key]) === 'Object' || getType(obj[_key]) === 'Array' ? deepClone(obj[_key]) : obj[_key];
        }
    }
    return _out;
}

Backporting Python 3 open(encoding="utf-8") to Python 2

1. To get an encoding parameter in Python 2:

If you only need to support Python 2.6 and 2.7 you can use io.open instead of open. io is the new io subsystem for Python 3, and it exists in Python 2,6 ans 2.7 as well. Please be aware that in Python 2.6 (as well as 3.0) it's implemented purely in python and very slow, so if you need speed in reading files, it's not a good option.

If you need speed, and you need to support Python 2.6 or earlier, you can use codecs.open instead. It also has an encoding parameter, and is quite similar to io.open except it handles line-endings differently.

2. To get a Python 3 open() style file handler which streams bytestrings:

open(filename, 'rb')

Note the 'b', meaning 'binary'.

Format cell color based on value in another sheet and cell

You can also do this with named ranges so you don't have to copy the cells from Sheet1 to Sheet2:

  1. Define a named range, say Sheet1Vals for the column that has the values on which you want to base your condition. You can define a new named range by using the Insert\Name\Define... menu item. Type in your name, then use the cell browser in the Refers to box to select the cells you want in the range. If the range will change over time (add or remove rows) you can use this formula instead of selecting the cells explicitly:

    =OFFSET('SheetName'!$COL$ROW,0,0,COUNTA('SheetName'!$COL:$COL)).

    Add a -1 before the last ) if the column has a header row.

  2. Define a named range, say Sheet2Vals for the column that has the values you want to conditionally format.

  3. Use the Conditional Formatting dialog to create your conditions. Specify Formula Is in the dropdown, then put this for the formula:

    =INDEX(Sheet1Vals, MATCH([FirstCellInRange],Sheet2Vals))=[Condition]

    where [FirstCellInRange] is the address of the cell you want to format and [Condition] is the value your checking.

For example, if my conditions in Sheet1 have the values of 1, 2 and 3 and the column I'm formatting is column B in Sheet2 then my conditional formats would be something like:

=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=1
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=2
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=3

You can then use the format painter to copy these formats to the rest of the cells.

Xcode error "Could not find Developer Disk Image"

It works, in my case for Xcode from 7.3 TO 7.1. Copy directory 9.2, for iOS device OS 9.2.1.

Why does one use dependency injection?

The main reason to use DI is that you want to put the responsibility of the knowledge of the implementation where the knowledge is there. The idea of DI is very much inline with encapsulation and design by interface. If the front end asks from the back end for some data, then is it unimportant for the front end how the back end resolves that question. That is up to the requesthandler.

That is already common in OOP for a long time. Many times creating code pieces like:

I_Dosomething x = new Impl_Dosomething();

The drawback is that the implementation class is still hardcoded, hence has the front end the knowledge which implementation is used. DI takes the design by interface one step further, that the only thing the front end needs to know is the knowledge of the interface. In between the DYI and DI is the pattern of a service locator, because the front end has to provide a key (present in the registry of the service locator) to lets its request become resolved. Service locator example:

I_Dosomething x = ServiceLocator.returnDoing(String pKey);

DI example:

I_Dosomething x = DIContainer.returnThat();

One of the requirements of DI is that the container must be able to find out which class is the implementation of which interface. Hence does a DI container require strongly typed design and only one implementation for each interface at the same time. If you need more implementations of an interface at the same time (like a calculator), you need the service locator or factory design pattern.

D(b)I: Dependency Injection and Design by Interface. This restriction is not a very big practical problem though. The benefit of using D(b)I is that it serves communication between the client and the provider. An interface is a perspective on an object or a set of behaviours. The latter is crucial here.

I prefer the administration of service contracts together with D(b)I in coding. They should go together. The use of D(b)I as a technical solution without organizational administration of service contracts is not very beneficial in my point of view, because DI is then just an extra layer of encapsulation. But when you can use it together with organizational administration you can really make use of the organizing principle D(b)I offers. It can help you in the long run to structure communication with the client and other technical departments in topics as testing, versioning and the development of alternatives. When you have an implicit interface as in a hardcoded class, then is it much less communicable over time then when you make it explicit using D(b)I. It all boils down to maintenance, which is over time and not at a time. :-)

VBA check if file exists

I use this function to check for file existence:

Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
    On Error Resume Next
    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function

ANTLR: Is there a simple example?

At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4

is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:

  1. parser grammar
  2. lexer grammar
  3. imported LexBasic grammar

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.

Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin

https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr

contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.

XML Schema minOccurs / maxOccurs default values

example:

XML

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<country xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="country.xsd">
    <countryName>Australia</countryName>
    <capital>Canberra</capital>
    <nationalLanguage>English</nationalLanguage>
    <population>21000000</population>
    <currency>Australian Dollar</currency>
    <nationalIdentities>
        <nationalAnthem>Advance Australia Fair</nationalAnthem>
        <nationalDay>Australia Day (26 January)</nationalDay>
        <nationalColour>Green and Gold</nationalColour>
        <nationalGemstone>Opal</nationalGemstone>
        <nationalFlower>Wattle (Acacia pycnantha)</nationalFlower>
    </nationalIdentities>
    <publicHolidays>
        <newYearDay>1 January</newYearDay>
        <australiaDay>26 January</australiaDay>
        <anzacDay>25 April</anzacDay>
        <christmasDay>25 December</christmasDay>
        <boxingDay>26 December</boxingDay>
        <laborDay>Variable Date</laborDay>
        <easter>Variable Date</easter>
        <queenBirthDay>21 April (Variable Date)</queenBirthDay>
    </publicHolidays>
    <states>
        <stateName><Name>NSW -  New South Wales</Name></stateName>
        <stateName><Name>VIC -  Victoria</Name></stateName>
        <stateName><Name>QLD -  Queensland</Name></stateName>
        <stateName><Name>SA -  South Australia</Name></stateName>
        <stateName><Name>WA -  Western Australia</Name></stateName>
        <stateName><Name>TAS -  Tasmania</Name></stateName>
    </states>
    <territories>
        <territoryName>ACT -  Australian Capital Territory</territoryName>
        <territoryName>NT -  Northern Territory</territoryName>
    </territories>
</country>

XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="country">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="countryName" type="xs:string"/>
                <xs:element name="capital" type="xs:string"/>
                <xs:element name="nationalLanguage" type="xs:string"/>
                <xs:element name="population" type="xs:double"/>
                <xs:element name="currency" type="xs:string"/>
                <xs:element name="nationalIdentities">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="nationalAnthem" type="xs:string"/>
                        <xs:element name="nationalDay" type="xs:string"/>
                        <xs:element name="nationalColour" type="xs:string"/>
                        <xs:element name="nationalGemstone" type="xs:string"/>
                        <xs:element name="nationalFlower" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
                <xs:element name="publicHolidays">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="newYearDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="australiaDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="anzacDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="christmasDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="boxingDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="laborDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="easter" maxOccurs="1" type="xs:string"/>
                            <xs:element name="queenBirthDay" maxOccurs="1" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="states">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="stateName" minOccurs="1" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Name" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="territories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="territoryName" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSL:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" version="4.0"/>
    <xsl:template match="/">
        <html>
            <body>          
                <xsl:for-each select="country">         
                    <xsl:value-of select="countryName"/><br/>
                    <xsl:value-of select="capital"/><br/>
                    <xsl:value-of select="nationalLanguage"/><br/>
                    <xsl:value-of select="population"/><br/>
                    <xsl:value-of select="currency"/><br/>              
                    <xsl:for-each select="nationalIdentities">
                        <xsl:value-of select="nationalAnthem"/><br/>
                        <xsl:value-of select="nationalDay"/><br/>
                        <xsl:value-of select="nationalColour"/><br/>
                        <xsl:value-of select="nationalGemstone"/><br/>
                        <xsl:value-of select="nationalFlower"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="publicHolidays">
                        <xsl:value-of select="newYearDay"/><br/>
                        <xsl:value-of select="australiaDay"/><br/>
                        <xsl:value-of select="anzacDay"/><br/>
                        <xsl:value-of select="christmasDay"/><br/>
                        <xsl:value-of select="boxingDay"/><br/>
                        <xsl:value-of select="laborDay"/><br/>
                        <xsl:value-of select="easter"/><br/>
                        <xsl:value-of select="queenBirthDay"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="states/stateName">
                        <xsl:value-of select="Name"/><br/>
                    </xsl:for-each>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Result:

Australia
Canberra
English
21000000
Australian Dollar
Advance Australia Fair
Australia Day (26 January)
Green and Gold
Opal
Wattle (Acacia pycnantha)
1 January
26 January
25 April
25 December
26 December
Variable Date
Variable Date
21 April (Variable Date)
NSW - New South Wales
VIC - Victoria
QLD - Queensland
SA - South Australia
WA - Western Australia
TAS - Tasmania

Which ChromeDriver version is compatible with which Chrome Browser version?

This is a helpful website listing the mapping for the latest releases of Chrome -

https://www.uitests-chromedrivermapping.com

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

How to find the Git commit that introduced a string in any branch?

git log -S"string_to_search" # options like --source --reverse --all etc

Pay attention not to use spaces between S and "string_to_search". In some setups (git 1.7.1), you'll get an error like:

fatal: ambiguous argument 'string_to_search': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

Why fragments, and when to use fragments instead of activities?

A fragment lives inside an activity, while an activity lives by itself.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

There is an MSDN blog article on investigating this type of issues:

Troubleshooting ASP.NET – The remote certificate is invalid according to the validation procedure:
http://blogs.msdn.com/b/jpsanders/archive/2009/09/16/troubleshooting-asp-net-the-remote-certificate-is-invalid-according-to-the-validation-procedure.aspx

The import org.apache.commons cannot be resolved in eclipse juno

You could also add the external jar file to the project. Go to your project-->properties-->java build path-->libraries, add external JARS. Then add your downloaded jar file.

How can I run a php without a web server?

PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.

Example PHP file:

#!/usr/bin/env php

<?php

echo("Hello World!\n")

?>

How to run it:

$ chmod 755 hello.php  # do this only once
$ ./hello.php

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

How do you determine what technology a website is built on?

I use WebParser (http://www.cybermake.com) that allows to determine the CMS used by a website. It allows to determine CMS for multiple websites as well as it can pull the list of websites from the search engines for a given list of keywords. Powerful tool.

Consider defining a bean of type 'service' in your configuration [Spring boot]

Please make sure that you have added the dependency in pom.xml or gradle file

spring-boot-starter-data-jpa

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.

How to get the unique ID of an object which overrides hashCode()?

System.identityHashCode(yourObject) will give the 'original' hash code of yourObject as an integer. Uniqueness isn't necessarily guaranteed. The Sun JVM implementation will give you a value which is related to the original memory address for this object, but that's an implementation detail and you shouldn't rely on it.

EDIT: Answer modified following Tom's comment below re. memory addresses and moving objects.

Passing headers with axios POST request

This might be helpful,

_x000D_
_x000D_
const data = {_x000D_
  email: "[email protected]",_x000D_
  username: "me"_x000D_
};_x000D_
_x000D_
const options = {_x000D_
  headers: {_x000D_
      'Content-Type': 'application/json',_x000D_
  }_x000D_
};_x000D_
_x000D_
axios.post('http://path', data, options)_x000D_
 .then((res) => {_x000D_
   console.log("RESPONSE ==== : ", res);_x000D_
 })_x000D_
 .catch((err) => {_x000D_
   console.log("ERROR: ====", err);_x000D_
 })
_x000D_
_x000D_
_x000D_ Note: All status codes above 400 will be caught in the Axios catch block. Also, headers are optional for the post method in Axios

Blockquote

Blockquote

Mod of negative number is melting my brain

For the more performance aware devs

uint wrap(int k, int n) ((uint)k)%n

A small performance comparison

Modulo: 00:00:07.2661827 ((n%x)+x)%x)
Cast:   00:00:03.2202334 ((uint)k)%n
If:     00:00:13.5378989 ((k %= n) < 0) ? k+n : k

As for performance cost of cast to uint have a look here

How do I make a burn down chart in Excel?

Thank you for your answers! They definitely led me on the right track. But none of them completely got me everything I wanted, so here's what I actually ended up doing.

The key piece of information I was missing was that I needed to put the data together in one big block, but I could still leave empty cells in it. Something like this:

  Date         Actual remaining     Desired remaining
7/13/2009            7350                 7350
7/15/2009            7100
7/21/2009            7150
7/23/2009            6600
7/27/2009            6550
8/8/2009             6525
8/16/2009            6200
11/3/2009                                  0

Now I have something Excel is a little better at charting. So long as I set the chart options to "Show empty cells as: Connect data points with line," it ends up looking pretty nice. Using the above test data:

Book burn down chart

Then I just needed my update macro to insert new rows above the last one to fill in new data whenever I want. My macro looks something like this:

' Find the last cell on the left going down.  This will be the last cell 
' in the "Date" column
Dim left As Range
Set left = Range("A1").End(xlDown)

' Move two columns to the right and select so we have the 3 final cells, 
' including "Date", "Actual remaining", and "Desired remaining"
Dim bottom As Range
Set bottom = Range(left.Cells(1), left.Offset(0, 2))

' Insert a new blank row, and then move up to account for it
bottom.Insert (xlShiftDown)
Set bottom = bottom.Offset(-1)

' We are now sitting on some blank cells very close to the end of the data,
' and are ready to paste in new values for the date and new pages remaining

' (I do this by grabbing some other cells and doing a PasteSpecial into bottom)

Improvement suggestions on that macro are welcome. I just fiddled with it until it worked.

Now I have a pretty chart and I can nerd out all I want with my nerdy books for nerds.

Pandas Merge - How to avoid duplicating columns

This is a bit of going around the problem, but I have written a function that basically deals with the extra columns:

def merge_fix_cols(df_company,df_product,uniqueID):
    
    df_merged = pd.merge(df_company,
                         df_product,
                         how='left',left_on=uniqueID,right_on=uniqueID)    
    for col in df_merged:
        if col.endswith('_x'):
            df_merged.rename(columns = lambda col:col.rstrip('_x'),inplace=True)
        elif col.endswith('_y'):
            to_drop = [col for col in df_merged if col.endswith('_y')]
            df_merged.drop(to_drop,axis=1,inplace=True)
        else:
            pass
    return df_merged

Seems to work well with my merges!

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

How should I declare default values for instance variables in Python?

With dataclasses, a feature added in Python 3.7, there is now yet another (quite convenient) way to achieve setting default values on class instances. The decorator dataclass will automatically generate a few methods on your class, such as the constructor. As the documentation linked above notes, "[t]he member variables to use in these generated methods are defined using PEP 526 type annotations".

Considering OP's example, we could implement it like this:

from dataclasses import dataclass

@dataclass
class Foo:
    num: int = 0

When constructing an object of this class's type we could optionally overwrite the value.

print('Default val: {}'.format(Foo()))
# Default val: Foo(num=0)
print('Custom val: {}'.format(Foo(num=5)))
# Custom val: Foo(num=5)

How can I get my webapp's base URL in ASP.NET MVC?

This is a conversion of an asp.net property to MVC . It's a pretty much all singing all dancing get root url method.

Declare a helper class:

namespace MyTestProject.Helpers
{
    using System.Web;

    public static class PathHelper
    {
        public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
        {
            string appPath = string.Empty;

            if (httpRequestBase != null)
            {
                //Formatting the fully qualified website url/name
                appPath = string.Format("{0}://{1}{2}{3}",
                            httpRequestBase.Url.Scheme,
                            httpRequestBase.Url.Host,
                            httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
                            httpRequestBase.ApplicationPath);
            }

            if (!appPath.EndsWith("/"))
            {
                appPath += "/";
            }

            return appPath;
        }
    }
}

Usage:

To use from a controller:

PathHelper.FullyQualifiedApplicationPath(ControllerContext.RequestContext.HttpContext.Request)

To use in a view:

@using MyTestProject.Helpers

PathHelper.FullyQualifiedApplicationPath(Request)

No Access-Control-Allow-Origin header is present on the requested resource

Solution:
Instead of using setHeader method I have used addHeader.

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains, For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

For issues related to IE<=9, Please see here.

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

Did you forget to add the init.py in your package?

How to execute a Ruby script in Terminal?

For those not getting a solution for older answers, i simply put my file name as the very first line in my code.

like so

 #ruby_file_name_here.rb

 puts "hello world"

java.lang.RuntimeException: Uncompilable source code - what can cause this?

Just check the packaging, the simplest answer I can provide is that your package has been mislabeled (within a class).

Also, you may have some weird characters. Try white-flushing the code in a Notepad (or Gedit) and then pasting it into a newly created class with your IDE.

How to take off line numbers in Vi?

To turn off line numbering, again follow the preceding instructions, except this time enter the following line at the : prompt:

set nonumber

How to get the system uptime in Windows?

I use this little PowerShell snippet:

function Get-SystemUptime {
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    "$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}

which then yields something like the following:

PS> Get-SystemUptime
6.20:40:40.2625526

How do you set the EditText keyboard to only consist of numbers on Android?

For the EditText if we specify,

android:inputType="number"

only numbers can be got. But if you use,

android:inputType="phone"

along with the numbers it can accept special characters like ;,/". etc.

ReactJS - Add custom event listener to component

You could use componentDidMount and componentWillUnmount methods:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MovieItem extends Component
{
    _handleNVEvent = event => {
        ...
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
    }

    componentWillUnmount() {
        ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
    }

    [...]

}

export default MovieItem;

What is the HTML unicode character for a "tall" right chevron?

Use '›'

&rsaquo; -> single right angle quote. For single left angle quote, use &lsaquo;

Convert JavaScript String to be all lower case?

Simply use JS toLowerCase()
let v = "Your Name" let u = v.toLowerCase(); or
let u = "Your Name".toLowerCase();

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

Remove border radius from Select tag in bootstrap 3

In addition to border-radius: 0, add -webkit-appearance: none;.

How to split the name string in mysql?

DELIMITER $$

DROP FUNCTION IF EXISTS `split_name`$$

CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
    READS SQL DATA
BEGIN
    DECLARE v_words INT UNSIGNED;
    DECLARE v_name TEXT;

    SET p_fullname=RTRIM(LTRIM(p_fullname));

    SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));

    IF v_words=1 THEN 
        IF p_part=1 THEN
            SET v_name=p_fullname;
        ELSEIF p_part=2 THEN
            SET v_name=NULL;
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=2 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words>3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
            SET v_name=REVERSE(p_fullname);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF;
    ELSE
        SET v_name=NULL;
    END IF;
 RETURN v_name; 
END;

SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name

Calculating the sum of two variables in a batch script

You need to use the property /a on the set command.

For example,

set /a "c=%a%+%b%"

This allows you to use arithmetic expressions in the set command, rather than simple concatenation.

Your code would then be:

@set a=3
@set b=4
@set /a "c=%a%+%b%"
echo %c%
@set /a "d=%c%+1"
echo %d%

and would output:

7
8

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:

$.get('/service', function(data) {  
  var obj = data;

      /* 
         "obj" is evaluated at this point if server responded 
         with "application/json" or similar.
       */
      for (var i = 0; i < obj.length; i++) {
        console.log(obj[i].Name);
      }
    });

Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify:

var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);

But in this case I don't understand why you can't just take the json variable and refer to it instead of stringifying and parsing.

How do I create directory if it doesn't exist to create a file?

To Create

(new FileInfo(filePath)).Directory.Create() Before writing to the file.

....Or, If it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);

When to Redis? When to MongoDB?

Difficult question to answer - as with most technology solutions, it really depends on your situation and since you have not described the problem you are trying to solve, how can anyone propose a solution?

You need to test them both to see which of them satisfied your needs.

With that said, MongoDB does not require any expensive hardware. Like any other database solution, it will work better with more CPU and memory but is certainly not a requirement - especially for early development purposes.

How can I read the contents of an URL with Python?

We can read website html content as below :

from urllib.request import urlopen
response = urlopen('http://google.com/')
html = response.read()
print(html)

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.

As soon as you show a Dialog it throws the error:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

You can see its a MessageBox causing the problem in the stack trace:

at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon,  MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)  

Solution

If you're running your app on a Scheduled Task send an email instead of showing a Dialog.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

SendRedirect() will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.

RquestDispatcher is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect() method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.

How to use bootstrap-theme.css with bootstrap 3?

For an example of the css styles have a look at: http://getbootstrap.com/examples/theme/

If you want to see how the example looks without the bootstrap-theme.css file open up your browser developer tools and delete the link from the <head> of the example and then you can compare it.

I know this is an old question but posted it just in case anyone is looking for an example of how it looks like I was.

Update

bootstrap.css = main css framework (grids, basic styles, etc)

bootstrap-theme.css = extended styling (3D buttons, gradients etc). This file is optional and does not effect the functionality of bootstrap at all, it only enhances the appearance.

Update 2

With the release of v3.2.0 Bootstrap have added an option to view the theme css on the doc pages. If you go to one of the doc pages (css, components, javascript) you should see a "Preview theme" link at the bottom of the side nav which you can use to turn the theme css on and off.

Create a shortcut on Desktop

Here is a piece of code that has no dependency on an external COM object (WSH), and supports 32-bit and 64-bit programs:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

namespace TestShortcut
{
    class Program
    {
        static void Main(string[] args)
        {
            IShellLink link = (IShellLink)new ShellLink();

            // setup shortcut information
            link.SetDescription("My Description");
            link.SetPath(@"c:\MyPath\MyProgram.exe");

            // save it
            IPersistFile file = (IPersistFile)link;
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            file.Save(Path.Combine(desktopPath, "MyLink.lnk"), false);
        }
    }

    [ComImport]
    [Guid("00021401-0000-0000-C000-000000000046")]
    internal class ShellLink
    {
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("000214F9-0000-0000-C000-000000000046")]
    internal interface IShellLink
    {
        void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
        void GetIDList(out IntPtr ppidl);
        void SetIDList(IntPtr pidl);
        void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
        void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
        void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
        void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
        void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
        void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
        void GetHotkey(out short pwHotkey);
        void SetHotkey(short wHotkey);
        void GetShowCmd(out int piShowCmd);
        void SetShowCmd(int iShowCmd);
        void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
        void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
        void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
        void Resolve(IntPtr hwnd, int fFlags);
        void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
    }
}

add item to dropdown list in html using javascript

Try this

<script type="text/javascript">
    function AddItem()
    {
        // Create an Option object       
        var opt = document.createElement("option");        

        // Assign text and value to Option object
        opt.text = "New Value";
        opt.value = "New Value";

        // Add an Option object to Drop Down List Box
        document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
    }
<script />

The Value will append to the drop down list.

Initialising an array of fixed size in python

>>> n = 5                     #length of list
>>> list = [None] * n         #populate list, length n with n entries "None"
>>> print(list)
[None, None, None, None, None]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, None, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, 1, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, 1, 1, 1]

or with really nothing in the list to begin with:

>>> n = 5                     #length of list
>>> list = []                 # create list
>>> print(list)
[]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1]

on the 4th iteration of append:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1]

5 and all subsequent:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1,1]

How to get the error message from the error code returned by GetLastError()?

If you're using c# you can use this code:

using System.Runtime.InteropServices;

public static class WinErrors
{
    #region definitions
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr LocalFree(IntPtr hMem);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, IntPtr Arguments);

    [Flags]
    private enum FormatMessageFlags : uint
    {
        FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
        FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
        FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
        FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000,
        FORMAT_MESSAGE_FROM_HMODULE = 0x00000800,
        FORMAT_MESSAGE_FROM_STRING = 0x00000400,
    }
    #endregion

    /// <summary>
    /// Gets a user friendly string message for a system error code
    /// </summary>
    /// <param name="errorCode">System error code</param>
    /// <returns>Error string</returns>
    public static string GetSystemMessage(int errorCode)
    {
        try
        {
            IntPtr lpMsgBuf = IntPtr.Zero;

            int dwChars = FormatMessage(
                FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER | FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM | FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS,
                IntPtr.Zero,
                (uint) errorCode,
                0, // Default language
                ref lpMsgBuf,
                0,
                IntPtr.Zero);
            if (dwChars == 0)
            {
                // Handle the error.
                int le = Marshal.GetLastWin32Error();
                return "Unable to get error code string from System - Error " + le.ToString();
            }

            string sRet = Marshal.PtrToStringAnsi(lpMsgBuf);

            // Free the buffer.
            lpMsgBuf = LocalFree(lpMsgBuf);
            return sRet;
        }
        catch (Exception e)
        {
            return "Unable to get error code string from System -> " + e.ToString();
        }
    }
}

Permanently add a directory to PYTHONPATH?

In case anyone is still confused - if you are on a Mac, do the following:

  1. Open up Terminal
  2. Type open .bash_profile
  3. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. Save the file, restart the Terminal, and you're done

Executing <script> elements inserted with .innerHTML

Try this, it works for me on Chrome, Safari & Firefox:

var script = document.createElement('script');
script.innerHTML = 'console.log("hi")';
document.body.appendChild(script); 
--> logs "hi"

One thing to note though, is that the following div-nested script will NOT run:

var script = document.createElement('div');
script.innerHTML = '<script>console.log("hi")</script>';
document.body.appendChild(script);
--> doesn't log anything

For a script to run it has to be created as a node then appended as a child. You can even append a script inside a previously injected div & it will run (I've run into this before when trying to get ad server code to work):

var div = document.createElement('div');
div.id = 'test-id';
document.body.appendChild(div);
var script = document.createElement('script');
script.innerHTML = 'console.log("hi")';
document.getElementById('test-id').appendChild(script);
--> logs "hi"

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<style>
a{
cursor: default;
}
</style>

In the above code [cursor:default] is used. Default is the usual arrow cursor that appears.

And if you use [cursor: pointer] then you can access to the hand like cursor that appears when you hover over a link.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

SQL Sum Multiple rows into one

You're grouping with BillDate, but the bill dates are different for each account so your rows are not being grouped. If you think about it, that doesn't even make sense - they are different bills, and have different dates. The same goes for the Bill - you're attempting to sum bills for an account, why would you group by that?

If you leave BillDate and Bill off of the select and group by clauses you'll get the correct results.

SELECT AccountNumber, SUM(Bill)
FROM Table1
GROUP BY AccountNumber

How can I select rows with most recent timestamp for each key value?

This can de done in a relatively elegant way using SELECT DISTINCT, as follows:

SELECT DISTINCT ON (sensorID)
sensorID, timestamp, sensorField1, sensorField2 
FROM sensorTable
ORDER BY sensorID, timestamp DESC;

The above works for PostgreSQL (some more info here) but I think also other engines. In case it's not obvious, what this does is sort the table by sensor ID and timestamp (newest to oldest), and then returns the first row (i.e. latest timestamp) for each unique sensor ID.

In my use case I have ~10M readings from ~1K sensors, so trying to join the table with itself on a timestamp-based filter is very resource-intensive; the above takes a couple of seconds.

UL list style not applying

Turns out that YUI's reset CSS strips the list style from 'ul li' instead of just 'ul', which is why setting it just in 'ul' never worked.

SQL: How to properly check if a record exists

The other answers are quite good, but it would also be useful to add LIMIT 1 (or the equivalent, to prevent the checking of unnecessary rows.

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

This problem has nothing to do with the linker, so modifying it's setting won't affect the outcome. You're getting this because I assume you're trying to target x86 but for one reason or another wxcode_msw28d_freechart.lib is being built as an x64 file.

Try looking at wxcode_msw28d_freechart.lib and whatever source code it derives from. Your problem is happening there. See if there are some special build steps that are using the wrong set of tools (x64 instead of x86).

Java: Convert a String (representing an IP) to InetAddress

Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

InetAddress javadoc

How to use the TextWatcher class in Android?

A little bigger perspective of the solution:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourlayout, container, false);
        View tv = v.findViewById(R.id.et1);
        ((TextView) tv).addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                 SpannableString contentText = new SpannableString(((TextView) tv).getText());
                 String contents = Html.toHtml(contentText).toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });
        return v;
    }

This works for me, doing it my first time.

How to add many functions in ONE ng-click?

The standard way to add Multiple functions

<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>

or

<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.

The best option is using a server side script like the one posted by jellyfishtree.

One line if/else condition in linux shell scripting

It's not a direct answer to the question but you could just use the OR-operator

( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."

Uninstall Eclipse under OSX?

Deleting the eclipse folder is equivalent to uninstalling it. In fact, if you don't want to tamper with the existing installation you can create another instance of eclipse and run from the new location.

.NET Console Application Exit Event

Here is a complete, very simple .Net solution that works in all versions of windows. Simply paste it into a new project, run it and try CTRL-C to view how it handles it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace TestTrapCtrlC{
    public class Program{
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
         CTRL_C_EVENT = 0,
         CTRL_BREAK_EVENT = 1,
         CTRL_CLOSE_EVENT = 2,
         CTRL_LOGOFF_EVENT = 5,
         CTRL_SHUTDOWN_EVENT = 6
         }

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
             exitSystem = true;

            //shutdown right away so there are no lingering threads
            Environment.Exit(-1);

            return true;
        }
        #endregion

        static void Main(string[] args) {
            // Some biolerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();
            p.Start();

            //hold the console so it doesn’t run off the end
            while(!exitSystem) {
                Thread.Sleep(500);
            }
        }

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");
        }
    }
 }

Set Colorbar Range in matplotlib

Using vmin and vmax forces the range for the colors. Here's an example:

enter image description here

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )

def do_plot(n, f, title):
    #plt.clf()
    plt.subplot(1, 3, n)
    plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4)
    plt.title(title)
    plt.colorbar()

plt.figure()
do_plot(1, lambda x:x, "all")
do_plot(2, lambda x:np.clip(x, -4, 0), "<0")
do_plot(3, lambda x:np.clip(x, 0, 4), ">0")
plt.show()

What is ANSI format?

I remember when "ANSI" text referred to the pseudo VT-100 escape codes usable in DOS through the ANSI.SYS driver to alter the flow of streaming text.... Probably not what you are referring to but if it is see http://en.wikipedia.org/wiki/ANSI_escape_code

How to retrieve GET parameters from JavaScript

This one uses a regular expression and returns null if the parameter doesn't exist or doesn't have any value:

function getQuery(q) {
   return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

How do I determine height and scrolling position of window in jQuery?

From jQuery Docs:

const height = $(window).height();
const scrollTop = $(window).scrollTop();

http://api.jquery.com/scrollTop/
http://api.jquery.com/height/

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

Just Go to Model file of the corresponding Controller and check the primary key filed name

such as

protected $primaryKey = 'info_id';

here info id is field name available in database table

More info can be found at "Primary Keys" section of the docs.

Unit testing with mockito for constructors

Mockito can now mock constructors (since version 3.5.0) https://javadoc.io/static/org.mockito/mockito-core/3.5.13/org/mockito/Mockito.html#mocked_construction

try (MockedConstruction mocked = mockConstruction(Foo.class)) {
   Foo foo = new Foo();
   when(foo.method()).thenReturn("bar");
   assertEquals("bar", foo.method());
   verify(foo).method();
 }

"java.lang.OutOfMemoryError : unable to create new native Thread"

I encountered same issue during the load test, the reason is because of JVM is unable to create a new Java thread further. Below is the JVM source code

if (native_thread->osthread() == NULL) {    
// No one should hold a reference to the 'native_thread'.    
    delete native_thread;   
if (JvmtiExport::should_post_resource_exhausted()) {      
    JvmtiExport::post_resource_exhausted(        
        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 
        JVMTI_RESOURCE_EXHAUSTED_THREADS, 
        "unable to create new native thread");    
    } THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "unable to create new native thread");  
} Thread::start(native_thread);`

Root cause : JVM throws this exception when JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR (resources exhausted (means memory exhausted) ) or JVMTI_RESOURCE_EXHAUSTED_THREADS (Threads exhausted).

In my case Jboss is creating too many threads , to serve the request, but all the threads are blocked . Because of this, JVM is exhausted with threads as well with memory (each thread holds memory , which is not released , because each thread is blocked).

Analyzed the java thread dumps observed nearly 61K threads are blocked by one of our method, which is causing this issue . Below is the portion of Thread dump

"SimpleAsyncTaskExecutor-16562" #38070 prio=5 os_prio=0 tid=0x00007f9985440000 nid=0x2ca6 waiting for monitor entry [0x00007f9d58c2d000]
   java.lang.Thread.State: BLOCKED (on object monitor)

How can I inject a property value into a Spring Bean which was configured using annotations?

I need to have two properties files, one for production and an override for development (that will not be deployed).

To have both, a Properties Bean that can be autowired and a PropertyConfigurer, you can write:

<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="singleton" value="true" />

    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:live.properties</value>
            <value>classpath:development.properties</value>
        </list>
    </property>
</bean>

and reference the Properties Bean in the PropertyConfigurer

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties" ref="appProperties" />
</bean>

Using json_encode on objects in PHP (regardless of scope)

$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

I had the same problem with a ClickOnce deployment.

I solved the problem by going to the 'Publish' tab in the project properties and then selecting the 'Application Files' button.

I then selected the options:

  • 'File Name' of 'stdole.dll'
  • 'Publish status' to 'Include' and
  • 'Download Group' to 'Required'.

This fixed my problem when I re-published.

I hope this help you :D

Java: set timeout on a certain block of code?

Instead of having the task in the new thread and the timer in the main thread, have the timer in the new thread and the task in the main thread:

public static class TimeOut implements Runnable{
    public void run() {
        Thread.sleep(10000);
        if(taskComplete ==false) {
            System.out.println("Timed Out");
            return;
        }
        else {
            return;
        }
    }
}
public static boolean taskComplete = false;
public static void main(String[] args) {
    TimeOut timeOut = new TimeOut();
    Thread timeOutThread = new Thread(timeOut);
    timeOutThread.start();
    //task starts here
    //task completed
    taskComplete =true;
    while(true) {//do all other stuff }
}

How to give environmental variable path for file appender in configuration file in log4j

When parsing its configuration file, the expression ${MY_HOME} will be expanded to the value of the system property named MY_HOME, not the system environment variable. There's a difference between the two.

To achieve this in a clean way, you'll have to add something like this to the JVM invocation line:

-DMY_HOME=$MY_HOME

That would define the Java system property MY_HOME to contain the value of the environment variable MY_HOME.

How to change the font size on a matplotlib plot

Here is a totally different approach that works surprisingly well to change the font sizes:

Change the figure size!

I usually use code like this:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)

The smaller you make the figure size, the larger the font is relative to the plot. This also upscales the markers. Note I also set the dpi or dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example from above code: enter image description here

USB Debugging option greyed out

Just ran into this on the LG Rebel LTE (LGL44VL). As other answers note, you need to change the USB connection mode to PTP. But my phone's control panels were different from stock Android and didn't have such an option.

The option was hiding in a notification that appeared when I plugged the phone in. I had to open the notification tray and tap a notification labeled

Media Device (MTP)
Tap here for more USB options

Updating version numbers of modules in a multi-module Maven project

If you want to fully automate the process (i.e. you want to increment the version number without having to know what the current version number is), you can do this:

mvn build-helper:parse-version versions:set -DnewVersion=\${parsedVersion.majorVersion}.\${parsedVersion.minorVersion}.\${parsedVersion.nextIncrementalVersion} versions:commit

Finding diff between current and last version

If last versions means last tag, and current versions means HEAD (current state), it's just a diff with the last tag:

Looking for tags:

$ git tag --list
...
v20.11.23.4
v20.11.25.1
v20.11.25.2
v20.11.25.351

The last tag would be:

$ git tag --list | tail -n 1
v20.11.25.351

Putting it together:

tag=$(git tag --list | tail -n 1)
git diff $tag

How to retrieve value from elements in array using jQuery?

You can just loop though the items:

$("input[name^='card']").each(function() {
    console.log($(this).val());
});

Turn off textarea resizing

CSS3 can solve this problem. Unfortunately it's only supported on 60% of used browsers nowadays.

For IE and iOS you can't turn off resizing but you can limit the textarea dimension by setting its width and height.

/* One can also turn on/off specific axis. Defaults to both on. */
textarea { resize:vertical; } /* none|horizontal|vertical|both */

See Demo

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
      break;
    case "monthly":
      //Do somthing
      break;
    }
  }

Regards

How to find the size of integer array

_msize(array) in Windows or malloc_usable_size(array) in Linux should work for the dynamic array

Both are located within malloc.h and both return a size_t

Parse an URL in JavaScript

I wrote a javascript url parsing library, URL.js, you can use it for this.

Example:

url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"

Setting device orientation in Swift iOS

Above code might not be working due to possibility if your view controller belongs to a navigation controller. If yes then it has to obey the rules of the navigation controller even if it has different orientation rules itself. A better approach would be to let the view controller decide for itself and the navigation controller will use the decision of the top most view controller.

We can support both locking to current orientation and autorotating to lock on a specific orientation with this generic extension on UINavigationController: -:

extension UINavigationController {
            public override func shouldAutorotate() -> Bool {
                return visibleViewController.shouldAutorotate()
            }

        public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
            return (visibleViewController?.supportedInterfaceOrientations())!
        }
    }

Now inside your view controller we can

class ViewController: UIViewController {
    // MARK: Autoroate configuration

    override func shouldAutorotate() -> Bool {
        if (UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait ||
            UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown ||
            UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
                return true
        }
        else {
            return false
        }
    }

    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Portrait.rawValue) | Int(UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
    }
}

Hope it helps. Thanks

How to find an available port?

Using 'ServerSocket' class we can identify whether given port is in use or free. ServerSocket provides a constructor that take an integer (which is port number) as argument and initialise server socket on the port. If ServerSocket throws any IO Exception, then we can assume this port is already in use.

Following snippet is used to get all available ports.

for (int port = 1; port < 65535; port++) {
         try {
                  ServerSocket socket = new ServerSocket(port);
                  socket.close();
                  availablePorts.add(port);
         } catch (IOException e) {

         }
}

Reference link.

How can I compare two ordered lists in python?

Just use the classic == operator:

>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False

Lists are equal if elements at the same index are equal. Ordering is taken into account then.

Regular expression matching a multiline block of text

My preference.

lineIter= iter(aFile)
for line in lineIter:
    if line.startswith( ">" ):
         someVaryingText= line
         break
assert len( lineIter.next().strip() ) == 0
acids= []
for line in lineIter:
    if len(line.strip()) == 0:
        break
    acids.append( line )

At this point you have someVaryingText as a string, and the acids as a list of strings. You can do "".join( acids ) to make a single string.

I find this less frustrating (and more flexible) than multiline regexes.

How do I compare two strings in python?

For that, you can use default difflib in python

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

then call similar() as

similar(string1, string2)

it will return compare as ,ratio >= threshold to get match result

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Use Message.get_payload

b = email.message_from_string(a)
if b.is_multipart():
    for payload in b.get_payload():
        # if payload.is_multipart(): ...
        print payload.get_payload()
else:
    print b.get_payload()

Is it possible to create a File object from InputStream

Since Java 7, you can do it in one line even without using any external libraries:

Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

See the API docs.

Is there Selected Tab Changed Event in the standard WPF Tab Control

I tied this in the handler to make it work:

void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {
      //do work when tab is changed
    }
}

Eclipse CDT: Symbol 'cout' could not be resolved

I had a similar problem with *std::shared_ptr* with Eclipse using MinGW and gcc 4.8.1. No matter what, Eclipse would not resolve *shared_ptr*. To fix this, I manually added the __cplusplus macro to the C++ symbols and - viola! - Eclipse can find it. Since I specified -std=c++11 as a compile option, I (ahem) assumed that the Eclipse code analyzer would use that option as well. So, to fix this:

  1. Project Context -> C/C++ General -> Paths and Symbols -> Symbols Tab
  2. Select C++ in the Languages panel.
  3. Add symbol __cplusplus with a value of 201103.

The only problem with this is that gcc will complain that the symbol is already defined(!) but the compile will complete as before.

Difference between Visibility.Collapsed and Visibility.Hidden

Even though a bit old thread, for those who still looking for the differences:

Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.

If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.

As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.