Programs & Examples On #Mysql connector

MySQL provides standards-based drivers for JDBC, ODBC, and .NET enabling developers to build database applications in their language of choice. In addition, a native C library allows developers to embed MySQL directly into their applications.

How to connect to a MySQL Data Source in Visual Studio

Installing the following packages:

adds MySQL Database to the data sources list (Visual Studio 2017)

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

The exception can also occur because of the class path not being defined.

After hours of research and literally going through hundreds of pages, the problem was that the class path of the library was not defined.

Set the class path as follows in your windows machine

set classpath=path\to\your\jdbc\jar\file;.

How to install mysql-connector via pip

pip install mysql-connector

Last but not least,You can also install mysql-connector via source code

Download source code from: https://dev.mysql.com/downloads/connector/python/

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

Try to specify the port in

conn = DriverManager.getConnection("jdbc:mysql://localhost/mysql?"
                                        + "user=root&password=onelife");

I think you should have something like this:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?"
                                            + "user=root&password=onelife");

Also, the port number in my example (3306) is the default port, but you may change it while installing MySQL.

I think that a better way to specify password and user is to separate them from the URL like this:

connection = DriverManager.getConnection(url, login, password);

How to connect to MySQL Database?

Looking at the code below, I tried it and found: Instead of writing DBCon = DBConnection.Instance(); you should put DBConnection DBCon - new DBConnection(); (That worked for me)

and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection()); you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection()); (it's missing the d)

mysql.h file can't be found

For those who are using Eclipse IDE.

After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,

You will need to tell Eclipse IDE about the following

  • Where to find mysql.h
  • Where to find libmysqlclient library
  • The path to search for libmysqlclient library

Here is how you go about it.

To Add mysql.h

1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql

enter image description here

To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.

2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient

enter image description here

3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.

Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql

enter image description here

Extracting substrings in Go

8 years later I stumbled upon this gem, and yet I don't believe OP's original question was really answered:

so I came up with the following code to trim the newline character

While the bufio.Reader type supports a ReadLine() method which both removes \r\n and \n it is meant as a low-level function which is awkward to use because repeated checks are necessary.

IMO an idiomatic way to remove whitespace is to use Golang's strings library:

input, _ = src.ReadString('\n')

// more specific to the problem of trailing newlines
actual = strings.TrimRight(input, "\r\n")

// or if you don't mind to trim leading and trailing whitespaces 
actual := strings.TrimSpace(input)

See this example in action in the Golang playground: https://play.golang.org/p/HrOWH0kl3Ww

npm ERR! Error: EPERM: operation not permitted, rename

These steps solved for me

Go to the package.json file in the file explorer Right click & select Properties. Deselect Read-only. Click Apply

NOTE: (In case if it is already deselected , check and uncheck the read-only once and click Apply)

How to get the start time of a long-running Linux process?

As a follow-up to Adam Matan's answer, the /proc/<pid> directory's time stamp as such is not necessarily directly useful, but you can use

awk -v RS=')' 'END{print $20}' /proc/12345/stat

to get the start time in clock ticks since system boot.1

This is a slightly tricky unit to use; see also convert jiffies to seconds for details.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat

This should give you seconds, which you can pass to strftime() to get a (human-readable, or otherwise) timestamp.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat

Updated with some fixes from Stephane Chazelas in the comments; thanks as always!

If you only have Mawk, maybe try

awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
  NR==1 { now=$1; next }
  END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}

1 man proc; search for starttime.

How can I use Guzzle to send a POST request in JSON?

Above answers did not worked for me somehow. But this works fine for me.

 $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

 $request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));

What's the best way to store Phone number in Django models

Use CharField for phone field in the model and the localflavor app for form validation:

https://docs.djangoproject.com/en/1.7/topics/localflavor/

ImportError in importing from sklearn: cannot import name check_build

For me, I was upgrading the existing code into new setup by installing Anaconda from fresh with latest python version(3.7) For this,

from sklearn import cross_validation, 
from sklearn.grid_search import GridSearchCV

to

from sklearn.model_selection import GridSearchCV,cross_validate

Convert a string to int using sql query

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

How to validate phone number in laravel 5.2?

From Laravel 5.5 on you can use an artisan command to create a new Rule which you can code regarding your requirements to decide whether it passes or fail.

Ej: php artisan make:rule PhoneNumber

Then edit app/Rules/PhoneNumber.php, on method passes

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{

    return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
}

Then, use this Rule as you usually would do with the validation:

use App\Rules\PhoneNumber;

$request->validate([
    'name' => ['required', new PhoneNumber],
]);

docs

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.

What are the differences between Mustache.js and Handlebars.js?

One more subtle difference is the treatment of falsy values in {{#property}}...{{/property}} blocks. Most mustache implementations will just obey JS falsiness here, not rendering the block if property is '' or '0'.

Handlebars will render the block for '' and 0, but not other falsy values. This can cause some trouble when migrating templates.

List submodules in a Git repository

The following command will list the submodules:

git submodule--helper list

The output is something like this:

<mode> <sha1> <stage> <location>

Note: It requires Git 2.7.0 or above.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations. Make sure to select the proper start project.

How to launch an Activity from another Application in Android

Steps to launch new activity as follows:

1.Get intent for package

2.If intent is null redirect user to playstore

3.If intent is not null open activity

public void launchNewActivity(Context context, String packageName) {
    Intent intent = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.CUPCAKE) {
        intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    }
    if (intent == null) {
        try {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("market://details?id=" + packageName));
            context.startActivity(intent);
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
        }
    } else {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

Phone validation regex

Try this

\+?\(?([0-9]{3})\)?[-.]?\(?([0-9]{3})\)?[-.]?\(?([0-9]{4})\)?

It matches the following cases

  • +123-(456)-(7890)
  • +123.(456).(7890)
  • +(123).(456).(7890)
  • +(123)-(456)-(7890)
  • +123(456)(7890)
  • +(123)(456)(7890)
  • 123-(456)-(7890)
  • 123.(456).(7890)
  • (123).(456).(7890)
  • (123)-(456)-(7890)
  • 123(456)(7890)
  • (123)(456)(7890)

For further explanation on the pattern CLICKME

How to replace specific values in a oracle database column?

Use REPLACE:

SELECT REPLACE(t.column, 'est1', 'rest1')
  FROM MY_TABLE t

If you want to update the values in the table, use:

UPDATE MY_TABLE t
   SET column = REPLACE(t.column, 'est1', 'rest1')

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This did the trick for me:

echo trim($entry->title);

Python, how to read bytes from file and save it?

with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.

Specifying number of decimal places in Python

You don't show the code for display_data, but here's what you need to do:

print "$%0.02f" %amount

This is a format specifier for the variable amount.

Since this is beginner topic, I won't get into floating point rounding error, but it's good to be aware that it exists.

Permissions error when connecting to EC2 via SSH on Mac OSx

I had met this problem too.And I found that happend beacuse I forgot to add the user-name before the host name: like this:

ssh -i test.pem ec2-32-122-42-91.us-west-2.compute.amazonaws.com

and I add the user name:

ssh -i test.pem [email protected]

it works!

Calling another different view from the controller using ASP.NET MVC 4

You can directly return a different view like:

return View("NameOfView", Model);

Or you can make a partial view and can return like:

return PartialView("PartialViewName", Model);

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

Random number in range [min - max] using PHP

I have bundled the answers here and made it version independent;

function generateRandom($min = 1, $max = 20) {
    if (function_exists('random_int')):
        return random_int($min, $max); // more secure
    elseif (function_exists('mt_rand')):
        return mt_rand($min, $max); // faster
    endif;
    return rand($min, $max); // old
}

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

(edit: Does not work)As of 2014, You can clear your cache whenever you want, Please go thorough the Documentation or just go to your distribution settings>Behaviors>Edit

Object Caching Use (Origin Cache Headers) Customize

Minimum TTL = 0

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html

Regex number between 1 and 100

Here are simple regex to understand (verified, and no preceding 0)

Between 0 to 100 (Try it here):

^(0|[1-9][0-9]?|100)$

Between 1 to 100 (Try it here):

^([1-9][0-9]?|100)$

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

Mine was about

dispatch_group_leave(group)

was inside if closure in block. I just moved it out of closure.

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

Is there a way to disable initial sorting for jquery DataTables?

As per latest api docs:

$(document).ready(function() {
    $('#example').dataTable({
        "order": []
    });
});

More Info

How to convert a string to a date in sybase

Use the convert function, for example:

select * from data 
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.

How to take input in an array + PYTHON?

raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

Best way to convert string to bytes in Python 3?

If you look at the docs for bytes, it points you to bytearray:

bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.

For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.

Edit: I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself.

Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice.

What is the difference between linear regression and logistic regression?

To put it simply, if in linear regression model more test cases arrive which are far away from the threshold(say =0.5)for a prediction of y=1 and y=0. Then in that case the hypothesis will change and become worse.Therefore linear regression model is not used for classification problem.

Another Problem is that if the classification is y=0 and y=1, h(x) can be > 1 or < 0.So we use Logistic regression were 0<=h(x)<=1.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Concepts

Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.

What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map, ...). This allows to handle asynchronous things in a very flexible way.

A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

(textValue is the control associated with the filter input).

Here is a wider description of such use case: How to watch for form changes in Angular 2?.

There are two great presentations at AngularConnect 2015 and EggHead:

Christoph Burgdorf also wrote some great blog posts on the subject:

In action

In fact regarding your code, you mixed two approaches ;-) Here are they:

  • Manage the observable by your own. In this case, you're responsible to call the subscribe method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of result">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit, OnDestroy {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.friendsObservable = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result = result);
       }
    
       ngOnDestroy() {
         this.friendsObservable.dispose();
       }
    }
    

    Returns from both get and map methods are the observable not the result (in the same way than with promises).

  • Let manage the observable by the Angular template. You can also leverage the async pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe method.

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of (result | async)">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.result = http.get('friends.json')
                      .map(response => response.json());
       }
    }
    

You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe method.

You can also notice that the map method is used to extract the JSON content from the response and use it then in the observable processing.

Hope this helps you, Thierry

Syntax of for-loop in SQL Server

For loop is not officially supported yet by SQL server. Already there is answer on achieving FOR Loop's different ways. I am detailing answer on ways to achieve different types of loops in SQL server.

FOR Loop

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'Inside FOR LOOP';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done FOR LOOP';

If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.

DO..WHILE Loop

DECLARE @X INT=1;

WAY:  --> Here the  DO statement

  PRINT @X;

  SET @X += 1;

IF @X<=10 GOTO WAY;

REPEAT..UNTIL Loop

DECLARE @X INT = 1;

WAY:  -- Here the REPEAT statement

  PRINT @X;

  SET @X += 1;

IFNOT(@X > 10) GOTO WAY;

Reference

UDP vs TCP, how much faster is it?

Keep in mind that TCP usually keeps multiple messages on wire. If you want to implement this in UDP you'll have quite a lot of work if you want to do it reliably. Your solution is either going to be less reliable, less fast or an incredible amount of work. There are valid applications of UDP, but if you're asking this question yours probably is not.

Sending simple message body + file attachment using Linux Mailx

You can try this:

(cat ./body.txt)|mailx -s "subject text" -a "attchement file" [email protected]

How to check if a Docker image with a specific tag exist locally?

tldr:

docker image inspect myimage:mytag

By way of demonstration...

success, found image:

$ docker image pull busybox:latest
latest: Pulling from library/busybox
Digest: sha256:32f093055929dbc23dec4d03e09dfe971f5973a9ca5cf059cbfb644c206aa83f
Status: Image is up to date for busybox:latest

$ docker image inspect busybox:latest >/dev/null 2>&1 && echo yes || echo no
yes

failure, missing image:

$ docker image rm busybox:latest
Untagged: busybox:latest
Untagged: busybox@sha256:32f093055929dbc23dec4d03e09dfe971f5973a9ca5cf059cbfb644c206aa83f

$ docker image inspect busybox:latest >/dev/null 2>&1 && echo yes || echo no
no

Reference:

https://docs.docker.com/engine/reference/commandline/image_inspect/

How to run SQL in shell script

#!/bin/ksh
variable1=$( 
echo "set feed off
set pages 0
select count(*) from table;
exit
"  | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"

How to edit a text file in my terminal

Try this command:

sudo gedit helloWorld.txt

it, will open up a text editor to edit your file.

OR

sudo nano helloWorld.txt

Here, you can edit your file in the terminal window.

How can I tell when a MySQL table was last updated?

I don't have information_schema database, using mysql version 4.1.16, so in this case you can query this:

SHOW TABLE STATUS FROM your_database LIKE 'your_table';

It will return these columns:

| Name      | Engine | Version | Row_format | Rows | Avg_row_length 
| Data_length | Max_data_length | Index_length | Data_free | Auto_increment
| Create_time | Update_time | Check_time | Collation
| Checksum | Create_options | Comment |

As you can see there is a column called: "Update_time" that shows you the last update time for your_table.

Enabling/Disabling Microsoft Virtual WiFi Miniport

In the device manager you can select View > Show hidden devices

How to get year and month from a date - PHP

Using date() and strtotime() from the docs.

$date = "2012-01-05";

$year = date('Y', strtotime($date));

$month = date('F', strtotime($date));

echo $month

python pip: force install ignoring dependencies

When I were trying install librosa package with pip (pip install librosa), this error were appeared:

ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

I tried to remove llvmlite, but pip uninstall could not remove it. So, I used capability of ignore of pip by this code:

pip install librosa --ignore-installed llvmlite

Indeed, you can use this rule for ignoring a package you don't want to consider:

pip install {package you want to install} --ignore-installed {installed package you don't want to consider}

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

is there something like isset of php in javascript/jQuery?

You can just:

if(variable||variable===0){
    //Yes it is set
    //do something
}
else {
    //No it is not set
    //Or its null
    //do something else 
}

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

Explicit vs implicit SQL joins

The first answer you gave uses what is known as ANSI join syntax, the other is valid and will work in any relational database.

I agree with grom that you should use ANSI join syntax. As they said, the main reason is for clarity. Rather than having a where clause with lots of predicates, some of which join tables and others restricting the rows returned with the ANSI join syntax you are making it blindingly clear which conditions are being used to join your tables and which are being used to restrict the results.

Paste text on Android Emulator

For Mac and Linux try this function in your aliases_bash file (located in /etc/aliases_bash for Mac folks, be sure to use sudo vim /etc/aliases_bash)

function adbtx {
  userinput="$(sed 's/ /%s/g' <<< $1)"
  adb shell input text "${userinput}";
}
export -f adbtx

Then in the command line enter:

adbtx 'Your text to emulator input'

'Your text to emulator input' will be input on the emulator text field.

Kudos to Eliot for his substitution string for sed.

Changing the sign of a number in PHP?

using alberT and Dan Tao solution:

negative to positive and viceversa

$num = $num <= 0 ? abs($num) : -$num ;

Moment Js UTC to Local Time

I've created one function which converts all the timezones into local time.

Requirements:

1. npm i moment-timezone

function utcToLocal(utcdateTime, tz) {
    var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
    var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
    var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
    var localDateTime
    var hours = zoneValue.split(":")[0]
    var minutes = zoneValue.split(":")[1]
    if (operator === "-") {
        localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else if (operator) {
        localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else {
        localDateTime = "Invalid Timezone Operator"
    }
    return localDateTime
}

utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")

//Returns "2019-11-14 12:45:37"

How to show MessageBox on asp.net?

It's true that Messagebox.show("dd"); is not a part of using System.Web;,

I felt the same situation for most of time. If you want to do this then do the following steps.

  • Right click on project in solution explorer
  • go for add reference, then choose .NET tab

  • And select, System.windows.forms (press 's' to find quickly)

u can get the namespace, now u can use Messagebox.show("dd");

But I recommend to go with javascript alert for this.

Custom format for time command

Use the bash built-in variable SECONDS. Each time you reference the variable it will return the elapsed time since the script invocation.

Example:

echo "Start $SECONDS"
sleep 10
echo "Middle $SECONDS"
sleep 10
echo "End $SECONDS"

Output:

Start 0
Middle 10
End 20

Multiple controllers with AngularJS in single page app

I'm currently in the process of building a single page application. Here is what I have thus far that I believe would be answering your question. I have a base template (base.html) that has a div with the ng-view directive in it. This directive tells angular where to put the new content in. Note that I'm new to angularjs myself so I by no means am saying this is the best way to do it.

app = angular.module('myApp', []);                                                                             

app.config(function($routeProvider, $locationProvider) {                        
  $routeProvider                                                                
       .when('/home/', {                                            
         templateUrl: "templates/home.html",                                               
         controller:'homeController',                                
        })                                                                      
        .when('/about/', {                                       
            templateUrl: "templates/about.html",     
            controller: 'aboutController',  
        }) 
        .otherwise({                      
            template: 'does not exists'   
        });      
});

app.controller('homeController', [              
    '$scope',                              
    function homeController($scope,) {        
        $scope.message = 'HOME PAGE';                  
    }                                                
]);                                                  

app.controller('aboutController', [                  
    '$scope',                               
    function aboutController($scope) {        
        $scope.about = 'WE LOVE CODE';                       
    }                                                
]); 

base.html

<html>
<body>

    <div id="sideMenu">
        <!-- MENU CONTENT -->
    </div>

    <div id="content" ng-view="">
        <!-- Angular view would show here -->
    </div>

<body>
</html>

How do you detect where two line segments intersect?

A C++ program to check if two given line segments intersect

#include <iostream>
using namespace std;

struct Point
{
    int x;
    int y;
};

// Given three colinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r)
{
    if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
        q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
       return true;

    return false;
}

// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
    // See 10th slides from following link for derivation of the formula
    // http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
    int val = (q.y - p.y) * (r.x - q.x) -
              (q.x - p.x) * (r.y - q.y);

    if (val == 0) return 0;  // colinear

    return (val > 0)? 1: 2; // clock or counterclock wise
}

// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
    // Find the four orientations needed for general and
    // special cases
    int o1 = orientation(p1, q1, p2);
    int o2 = orientation(p1, q1, q2);
    int o3 = orientation(p2, q2, p1);
    int o4 = orientation(p2, q2, q1);

    // General case
    if (o1 != o2 && o3 != o4)
        return true;

    // Special Cases
    // p1, q1 and p2 are colinear and p2 lies on segment p1q1
    if (o1 == 0 && onSegment(p1, p2, q1)) return true;

    // p1, q1 and p2 are colinear and q2 lies on segment p1q1
    if (o2 == 0 && onSegment(p1, q2, q1)) return true;

    // p2, q2 and p1 are colinear and p1 lies on segment p2q2
    if (o3 == 0 && onSegment(p2, p1, q2)) return true;

     // p2, q2 and q1 are colinear and q1 lies on segment p2q2
    if (o4 == 0 && onSegment(p2, q1, q2)) return true;

    return false; // Doesn't fall in any of the above cases
}

// Driver program to test above functions
int main()
{
    struct Point p1 = {1, 1}, q1 = {10, 1};
    struct Point p2 = {1, 2}, q2 = {10, 2};

    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    p1 = {10, 0}, q1 = {0, 10};
    p2 = {0, 0}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    p1 = {-5, -5}, q1 = {0, 0};
    p2 = {1, 1}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    return 0;
}

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

How to fix a locale setting warning from Perl

Following the accepted answer:

LANG=C ssh hunter2.

LC_ALL=C ssh hunter2

on the client side did the trick for me.

when I run mockito test occurs WrongTypeOfReturnValue Exception

If you are using annotations, may be you need to use @Mock instead of @InjectMocks. Because @InjectMocks works as @Spy and @Mock together. And @Spy keeps track of recently executed methods and you may feel that incorrect data is returned/subbed.

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

Real escape string and PDO

You should use PDO Prepare

From the link:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

Adding n hours to a date in Java?

tl;dr

myJavaUtilDate.toInstant()
              .plusHours( 8 )

Or…

myJavaUtilDate.toInstant()                // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
              .plus(                      // Do the math, adding a span of time to our moment, our `Instant`. 
                  Duration.ofHours( 8 )   // Specify a span of time unattached to the timeline.
               )                          // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.

Using java.time

The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.

Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.

Instant instant = myUtilDate.toInstant();

You can add hours to that Instant by passing a TemporalAmount such as Duration.

Duration duration = Duration.ofHours( 8 );
Instant instantHourLater = instant.plus( duration );

To read that date-time, generate a String in standard ISO 8601 format by calling toString.

String output = instantHourLater.toString();

You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.

ZonedDateTime later = zdt.plusHours( 8 );

You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.

java.util.Date date = java.util.Date.from( later.toInstant() );

For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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

One of the values you pass on to Ancestors becomes None at some point, it says, so check if otu, tree, tree[otu] or tree[otu][0] are None in the beginning of the function instead of only checking tree[otu][0][0] == None. But perhaps you should reconsider your path of action and the datatype in question to see if you could improve the structure somewhat.

Get and set position with jQuery .offset()

I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.

Here's one way to position your elements using the position feature:

var options = {
    "my": "top left",
    "at": "top left",
    "of": ".layer1"
};
$(".layer2").position(options);

MySQL skip first 10 results

Use LIMIT with two parameters. For example, to return results 11-60 (where result 1 is the first row), use:

SELECT * FROM foo LIMIT 10, 50

For a solution to return all results, see Thomas' answer.

count of entries in data frame in R

You could use table:

R> x <- read.table(textConnection('
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty'
), header=TRUE)

R> table(x$Believe)

FALSE  TRUE 
    1     3 

Allow anonymous authentication for a single folder in web.config?

To make it work I build my directory like this:

Project Public Restrict

So I edited my webconfig for my public folder:

<location path="Project/Public">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

And for my Restricted folder:

 <location path="Project/Restricted">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorizatio>
    </system.web>
  </location>

See here for the spec of * and ?:

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/add

I hope I have helped.

Where to get this Java.exe file for a SQL Developer installation

Please provide full path >

In mines case it was E:\app\ankitmittal01\product\11.2.0\dbhome_1\jdk\bin\java.exe

From : http://www.javamadesoeasy.com/2015/07/oracle-11g-and-sql-developer.html

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In your yaml file, add command and args lines:

...
containers:
      - name: api
        image: localhost:5000/image-name 
        command: [ "sleep" ]
        args: [ "infinity" ]
...

Works for me.

How to store images in mysql database using php

<!-- 
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])


CREATE TABLE  `images` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `image` longblob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

-->
<!-- this form is user to store images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />

<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>



<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
        mysql_connect("", "", "") OR DIE (mysql_error());
        mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
    header("location:search.php");

}

//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
        $name=$_POST['image_name'];
        $email=$_POST['mail'];
        $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
        }
                // our sql query
                $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
                            mysql_query($sql) or die("Error in Query insert: " . mysql_error());
} 
?>



<?php
//SEARCH.PHP PAGE
    //connect to database.db name = images
         mysql_connect("localhost", "root", "") OR DIE (mysql_error());
        mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database

        $msg="";
        $sql="select * from images";
        if(mysql_query($sql))
        {
            $res=mysql_query($sql);
            while($row=mysql_fetch_array($res))
            {
                    $id=$row['id'];
                    $name=$row['name'];
                    $image=$row['image'];

                  $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " />   </a>';

            }
        }
        else
            $msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

Show popup after page load

If you don't want to use jquery, use this:

<script>
 // without jquery
document.addEventListener("DOMContentLoaded", function() {
 setTimeout(function() {
  // run your open popup function after 5 sec = 5000
  PopUp();
 }, 5000)
});
</script>

OR With jquery

<script>
  $(document).ready(function(){
   setTimeout(function(){
   // open popup after 5 seconds
   PopUp();
  },5000);  
 });
</script>

Apply a theme to an activity in Android?

You can apply a theme to any activity by including android:theme inside <activity> inside manifest file.

For example:

  1. <activity android:theme="@android:style/Theme.Dialog">
  2. <activity android:theme="@style/CustomTheme">

And if you want to set theme programatically then use setTheme() before calling setContentView() and super.onCreate() method inside onCreate() method.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

Android canvas draw rectangle

The code is fine just setStyle of paint as STROKE

paint.setStyle(Paint.Style.STROKE);

Fatal error: Call to undefined function imap_open() in PHP

if it is centos with php 5.3 installed.

sudo yum install php53-imap

and restart apache

sudo /sbin/service httpd restart

or

sudo service apache2 restart

How to check for an undefined or null variable in JavaScript?

Since there is no single complete and correct answer, I will try to summarize:

In general, the expression:

if (typeof(variable) != "undefined" && variable != null)

cannot be simplified, because the variable might be undeclared so omitting the typeof(variable) != "undefined" would result in ReferenceError. But, you can simplify the expression according to the context:

If the variable is global, you can simplify to:

if (window.variable != null)

If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:

if (variable != null)

If it is object property, you don't have to worry about ReferenceError:

if (obj.property != null)

How to animate RecyclerView items when they appear

Just extends your Adapter like below

public class RankingAdapter extends AnimatedRecyclerView<RankingAdapter.ViewHolder> 

And add super method to onBindViewHolder

@Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        super.onBindViewHolder(holder, position);

It's automate way to create animated adapter like "Basheer AL-MOMANI"

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;

import java.util.Random;

/**
 * Created by eliaszkubala on 24.02.2017.
 */
public class AnimatedRecyclerView<T extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<T> {


    @Override
    public T onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(T holder, int position) {
        setAnimation(holder.itemView, position);
    }

    @Override
    public int getItemCount() {
        return 0;
    }

    protected int mLastPosition = -1;

    protected void setAnimation(View viewToAnimate, int position) {
        if (position > mLastPosition) {
            ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
            viewToAnimate.startAnimation(anim);
            mLastPosition = position;
        }
    }

}

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Adding this as an answer, just since you can't do much fancy formatting in comments.
I had the same issue, except I was creating and binding my web service client entirely in code.
Reason is the DLL was being uploaded into a system, which prohibited the use of config files.

Here is the code as it needed to be updated to communicate over SSL...

Public Function GetWebserviceClient() As WebWorker.workerSoapClient
    Dim binding = New BasicHttpBinding()
    binding.Name = "WebWorkerSoap"
    binding.CloseTimeout = TimeSpan.FromMinutes(1)
    binding.OpenTimeout = TimeSpan.FromMinutes(1)
    binding.ReceiveTimeout = TimeSpan.FromMinutes(10)
    binding.SendTimeout = TimeSpan.FromMinutes(1)

    '// HERE'S THE IMPORTANT BIT FOR SSL
    binding.Security.Mode = BasicHttpSecurityMode.Transport

    Dim endpoint = New EndpointAddress("https://myurl/worker.asmx")

    Return New WebWorker.workerSoapClient(binding, endpoint)
End Function

How to secure phpMyAdmin

One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.

I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29

AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')

Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.

grant select on db_name.some_table to 'pma-user'@'app-server'

How to fix Error: laravel.log could not be opened?

This is work for me.

Essa foi a única solução que funcionou para mim. Estou usando Docker e Laradock

chmod -Rvc 775 storage

Create list of object from another using Java 8 Streams

An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping does the same in one step:

//...
List<Employee> employees = persons.stream()
  .filter(p -> p.getLastName().equals("l1"))
  .collect(
    Collectors.mapping(
      p -> new Employee(p.getName(), p.getLastName(), 1000),
      Collectors.toList()));

Detailed example can be found here

Android: remove left margin from actionbar's custom layout

The left inset is caused by Toolbar's contentInsetStart which by default is 16dp.

Change this to align to the keyline.

Update for support library v24.0.0:

To match the Material Design spec there's an additional attribute contentInsetStartWithNavigation which by default is 16dp. Change this if you also have a navigation icon.

It turned out that this is part of a new Material Design Specification introduced in version 24 of Design library.

https://material.google.com/patterns/navigation.html

However, it is possible to remove the extra space by adding the following property to Toolbar widget.

app:contentInsetStartWithNavigation="0dp"

Before : enter image description here

After : enter image description here

how to redirect to external url from c# controller

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/

How can I style the border and title bar of a window in WPF?

Those are "non-client" areas and are controlled by Windows. Here is the MSDN docs on the subject (the pertinent info is at the top).

Basically, you set your Window's WindowStyle="None", then build your own window interface. (similar question on SO)

Find a private field with Reflection?

Use BindingFlags.NonPublic and BindingFlags.Instance flags

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);

matching query does not exist Error in Django

try:
    user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
    user = None

I also see you're storing your passwords in plaintext (a big security no-no!). Consider using the built-in auth system instead.

Parse JSON response using jQuery

Try bellow code. This is help your code.

  $("#btnUpdate").on("click", function () {
            //alert("Alert Test");
            var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';
            $.ajax({
                type: "GET",
                url: url,
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    debugger;

                    $.each(result.callback, function (index, value) {
                        alert(index + ': ' + value.Name);
                    });
                },
                failure: function (result) { alert('Fail'); }
            });
        });

I could not access your url. Bellow error is shows

XMLHttpRequest cannot load http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:19829' is therefore not allowed access. The response had HTTP status code 501.

Executing set of SQL queries using batch file?

Different ways:

  1. Using SQL Server Agent (If local instance)
    schedule a job in sql server agent with a new step having type as "T-SQL" then run the job.

  2. Using SQLCMD
    To use SQLCMD refer http://technet.microsoft.com/en-us/library/ms162773.aspx

  3. Using SQLPS
    To use SQLPS refer http://technet.microsoft.com/en-us/library/cc280450.aspx

AWS Lambda import module error in python

Please add below one after Import requests

import boto3

What I can see that is missing in your code.

How can one use multi threading in PHP applications

You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.

I can't quite remember the php CLI syntax, but you'd want something like:

exec("/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'");

I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.

Angular ng-class if else

Both John Conde's and ryeballar's answers are correct and will work.

If you want to get too geeky:

  • John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center and it has to decide whether to add/remove left), when clearly only one is needed.

  • Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)


So, you can do the following as an alternative:

ng-class="{true:'center',false:'left'}[page.isSelected(1)]"

onchange equivalent in angular2

In Angular you can define event listeners like in the example below:

<!-- Here you can call public methods from parental component -->
<input (change)="method_name()"> 

How to debug when Kubernetes nodes are in 'Not Ready' state

I recently started using VMWare Octant https://github.com/vmware-tanzu/octant. This is a better UI than the Kubernetes Dashboard. You can view the Kubernetes cluster and look at the details of the cluster and the PODS. This will allow you to check the logs and open a terminal into the POD(s).

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

Count rows with not empty value

Solved using a solution i found googling by Yogi Anand: https://productforums.google.com/d/msg/docs/3qsR2m-1Xx8/sSU6Z6NYLOcJ

The example below counts the number of non-empty rows in the range A3:C, remember to update both ranges in the formula with your range of interest.

=ArrayFormula(SUM(SIGN(MMULT(LEN(A3:C), TRANSPOSE(SIGN(COLUMN(A3:C)))))))

Also make sure to avoid circular dependencies, it will happen if you for example count the number of non-empty rows in A:C and place this formula in the A or C column.

What Scala web-frameworks are available?

Following is a dump of frameworks. It doesn't mean I actually used them:

  • Coeus. A traditional MVC web framework for Scala.

  • Unfiltered. A toolkit for servicing HTTP requests in Scala.

  • Uniscala Granite.

  • Gardel

  • Mondo

  • Amore. A Scala port of the Ruby web framework Sinatra

  • Scales XML. Flexible approach to XML handling and a simplified way of interacting with XML.

  • Belt. A Rack-like interface for web applications built on top of Scalaz-HTTP

  • Frank. Web application DSL built on top of Scalaz/Belt

  • MixedBits. A framework for the Scala progamming language to help build web sites

  • Circumflex. Unites several self-contained open source projects for application development using the Scala programming language.

  • Scala Webmachine. Port of Basho's webmachine in Scala, a REST-based system for building web applications

  • Bowler. A RESTful, multi-channel ready Scala web framework

How can I run a html file from terminal?

Skip reading the html and use curl to POST whatever form data you want to submit to the server.

How to get current working directory using vba?

Your code: path = ActiveWorkbook.Path

returns blank because you haven't saved your workbook yet.

To overcome your problem, go back to the Excel sheet, save your sheet, and run your code again.

This time it will not show blank, but will show you the path where it is located (current folder)

I hope that helped.

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

Axios get access to response header fields

for django help

CORS_EXPOSE_HEADERS = [
        'your header'
    ]

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

How to generate a Dockerfile from an image?

I somehow absolutely missed the actual command in the accepted answer, so here it is again, bit more visible in its own paragraph, to see how many people are like me

$ docker history --no-trunc <IMAGE_ID>

error: command 'gcc' failed with exit status 1 while installing eventlet

I am using MacOS catalina 10.15.4. None of the posted solutions worked for me. What worked for me is:

 >> xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates

>> env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2==2.8.4
Collecting psycopg2==2.8.4
  Using cached psycopg2-2.8.4.tar.gz (377 kB)
Installing collected packages: psycopg2
  Attempting uninstall: psycopg2
    Found existing installation: psycopg2 2.7.7
    Uninstalling psycopg2-2.7.7:
      Successfully uninstalled psycopg2-2.7.7
    Running setup.py install for psycopg2 ... done
Successfully installed psycopg2-2.8.4

use pip3 for python3

Oracle: not a valid month

To know the actual date format, insert a record by using sysdate. That way you can find the actual date format. for example

insert into emp values(7936, 'Mac', 'clerk', 7782, sysdate, 1300, 300, 10);

now, select the inserted record.

select ename, hiredate from emp where ename='Mac';

the result is

ENAME   HIREDATE
Mac     06-JAN-13

voila, now your actual date format is found.

I do not understand how execlp() works in Linux

The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:

execl("/bin/ls", "ls", "-la", NULL);

The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:

execlp("ls", "ls", "-la", NULL);

Accessing post variables using Java Servlets

The previous answers are correct but remember to use the name attribute in the input fields (html form) or you won't get anything. Example:

<input type="text" id="username" /> <!-- won't work --> <input type="text" name="username" /> <!-- will work --> <input type="text" name="username" id="username" /> <!-- will work too -->

All this code is HTML valid, but using getParameter(java.lang.String) you will need the name attribute been set in all parameters you want to receive.

Nested lists python

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
  results = []
  for numbers in lists:
    for numbers2 in numbers:
        results.append(numbers2) 
  return results
print flatten(n)

Output: n = [1,2,3,4,5,6,7,8,9]

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

Getting content/message from HttpResponseMessage

You need to call GetResponse().

Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();

Why use a ReentrantLock if one can use synchronized(this)?

You can use reentrant locks with a fairness policy or timeout to avoid thread starvation. You can apply a thread fairness policy. it will help avoid a thread waiting forever to get to your resources.

private final ReentrantLock lock = new ReentrantLock(true);
//the param true turns on the fairness policy. 

The "fairness policy" picks the next runnable thread to execute. It is based on priority, time since last run, blah blah

also, Synchronize can block indefinitely if it cant escape the block. Reentrantlock can have timeout set.

Convert a Unicode string to a string in Python (containing extra symbols)

Well, if you're willing/ready to switch to Python 3 (which you may not be due to the backwards incompatibility with some Python 2 code), you don't have to do any converting; all text in Python 3 is represented with Unicode strings, which also means that there's no more usage of the u'<text>' syntax. You also have what are, in effect, strings of bytes, which are used to represent data (which may be an encoded string).

http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

(Of course, if you're currently using Python 3, then the problem is likely something to do with how you're attempting to save the text to a file.)

java.lang.ClassNotFoundException on working app

I got this error when I ran my app on earlier versions of android. I thought SearchView was backwards compatible to Android 1.5, but it was created in 3.0. I removed its reference from the code and it worked.

Enable & Disable a Div and its elements in Javascript

The following selects all descendant elements and disables them:

$("#dcacl").find("*").prop("disabled", true);

But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:

$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);

To re-enable you just set "disabled" to false.

I want to Disable them at loading the page and then by a click i can enable them

OK, so put the above code in a document ready handler, and setup an appropriate click handler:

$(document).ready(function() {
    var $dcac1kids = $("#dcac1").find(":input");
    $dcac1kids.prop("disabled",true);

    // not sure what you want to click on to re-enable
    $("selector for whatever you want to click").one("click",function() {
       $dcac1kids.prop("disabled",false);
    }
}

I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one() since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one() to .click() if appropriate.

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

iPhone App Minus App Store?

  • Build your app
  • Upload to a crack site
  • (If you app is good enough) the crack version will be posted minutes later and ready for everyone to download ;-)

How to map with index in Ruby?

Ruby has Enumerator#with_index(offset = 0), so first convert the array to an enumerator using Object#to_enum or Array#map:

[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

Invoking JavaScript code in an iframe from the parent page

Folowing Nitin Bansal's answer

and for even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

Encode a FileStream to base64 with c#

You can also encode bytes to Base64. How to get this from a stream see here: How to convert an Stream into a byte[] in C#?

Or I think it should be also possible to use the .ToString() method and encode this.

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

How to set Android camera orientation properly?

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:

Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.

The method:

    protected void setDisplayOrientation(Camera camera, int angle){
    Method downPolymorphic;
    try
    {
        downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
        if (downPolymorphic != null)
            downPolymorphic.invoke(camera, new Object[] { angle });
    }
    catch (Exception e1)
    {
    }
}

And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :

    if (Integer.parseInt(Build.VERSION.SDK) >= 8)
        setDisplayOrientation(mCamera, 90);
    else
    {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation", 90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }
    }   

SQL Server - copy stored procedures from one db to another

Late one but gives more details that might be useful…

Here is a list of things you can do with advantages and disadvantages

Generate scripts using SSMS

  • Pros: extremely easy to use and supported by default
  • Cons: scripts might not be in the correct execution order and you might get errors if stored procedure already exists on secondary database. Make sure you review the script before executing.

Third party tools

  • Pros: tools such as ApexSQL Diff (this is what I use but there are many others like tools from Red Gate or Dev Art) will compare two databases in one click and generate script that you can execute immediately
  • Cons: these are not free (most vendors have a fully functional trial though)

System Views

  • Pros: You can easily see which stored procedures exist on secondary server and only generate those you don’t have.
  • Cons: Requires a bit more SQL knowledge

Here is how to get a list of all procedures in some database that don’t exist in another database

select *
from DB1.sys.procedures P
where P.name not in 
 (select name from DB2.sys.procedures P2)

How to redirect DNS to different ports

Possible solutions:

  1. Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.

  2. If you use AWS you can use the load balancer to redirect the request to specific port based on the host.

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

That worked for me:

$ export LC_ALL=en_US.UTF-8
$ export LANG=en_US.UTF-8

selected value get from db into dropdown select box option using php mysql error

BEST code and simple

<select id="example-getting-started" multiple="multiple" name="category">

    <?php
    $query = "select * from mine";
    $results = mysql_query($query);

    while ($rows = mysql_fetch_assoc(@$results)){ 
    ?>
    <option value="<?php echo $rows['category'];?>"><?php echo $rows['category'];?></option>

    <?php
    } 
    ?>
</select>

How to insert table values from one database to another database?

How to insert table values from one server/database to another database?

1 Creating Linked Servers {if needs} (SQL server 2008 R2 - 2012) http://technet.microsoft.com/en-us/library/ff772782.aspx#SSMSProcedure

2 configure the linked server to use Credentials a) http://technet.microsoft.com/es-es/library/ms189811(v=sql.105).aspx

EXEC sp_addlinkedsrvlogin 'NAMEOFLINKEDSERVER', 'false', null, 'REMOTEUSERNAME', 'REMOTEUSERPASSWORD'

-- CHECK SERVERS

SELECT * FROM sys.servers

-- TEST LINKED SERVERS

EXEC sp_testlinkedserver N'NAMEOFLINKEDSERVER'

INSERT INTO NEW LOCAL TABLE

SELECT * INTO NEWTABLE
FROM [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE

OR

INSERT AS NEW VALUES IN REMOTE TABLE

INSERT
INTO    [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
SELECT  *
FROM    localTABLE

INSERT AS NEW LOCAL TABLE VALUES

INSERT
INTO    localTABLE
SELECT  *
FROM    [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE

How to save password when using Subversion from the console

Unfortunately the answers did not solve the problem of asking for password for ssh+svn with a protected private key. After some research I found:

ssh-add

utility if you have a Linux computer. Make sure that you have your keys stored in /home/username/.ssh/ and type this command on Terminal.

how to set default method argument values?

You can accomplish this via method overloading.

public int doSomething(int arg1, int arg2)
{
        return 0;
}

public int doSomething()
{
        return doSomething(defaultValue0, defaultValue1);
}

By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

Change user-agent for Selenium web-driver

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

Setting the User Agent in Firefox

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

Both methods above were tested and found to work. I don't know about other browsers.

Getting the User Agent

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

The agent variable will contain the user agent.

How to get current date & time in MySQL?

$rs = $db->Insert('register',"'$fn','$ln','$email','$pass','$city','$mo','$fil'","'f_name','l_name=','email','password','city','contact','image'");

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

Make .gitignore ignore everything except a few files

I got this working

# Vendor
/vendor/braintree/braintree_php/*
!/vendor/braintree/braintree_php/lib

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Where to put the gradle.properties file

Gradle looks for gradle.properties files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).

Reference: https://gradle.org/docs/current/userguide/build_environment.html

Directory index forbidden by Options directive

Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/

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

For the records: the official documentation, as for Spring Boot v1.2.0.RELEASE and Spring v4.1.3.RELEASE:

If the only change you need to make to logging is to set the levels of various loggers then you can do that in application.properties using the "logging.level" prefix, e.g.

logging.level.org.springframework.web: DEBUG logging.level.org.hibernate: ERROR

You can also set the location of a file to log to (in addition to the console) using "logging.file".

To configure the more fine-grained settings of a logging system you need to use the native configuration format supported by the LoggingSystem in question. By default Spring Boot picks up the native configuration from its default location for the system (e.g. classpath:logback.xml for Logback), but you can set the location of the config file using the "logging.config" property.

Go install fails with error: no install location for directory xxx outside GOPATH

On OSX Mojave 10.14, go is typically installed at /usr/local/go.

Hence, setup these ENVs and you should be good to go.

export GOPATH=/usr/local/go && export GOBIN=/usr/local/go/bin

Also, add these to your bash_profile or zsh_profile if it works.

echo "export GOPATH=/usr/local/go && export GOBIN=/usr/local/go/bin" >> ~/.bash_profile && source ~/.bash_profile

Java: Instanceof and Generics

Provided your class extends a class with a generic parameter, you can also get this at runtime via reflection, and then use that for comparison, i.e.

class YourClass extends SomeOtherClass<String>
{

   private Class<?> clazz;

   public Class<?> getParameterizedClass()
   {
      if(clazz == null)
      {
         ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
          clazz = (Class<?>)pt.getActualTypeArguments()[0];
       }
       return clazz;
    }
}

In the case above, at runtime you will get String.class from getParameterizedClass(), and it caches so you don't get any reflection overhead upon multiple checks. Note that you can get the other parameterized types by index from the ParameterizedType.getActualTypeArguments() method.

Selecting one row from MySQL using mysql_* API

this shoude work

    <?php

require_once('connection.php');

 //fetch table rows from mysql db
$sql = "select  id,fname,lname,sms,phone from data";

    $result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));

    //create an array
    $emparray = array();

for ($i = 0; $i < 1; $i++) {
   $row =mysqli_fetch_assoc($result);

} $emparray[] = $row;
         echo $emparray ;
    mysqli_close($connection);
?>

Format date with Moment.js

The 2nd argument to moment() is a parsing format rather than an display format.

For that, you want the .format() method:

moment(testDate).format('MM/DD/YYYY');

Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.

SQL query to select distinct row with minimum value

SELECT DISTINCT 
FIRST_VALUE(ID) OVER (Partition by Game ORDER BY Point) AS ID,
Game,
FIRST_VALUE(Point) OVER (Partition by Game ORDER BY Point) AS Point
FROM #T

Meaning of "n:m" and "1:n" in database design

n:m --> if you dont know both n and m it is simply many to many and it is represented by a bridge table between 2 other tables like

   -- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CallTime DATETIME NOT NULL DEFAULT GETDATE(),
   CallerPhoneNumber CHAR(10) NOT NULL
)

-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
   Subject VARCHAR(250) NOT NULL,
   Notes VARCHAR(8000) NOT NULL,
   Completed BIT NOT NULL DEFAULT 0
)

this is the bridge table for implementing Mapping between 2 tables

CREATE TABLE dbo.PhoneCalls_Tickets
(
   PhoneCallID INT NOT NULL,
   TicketID INT NOT NULL
)

One to Many (1:n) is simply one table which has a column as primary key and another table which has this column as a foreign key relationship

Kind of like Product and Product Category where one product Category can have Many products

Generate SQL Create Scripts for existing tables with Query

Here's a slight variation on @Devart 's answer so you can get the CREATE script for a temp table.

Please note that since the @SQL variable is an NVARCHAR(MAX) data type you might not be able to copy it from the result using just only SSMS. Please see this question to see how to get the full value of a MAX field.

DECLARE @temptable_objectid INT = OBJECT_ID('tempdb..#Temp');

DECLARE 
      @object_name SYSNAME
    , @object_id INT

SELECT  
      @object_name = '[' + s.name + '].[' + o.name + ']'
    , @object_id = o.[object_id]
FROM tempdb.sys.objects o WITH (NOWAIT)
JOIN tempdb.sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE object_id = @temptable_objectid

DECLARE @SQL NVARCHAR(MAX) = ''

;WITH index_column AS 
(
    SELECT 
          ic.[object_id]
        , ic.index_id
        , ic.is_descending_key
        , ic.is_included_column
        , c.name
    FROM tempdb.sys.index_columns ic WITH (NOWAIT)
    JOIN tempdb.sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id
    WHERE ic.[object_id] = @object_id
),
fk_columns AS 
(
     SELECT 
          k.constraint_object_id
        , cname = c.name
        , rcname = rc.name
    FROM tempdb.sys.foreign_key_columns k WITH (NOWAIT)
    JOIN tempdb.sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id AND rc.column_id = k.referenced_column_id 
    JOIN tempdb.sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id AND c.column_id = k.parent_column_id
    WHERE k.parent_object_id = @object_id
)
SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
    SELECT CHAR(9) + ', [' + c.name + '] ' + 
        CASE WHEN c.is_computed = 1
            THEN 'AS ' + cc.[definition] 
            ELSE UPPER(tp.name) + 
                CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('nvarchar', 'nchar', 'ntext')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') 
                       THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
                     WHEN tp.name = 'decimal' 
                       THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
                    ELSE ''
                END +
                CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END +
                CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
                CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + 
                CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END 
        END + CHAR(13)
    FROM tempdb.sys.columns c WITH (NOWAIT)
    JOIN tempdb.sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
    LEFT JOIN tempdb.sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id
    LEFT JOIN tempdb.sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id
    LEFT JOIN tempdb.sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
    WHERE c.[object_id] = @object_id
    ORDER BY c.column_id
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ')
    + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + 
                    (SELECT STUFF((
                         SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END
                         FROM tempdb.sys.index_columns ic WITH (NOWAIT)
                         JOIN tempdb.sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
                         WHERE ic.is_included_column = 0
                             AND ic.[object_id] = k.parent_object_id 
                             AND ic.index_id = k.unique_index_id     
                         FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ''))
            + ')' + CHAR(13)
            FROM tempdb.sys.key_constraints k WITH (NOWAIT)
            WHERE k.parent_object_id = @object_id 
                AND k.[type] = 'PK'), '') + ')'  + CHAR(13)
    + ISNULL((SELECT (
        SELECT CHAR(13) +
             'ALTER TABLE ' + @object_name + ' WITH' 
            + CASE WHEN fk.is_not_trusted = 1 
                THEN ' NOCHECK' 
                ELSE ' CHECK' 
              END + 
              ' ADD CONSTRAINT [' + fk.name  + '] FOREIGN KEY(' 
              + STUFF((
                SELECT ', [' + k.cname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')' +
              ' REFERENCES [' + SCHEMA_NAME(ro.[schema_id]) + '].[' + ro.name + '] ('
              + STUFF((
                SELECT ', [' + k.rcname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')'
            + CASE 
                WHEN fk.delete_referential_action = 1 THEN ' ON DELETE CASCADE' 
                WHEN fk.delete_referential_action = 2 THEN ' ON DELETE SET NULL'
                WHEN fk.delete_referential_action = 3 THEN ' ON DELETE SET DEFAULT' 
                ELSE '' 
              END
            + CASE 
                WHEN fk.update_referential_action = 1 THEN ' ON UPDATE CASCADE'
                WHEN fk.update_referential_action = 2 THEN ' ON UPDATE SET NULL'
                WHEN fk.update_referential_action = 3 THEN ' ON UPDATE SET DEFAULT'  
                ELSE '' 
              END 
            + CHAR(13) + 'ALTER TABLE ' + @object_name + ' CHECK CONSTRAINT [' + fk.name  + ']' + CHAR(13)
        FROM tempdb.sys.foreign_keys fk WITH (NOWAIT)
        JOIN tempdb.sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id
        WHERE fk.parent_object_id = @object_id
        FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)')), '')
    + ISNULL(((SELECT
         CHAR(13) + 'CREATE' + CASE WHEN i.is_unique = 1 THEN ' UNIQUE' ELSE '' END 
                + ' NONCLUSTERED INDEX [' + i.name + '] ON ' + @object_name + ' (' +
                STUFF((
                SELECT ', [' + c.name + ']' + CASE WHEN c.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END
                FROM index_column c
                WHERE c.is_included_column = 0
                    AND c.index_id = i.index_id
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')'  
                + ISNULL(CHAR(13) + 'INCLUDE (' + 
                    STUFF((
                    SELECT ', [' + c.name + ']'
                    FROM index_column c
                    WHERE c.is_included_column = 1
                        AND c.index_id = i.index_id
                    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')', '')  + CHAR(13)
        FROM tempdb.sys.indexes i WITH (NOWAIT)
        WHERE i.[object_id] = @object_id
            AND i.is_primary_key = 0
            AND i.[type] = 2
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
    ), '')

SELECT @SQL

Test if object implements interface

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

If you currently have Red Gate SQL Toolbelt, you will need to unistall that too before continuing. Somehow it adds a reference to the 2005 version of the SQL Management Studio.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Retrieving the output of subprocess.call()

In Ipython shell:

In [8]: import subprocess
In [9]: s=subprocess.check_output(["echo", "Hello World!"])
In [10]: s
Out[10]: 'Hello World!\n'

Based on sargue's answer. Credit to sargue.

Wait till a Function with animations is finished until running another Function

You can use the javascript Promise and async/await to implement a synchronized call of the functions.

Suppose you want to execute n number of functions in a synchronized manner that are stored in an array, here is my solution for that.

_x000D_
_x000D_
async function executeActionQueue(funArray) {_x000D_
  var length = funArray.length;_x000D_
  for(var i = 0; i < length; i++) {_x000D_
    await executeFun(funArray[i]);_x000D_
  }_x000D_
};_x000D_
_x000D_
function executeFun(fun) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    _x000D_
    // Execute required function here_x000D_
    _x000D_
    fun()_x000D_
      .then((data) => {_x000D_
        // do required with data _x000D_
        resolve(true);_x000D_
      })_x000D_
      .catch((error) => {_x000D_
      // handle error_x000D_
        resolve(true);_x000D_
      });_x000D_
  })_x000D_
};_x000D_
_x000D_
executeActionQueue(funArray);
_x000D_
_x000D_
_x000D_

Get Selected value of a Combobox

If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:

Private Sub Worksheet_Change(ByVal Target As Range)

    MsgBox Target.Value

End Sub

If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.

Public WithEvents Cbx As MSForms.ComboBox

Private Sub Cbx_Change()

    MsgBox Cbx.Value

End Sub

Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.

Private mcolComboEvents As Collection

Private Sub Class_Initialize()
    Set mcolComboEvents = New Collection
End Sub

Private Sub Class_Terminate()
    Set mcolComboEvents = Nothing
End Sub

Public Sub Add(clsComboEvent As CComboEvent)

    mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name

End Sub

Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.

You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.

Public gclsComboEvents As CComboEvents

Public Sub AddCombox()

    Dim oleo As OLEObject
    Dim clsComboEvent As CComboEvent

    Set gclsComboEvents = New CComboEvents

    For Each oleo In Sheet1.OLEObjects
        If TypeName(oleo.Object) = "ComboBox" Then
            Set clsComboEvent = New CComboEvent
            Set clsComboEvent.Cbx = oleo.Object
            gclsComboEvents.Add clsComboEvent
        End If
    Next oleo

End Sub

Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.

You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm

Unable to Connect to GitHub.com For Cloning

You are probably behind a firewall. Try cloning via https – that has a higher chance of not being blocked:

git clone https://github.com/angular/angular-phonecat.git

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

Find multiple files and rename them in Linux

You can use this below.

rename --no-act 's/\.html$/\.php/' *.html */*.html

Java Replacing multiple different substring in a string at once (or in the most efficient way)

public String replace(String input, Map<String, String> pairs) {
  // Reverse lexic-order of keys is good enough for most cases,
  // as it puts longer words before their prefixes ("tool" before "too").
  // However, there are corner cases, which this algorithm doesn't handle
  // no matter what order of keys you choose, eg. it fails to match "edit"
  // before "bed" in "..bedit.." because "bed" appears first in the input,
  // but "edit" may be the desired longer match. Depends which you prefer.
  final Map<String, String> sorted = 
      new TreeMap<String, String>(Collections.reverseOrder());
  sorted.putAll(pairs);
  final String[] keys = sorted.keySet().toArray(new String[sorted.size()]);
  final String[] vals = sorted.values().toArray(new String[sorted.size()]);
  final int lo = 0, hi = input.length();
  final StringBuilder result = new StringBuilder();
  int s = lo;
  for (int i = s; i < hi; i++) {
    for (int p = 0; p < keys.length; p++) {
      if (input.regionMatches(i, keys[p], 0, keys[p].length())) {
        /* TODO: check for "edit", if this is "bed" in "..bedit.." case,
         * i.e. look ahead for all prioritized/longer keys starting within
         * the current match region; iff found, then ignore match ("bed")
         * and continue search (find "edit" later), else handle match. */
        // if (better-match-overlaps-right-ahead)
        //   continue;
        result.append(input, s, i).append(vals[p]);
        i += keys[p].length();
        s = i--;
      }
    }
  }
  if (s == lo) // no matches? no changes!
    return input;
  return result.append(input, s, hi).toString();
}

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

How to easily map c++ enums to strings

I remember having answered this elsewhere on StackOverflow. Repeating it here. Basically it's a solution based on variadic macros, and is pretty easy to use:

#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \
inline std::ostream& operator<<(std::ostream& os, name value) { \
std::string enumName = #name; \
std::string str = #__VA_ARGS__; \
int len = str.length(); \
std::vector<std::string> strings; \
std::ostringstream temp; \
for(int i = 0; i < len; i ++) { \
if(isspace(str[i])) continue; \
        else if(str[i] == ',') { \
        strings.push_back(temp.str()); \
        temp.str(std::string());\
        } \
        else temp<< str[i]; \
} \
strings.push_back(temp.str()); \
os << enumName << "::" << strings[static_cast<int>(value)]; \
return os;} 

To use it in your code, simply do:

AWESOME_MAKE_ENUM(Animal,
    DOG,
    CAT,
    HORSE
);
auto dog = Animal::DOG;
std::cout<<dog;

How can I reset eclipse to default settings?

You can reset settings for eclipse by deleting .metadata folder from your current workspace.

This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.

You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".

import Have a look here : import project in eclipse

What is aria-label and how should I use it?

If you wants to know how aria-label helps you practically .. then follow the steps ... you will get it by your own ..

Create a html page having below code

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <button title="Close"> X </button>
    <br />
    <br />
    <br />
    <br />
    <button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>

Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin

Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button .. will tell you only x button .. but in case of second x button .. you will hear back to the page button only..

i hope you got it well now!!

What is the difference between atan and atan2 in C++?

With atan2 you can determine the quadrant as stated here.

You can use atan2 if you need to determine the quadrant.

Split Java String by New Line

If, for some reason, you don't want to use String.split (for example, because of regular expressions) and you want to use functional programming on Java 8 or newer:

List<String> lines = new BufferedReader(new StringReader(string))
        .lines()
        .collect(Collectors.toList());

MongoDB not equal to

If you want to do multiple $ne then do

db.users.find({name : {$nin : ["mary", "dick", "jane"]}})

How to use SearchView in Toolbar Android

If you want to add it directly in the toolbar.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Search"
            android:layout_centerHorizontal="true" />

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

INSERT INTO TABLE from comma separated varchar-list

Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.

The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (items varchar(8000))       
as       
begin       
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return       
end  

select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
    myDict[k] = A.get(k, 0)+B.get(k, 0)

In jQuery, how do I select an element by its name attribute?

This should do it, all of this is in the documentation, which has a very similar example to this:

$("input[type='radio'][name='theme']").click(function() {
    var value = $(this).val();
});

I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.

Select option padding not working in chrome

This simple hack will indent the text. Works well.

select {
  text-indent: 5px;
}

how do I get the bullet points of a <ul> to center with the text?

Add list-style-position: inside to the ul element. (example)

The default value for the list-style-position property is outside.

_x000D_
_x000D_
ul {_x000D_
    text-align: center;_x000D_
    list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Another option (which yields slightly different results) would be to center the entire ul element:

_x000D_
_x000D_
.parent {_x000D_
  text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert a table to a data frame

I figured it out already:

as.data.frame.matrix(mytable) 

does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this as.data.frame.matrix() function for contingency tables at the Computational Ecology blog.

Naming conventions for Java methods that return boolean

I want to point a different view on this general naming convention, e.g.:

see java.util.Set: boolean add?(E e)

where the rationale is:

do some processing then report whether it succeeded or not.

While the return is indeed a boolean the method's name should point the processing to complete instead of the result type (boolean for this example).

Your createFreshSnapshot example seems for me more related to this point of view because seems to mean this: create a fresh-snapshot then report whether the create-operation succeeded. Considering this reasoning the name createFreshSnapshot seems to be the best one for your situation.

How to restart ADB manually from Android Studio

AndroidStudio:

Go to: Tools -> Android -> Android Device Monitor

see the Device tab, under many icons, last one is drop-down arrow.

Open it.

At the bottom: RESET ADB.

Convert to/from DateTime and Time in Ruby

Improving on Gordon Wilson solution, here is my try:

def to_time
  #Convert a fraction of a day to a number of microseconds
  usec = (sec_fraction * 60 * 60 * 24 * (10**6)).to_i
  t = Time.gm(year, month, day, hour, min, sec, usec)
  t - offset.abs.div(SECONDS_IN_DAY)
end

You'll get the same time in UTC, loosing the timezone (unfortunately)

Also, if you have ruby 1.9, just try the to_time method

Should IBOutlets be strong or weak under ARC?

It looks like something has changed over the years and now Apple recommends to use strong in general. The evidence on their WWDC session is in session 407 - Implementing UI Designs in Interface Builder and starts at 32:30. My note from what he says is (almost, if not exactly, quoting him):

  • outlet connections in general should be strong especially if we connect a subview or constraint that is not always retained by the view hierarchy

  • weak outlet connection might be needed when creating custom views that has some reference to something back up in the view hierarchy and in general it is not recommended

In other wards it should be always strong now as long as some of our custom view doesn't create a retain cycle with some of the view up in the view hierarchy

EDIT :

Some may ask the question. Does keeping it with a strong reference doesn't create a retain cycle as the root view controller and the owning view keeps the reference to it? Or why that changed happened? I think the answer is earlier in this talk when they describe how the nibs are created from the xib. There is a separate nib created for a VC and for the view. I think this might be the reason why they change the recommendations. Still it would be nice to get a deeper explanation from Apple.

How to get the current date and time of your timezone in Java?

As Jon Skeet already said, java.util.Date does not have a time zone. A Date object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.

When you format a Date object into a string, for example by using SimpleDateFormat, then you can set the time zone on the DateFormat object to let it know in which time zone you want to display the date and time:

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));

If you want the local time zone of the computer that your program is running on, use:

df.setTimeZone(TimeZone.getDefault());

DateTime's representation in milliseconds?

SELECT CAST(DATEDIFF(S, '1970-01-01', SYSDATETIME()) AS BIGINT) * 1000

This does not give you full precision, but DATEDIFF(MS... causes overflow. If seconds are good enough, this should do it.

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

Android Fastboot devices not returning device

Are you rebooting the device into the bootloader and entering fastboot USB on the bootloader menu?

Try

adb reboot bootloader

then look for on screen instructions to enter fastboot mode.

java.net.ConnectException: Connection refused

In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)

How to search through all Git and Mercurial commits in the repository for a certain string?

In Mercurial you use hg log --keyword to search for keywords in the commit messages and hg log --user to search for a particular user. See hg help log for other ways to limit the log.

Convert list to array in Java

Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example

import java.util.ArrayList;

public class CopyElementsOfArrayListToArrayExample {

  public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to ArrayList
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");

    /*
      To copy all elements of java ArrayList object into array use
      Object[] toArray() method.
    */

    Object[] objArray = arrayList.toArray();

    //display contents of Object array
    System.out.println("ArrayList elements are copied into an Array.
                                                  Now Array Contains..");
    for(int index=0; index < objArray.length ; index++)
      System.out.println(objArray[index]);
  }
}

/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5

Is there any difference between a GUID and a UUID?

GUID is Microsoft's implementation of the UUID standard.

Per Wikipedia:

The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.

An updated quote from that same Wikipedia article:

RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…

Reset CSS display property to default value

If using javascript is allowed, you can set the display property to an empty string. This will cause it to use the default for that particular element.

var element = document.querySelector('span.selector');

// Set display to empty string to use default for that element
element.style.display = '';

Here is a link to a jsbin.

This is nice because you don't have to worry about the different types of display to revert to (block, inline, inline-block, table-cell, etc).

But, it requires javascript, so if you are looking for a css-only solution, then this is not the solution for you.

Note: This overrides inline styles, but not styles set in css

What is the non-jQuery equivalent of '$(document).ready()'?

This does not answer the question nor does it show any non-jQuery code. See @ sospedra's answer below.

The nice thing about $(document).ready() is that it fires before window.onload. The load function waits until everything is loaded, including external assets and images. $(document).ready, however, fires when the DOM tree is complete and can be manipulated. If you want to acheive DOM ready, without jQuery, you might check into this library. Someone extracted just the ready part from jQuery. Its nice and small and you might find it useful:

domready at Google Code

Warning comparison between pointer and integer

In this line ...

if (*message == "\0") {

... as you can see in the warning ...

warning: comparison between pointer and integer
      ('int' and 'char *')

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

Can't import org.apache.http.HttpResponse in Android Studio

in case you are going to start development, go fot OkHttp from square, otherwise if you need to keep your previous code running, then add legacy library to your project dependencies:

dependencies {
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

How to locate the git config file in Mac

The solution to the problem is:

  1. Find the .gitconfig file

  2. [user] name = 1wQasdTeedFrsweXcs234saS56Scxs5423 email = [email protected] [credential] helper = osxkeychain [url ""] insteadOf = git:// [url "https://"] [url "https://"] insteadOf = git://

there would be a blank url="" replace it with url="https://"

[user]
    name = 1wQasdTeedFrsweXcs234saS56Scxs5423
    email = [email protected]
[credential]
    helper = osxkeychain
[url "https://"]
    insteadOf = git://
[url "https://"]
[url "https://"]
    insteadOf = git://

This will work :)

Happy Bower-ing

Filter data.frame rows by a logical condition

Sometimes the column you want to filter may appear in a different position than column index 2 or have a variable name.

In this case, you can simply refer the column name you want to filter as:

columnNameToFilter = "cell_type"
expr[expr[[columnNameToFilter]] == "hesc", ]

Has anyone gotten HTML emails working with Twitter Bootstrap?

I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link: http://zurb.com/ink/

Hope it helps someone.

Ninja edit: It has since been renamed to Foundation for Emails and the new link is: https://foundation.zurb.com/emails.html

Silent but deadly edit: New link https://get.foundation/emails.html

Set markers for individual points on a line in Matplotlib

Specify the keyword args linestyle and/or marker in your call to plot.

For example, using a dashed line and blue circle markers:

plt.plot(range(10), linestyle='--', marker='o', color='b')

A shortcut call for the same thing:

plt.plot(range(10), '--bo')

example1

Here is a list of the possible line and marker styles:

================    ===============================
character           description
================    ===============================
   -                solid line style
   --               dashed line style
   -.               dash-dot line style
   :                dotted line style
   .                point marker
   ,                pixel marker
   o                circle marker
   v                triangle_down marker
   ^                triangle_up marker
   <                triangle_left marker
   >                triangle_right marker
   1                tri_down marker
   2                tri_up marker
   3                tri_left marker
   4                tri_right marker
   s                square marker
   p                pentagon marker
   *                star marker
   h                hexagon1 marker
   H                hexagon2 marker
   +                plus marker
   x                x marker
   D                diamond marker
   d                thin_diamond marker
   |                vline marker
   _                hline marker
================    ===============================

edit: with an example of marking an arbitrary subset of points, as requested in the comments:

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(-np.pi, np.pi, 30)
ys = np.sin(xs)
markers_on = [12, 17, 18, 19]
plt.plot(xs, ys, '-gD', markevery=markers_on)
plt.show()

example2

This last example using the markevery kwarg is possible in since 1.4+, due to the merge of this feature branch. If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot. See the edit history for more details.

Creating folders inside a GitHub repository without using Git

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

For example, if I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub blog):

Enter image description here

Why use HttpClient for Synchronous Connection

I'd re-iterate Donny V. answer and Josh's

"The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support."

(and upvote if I had the reputation.)

I can't remember the last time if ever, I was grateful of the fact HttpWebRequest threw exceptions for status codes >= 400. To get around these issues you need to catch the exceptions immediately, and map them to some non-exception response mechanisms in your code...boring, tedious and error prone in itself. Whether it be communicating with a database, or implementing a bespoke web proxy, its 'nearly' always desirable that the Http driver just tell your application code what was returned, and leave it up to you to decide how to behave.

Hence HttpClient is preferable.

What to do about Eclipse's "No repository found containing: ..." error messages?

I've had the same issue since mid 2018. Performing a search, this issue has been reported since 2011. I'm surprised workarounds are proposed for this. Unfortunately they havent't worked for me, currently the only fix seems to completely reinstall Eclipse. As the most upvoted suggestion here, many of the suggestions are contradicting, suggesting trial-error guesses.

Besides these workarounds, IMHO this requires a fix. We're in 2019 now, surely there is a way to fix this recurring issue? How can there not be a simple fix i.e. if repo URL not found: skip and continue with next URL / update (without aborting as critical error and preventing any other update)?

Count the items from a IEnumerable<T> without iterating?

The best way I found is count by converting it to a list.

IEnumerable<T> enumList = ReturnFromSomeFunction();

int count = new List<T>(enumList).Count;

Can I escape a double quote in a verbatim string literal?

For adding some more information, your example will work without the @ symbol (it prevents escaping with \), this way:

string foo = "this \"word\" is escaped!";

It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).

How do I reverse an int array in Java?

It is most efficient to simply iterate the array backwards.

I'm not sure if Aaron's solution does this vi this call Collections.reverse(list); Does anyone know?

How to find the most recent file in a directory using .NET, and without looping?

Another approach if you are using Directory.EnumerateFiles and want to read files in latest modified by first.

foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))

}

asynchronous vs non-blocking

synchronous / asynchronous is to describe the relation between two modules.
blocking / non-blocking is to describe the situation of one module.

An example:
Module X: "I".
Module Y: "bookstore".
X asks Y: do you have a book named "c++ primer"?

  1. blocking: before Y answers X, X keeps waiting there for the answer. Now X (one module) is blocking. X and Y are two threads or two processes or one thread or one process? we DON'T know.

  2. non-blocking: before Y answers X, X just leaves there and do other things. X may come back every two minutes to check if Y has finished its job? Or X won't come back until Y calls him? We don't know. We only know that X can do other things before Y finishes its job. Here X (one module) is non-blocking. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.

  3. synchronous: before Y answers X, X keeps waiting there for the answer. It means that X can't continue until Y finishes its job. Now we say: X and Y (two modules) are synchronous. X and Y are two threads or two processes or one thread or one process? we DON'T know.

  4. asynchronous: before Y answers X, X leaves there and X can do other jobs. X won't come back until Y calls him. Now we say: X and Y (two modules) are asynchronous. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.


Please pay attention on the two bold-sentences above. Why does the bold-sentence in the 2) contain two cases whereas the bold-sentence in the 4) contains only one case? This is a key of the difference between non-blocking and asynchronous.

Here is a typical example about non-blocking & synchronous:

// thread X
while (true)
{
    msg = recv(Y, NON_BLOCKING_FLAG);
    if (msg is not empty)
    {
        break;
    }
    else
    {
        sleep(2000); // 2 sec
    }
}

// thread Y
// prepare the book for X
send(X, book);

You can see that this design is non-blocking (you can say that most of time this loop does something nonsense but in CPU's eyes, X is running, which means that X is non-blocking) whereas X and Y are synchronous because X can't continue to do any other things(X can't jump out of the loop) until it gets the book from Y.
Normally in this case, make X blocking is much better because non-blocking spends much resource for a stupid loop. But this example is good to help you understand the fact: non-blocking doesn't mean asynchronous.

The four words do make us confused easily, what we should remember is that the four words serve for the design of architecture. Learning about how to design a good architecture is the only way to distinguish them.

For example, we may design such a kind of architecture:

// Module X = Module X1 + Module X2
// Module X1
while (true)
{
    msg = recv(many_other_modules, NON_BLOCKING_FLAG);
    if (msg is not null)
    {
        if (msg == "done")
        {
            break;
        }
        // create a thread to process msg
    }
    else
    {
        sleep(2000); // 2 sec
    }
}
// Module X2
broadcast("I got the book from Y");


// Module Y
// prepare the book for X
send(X, book);

In the example here, we can say that

  • X1 is non-blocking
  • X1 and X2 are synchronous
  • X and Y are asynchronous

If you need, you can also describe those threads created in X1 with the four words.

The more important things are: when do we use synchronous instead of asynchronous? when do we use blocking instead of non-blocking? Is making X1 blocking better than non-blocking? Is making X and Y synchronous better than asynchronous? Why is Nginx non-blocking? Why is Apache blocking? These questions are what you must figure out.

To make a good choice, you must analyze your need and test the performance of different architectures. There is no such an architecture that is suitable for various of needs.

Casting objects in Java

The example you are referring to is called Upcasting in java.

It creates a subclass object with a super class variable pointing to it.

The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.

For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine

class Machine{

    public void start(){

        System.out.println("Machine Started");
    }
}

class Camera extends Machine{
     public void start(){

            System.out.println("Camera Started");
        }
     public void snap(){
         System.out.println("Photo taken");
     }
 }
Machine machine1 = new Camera();
machine1.start();

If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started" The variable is still a reference of Machine class. If you attempt machine1.snap(); the code will not compile

The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap() wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start()). You can not ask a machine reference to take a snap. :)