Programs & Examples On #Tnsnames

The Oracle `tnsnames.ora` is a client site configuration file with database server connection details.

Oracle PL Sql Developer cannot find my tnsnames.ora file

I had the same problema, but as described in the manual.pdf, you have to:

You are using an Oracle Instant Client but have not set all required environment variables:

  • PATH: Needs to include the Instant Client directory where oci.dll is located
  • TNS_ADMIN: Needs to point to the directory where tnsnames.ora is located.
  • NLS_LANG: Defines the language, territory, and character set for the client.

Regards

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

Also in addition to above solutions, also check the location where the tnsname ora file exists and compare with the path in the environment variable

Use tnsnames.ora in Oracle SQL Developer

  • In SQLDeveloper browse Tools --> Preferences, as shown in below image.

    SQLDeveloper access preferences

  • In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
  • Then click on Ok, as shown in below diagram.
    tnsnames.ora available at Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN

    SQLDeveloper update tnsnames directory

Now you can connect via the TNSnames options.

Oracle - What TNS Names file am I using?

By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin directory on UNIX operating systems and in the ORACLE_HOME\network\admin directory on Windows operating systems. tnsnames.ora can also be stored the following locations:

The directory specified by the TNS_ADMIN environment variable (or registry value)

On UNIX operating systems, the global configuration directory. For example, on the Solaris Operating System, this directory is /var/opt/oracle

If you have multiple ORACLE_HOMES, be aware of which one you are using, as the location of the tnsnames.ora file can vary from one ORACLE_HOME to the next.

For the person who mentioned the TWO_TASK environment variable, that is used to set a default database service name to connect to (which could be a database on another server). The service name you set TWO_TASK to is then looked up in the tnsnames.ora file when you connect.

Oracle TNS names not showing when adding new connection to SQL Developer

The steps mentioned by Jason are very good and should work. There is a little twist with SQL Developer, though. It caches the connection specifications (host, service name, port) the first time it reads the tnsnames.ora file. Then, it does not invalidate the specs when the original entry is removed from the tnsname.ora file. The cache persists even after SQL Developer has been terminated and restarted. This is not such an illogical way of handling the situation. Even if a tnsnames.ora file is temporarily unavailable, SQL Developer can still make the connection as long as the original specifications are still true. The problem comes with their next little twist. SQL Developer treats service names in the tnsnames.ora file as case-sensitive values when resolving the connection. So if you used to have an entry name ABCD.world in the file and you replaced it with an new entry named abcd.world, SQL Developer would NOT update its connection specs for ABCD.world - it will treat abcd.world as a different connection altogether. Why am I not surprised that an Oracle product would treat as case-sensitive the contents of an oracle-developed file format that is expressly case-insensitive?

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

I had the same issue on Windows 7. The cause was, that I had been connected to VPN using Cisco AnyConnect Secure Mobility Client.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

A "little" late to the party but the real answer to this - if you use Oracle.ManagedDataAccess ODP.NET provider, you should forget about things like network\admin, Oracle client, Oracle_Home, etc.

Here is what you need

  1. Download and install Oracle Developer Tools for VS or ODAC. Note - Dev tools will install ODAC for you. This will create relatively small installation under C:\Program Files (x86). With full dev tools, under 60Mb
  2. In your project you will install Nuget package with corresponding version of ODP.net (Oracle.ManagedDataAccess.dll) which you will reference
  3. At this point you have 2 options to connect.

    • a) In the connection string set datasource in the following format

      DataSource=ServerName:Port/SID . . . or DataSource=IP:Port/SID . . .

    • b) Create tnsnames.ora file (only it is going to be different from previous experiences). Have entry in it:

      AAA = (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ServerNameOrIP)(PORT = 1521))
      (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = SIDNAME)))

      And place this file into your bin folder, where your application is running from. Now you can connect using your connection name - DataSource=AAA . . . So, even though you have tnsnames.ora, with ODP.net managed it works a bit different - you create local TNS file. And now, it is easy to manage it.

To summarize - with managed, no need for heavy Oracle Client, Oracle_home or knowing depths of oracle installation folders. Everything can be done within your .net application structures.

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

Converting string to numeric

I suspect you are having a problem with factors. For example,

> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8

Some comments:

  • You mention that your vector contains the characters "Down" and "NoData". What do expect/want as.numeric to do with these values?
  • In read.csv, try using the argument stringsAsFactors=FALSE
  • Are you sure it's sep="/t and not sep="\t"
  • Use the command head(pitchman) to check the first fews rows of your data
  • Also, it's very tricky to guess what your problem is when you don't provide data. A minimal working example is always preferable. For example, I can't run the command pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t") since I don't have access to the data set.

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

CSS content generation before or after 'input' elements

Use tags label and our method for =, is bound to input. If follow the rules of the form, and avoid confusion with tags, use the following:

<style type="text/css">
    label.lab:before { content: 'input: '; }
</style>

or compare (short code):

<style type="text/css">
    div label { content: 'input: '; color: red; }
</style>

form....

<label class="lab" for="single"></label><input name="n" id="single" ...><label for="single"> - simle</label>

or compare (short code):

<div><label></label><input name="n" ...></div>

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

You can silence the "Snapshotting a view" warning by referencing the view property before presenting the view controller. Doing so causes the view to load and allows iOS render it before taking the snapshot.

UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
controller.modalPresentationStyle = UIModalPresentationPopover;
controller.popoverPresentationController.barButtonItem = (UIBarButtonItem *)sender;

... setup the UIAlertController ... 

[controller view]; // <--- Add to silence the warning.

[self presentViewController:controller animated:YES completion:nil];

Format ints into string of hex

From Python documentation. Using the built in format() function you can specify hexadecimal base using an 'x' or 'X' Example:

x= 255 print('the number is {:x}'.format(x))

Output:

the number is ff

Here are the base options

Type
'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the corresponding unicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. None The same as 'd'.

List of lists into numpy array

>>> numpy.array([[1, 2], [3, 4]]) 
array([[1, 2], [3, 4]])

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

How to open CSV file in R when R says "no such file or directory"?

In my case this very problem was raised by wrong spelling, lower case 'c:' instead of upper case 'C:' in the path. I corrected spelling and problem vanished.

How to create a label inside an <input> element?

When you start typing it will disappear.If empty it will appear again.

        <%= f.text_field :user_email,:value=>"",:placeholder => "Eg:[email protected]"%>

Simplest way...

How to tell git to use the correct identity (name and email) for a given project?

Edit the config file with in ".git" folder to maintain the different username and email depends upon the repository

  • Go to Your repository
  • Show the hidden files and go to ".git" folder
  • Find the "config" file
  • Add the below lines at EOF

[user]

name = Bob

email = [email protected]

This below command show you which username and email set for this repository.

git config --get user.name

git config --get user.email

Example: for mine that config file in D:\workspace\eclipse\ipchat\.git\config

Here ipchat is my repo name

How to check if an element is off-screen

  • Get the distance from the top of the given element
  • Add the height of the same given element. This will tell you the total number from the top of the screen to the end of the given element.
  • Then all you have to do is subtract that from total document height

    jQuery(function () {
        var documentHeight = jQuery(document).height();
        var element = jQuery('#you-element');
        var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
        alert(distanceFromBottom)
    });
    

Twig ternary operator, Shorthand if-then-else

Support for the extended ternary operator was added in Twig 1.12.0.

  1. If foo echo yes else echo no:

    {{ foo ? 'yes' : 'no' }}
    
  2. If foo echo it, else echo no:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    
  3. If foo echo yes else echo nothing:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    
  4. Returns the value of foo if it is defined and not null, no otherwise:

    {{ foo ?? 'no' }}
    
  5. Returns the value of foo if it is defined (empty values also count), no otherwise:

    {{ foo|default('no') }}
    

Is it possible to run a .NET 4.5 app on XP?

The Mono project dropped Windows XP support and "forgot" to mention it. Although they still claim Windows XP SP2 is the minimum supported version, it is actually Windows Vista.

The last version of Mono to support Windows XP was 3.2.3.

Use multiple css stylesheets in the same html page

Yes, you can include multiple style sheets, but you need to label them as alternate style sheets and give the user some way to activate them using JavaScript - perhaps by clicking a link.

To create an alternate style sheet:

<link type="text/css" href="nameOfAlterateStyleSheet.css" rel="alternate stylesheet" title="Blue" />

Next create a method in your Javascript file that will: 1. Load all the style sheets in an array 2. Example:

function getCSSArray()
{
var links = document.getElementsByTagName("link");
var link;
for(var i = 0; i < links.length; i++)
{
    link = links[i];
    if(/stylesheet/.test(link.rel))
    {
        sheets.push(link);
    }
}

    return sheets;
}

Then go through the array using some type of if/else loop that disables the style sheets you don't want and enables the style sheet you want. (You can write a separate method or insert the loop into the method above. I like to use the onload command to load the CSS array with the page, then call the printView method.)

function printView()
{
var sheet;
var title1 = "printVersion";
for(i = 0; i < sheets.length; i++)
{
    sheet = sheets[i];
            if(sheet.title == title1)
    {
        sheet.disabled = false;
    }
    else
    {
        sheet.disabled = true;
    }

Lastly, create code in your HTML document that the user will activate the JavaScript method such as:

 <a href="#" onClick ="methodName();">Link Name</a>

Run JavaScript when an element loses focus

You want to use the onblur event.

<input type="text" name="name" value="value" onblur="alert(1);"/>

Start script missing error when running npm start

"scripts": {
  "prestart": "npm install",
  "start": "http-server -a localhost -p 8000 -c-1"
}

add this code snippet in your package.json, depending on your own configuration.

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

In my case this error appeared out of blue. While staring at that mysterious error I've realized, that I was trying to run the command outside of vm...

Repeat string to certain length

Yay recursion!

def trunc(s,l):
    if l > 0:
        return s[:l] + trunc(s, l - len(s))
    return ''

Won't scale forever, but it's fine for smaller strings. And it's pretty.

I admit I just read the Little Schemer and I like recursion right now.

Could not resolve '...' from state ''

I had a case where the error was thrown by a

$state.go('');

Which is obvious. I guess this can help someone in future.

Are one-line 'if'/'for'-statements good Python style?

Well,

if "exam" in "example": print "yes!"

Is this an improvement? No. You could even add more statements to the body of the if-clause by separating them with a semicolon. I recommend against that though.

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Decimal precision and scale in EF Code First

In EF6

modelBuilder.Properties()
    .Where(x => x.GetCustomAttributes(false).OfType<DecimalPrecisionAttribute>().Any())
    .Configure(c => {
        var attr = (DecimalPrecisionAttribute)c.ClrPropertyInfo.GetCustomAttributes(typeof (DecimalPrecisionAttribute), true).FirstOrDefault();

        c.HasPrecision(attr.Precision, attr.Scale);
    });

Python Requests library redirect new url

This is answering a slightly different question, but since I got stuck on this myself, I hope it might be useful for someone else.

If you want to use allow_redirects=False and get directly to the first redirect object, rather than following a chain of them, and you just want to get the redirect location directly out of the 302 response object, then r.url won't work. Instead, it's the "Location" header:

r = requests.get('http://github.com/', allow_redirects=False)
r.status_code  # 302
r.url  # http://github.com, not https.
r.headers['Location']  # https://github.com/ -- the redirect destination

How do I install boto?

If you're on a mac, by far the simplest way to install is to use easy_install

sudo easy_install boto3

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

Add the following dependency. The scope should be compile then it will work.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>compile</scope> 
</dependency>

Read a file line by line assigning the value to a variable

Use:

filename=$1
IFS=$'\n'
for next in `cat $filename`; do
    echo "$next read from $filename" 
done
exit 0

If you have set IFS differently you will get odd results.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.

The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.

If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).

If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).

Propagate all arguments in a bash shell script

Use "$@" instead of plain $@ if you actually wish your parameters to be passed the same.

Observe:

$ cat no_quotes.sh
#!/bin/bash
echo_args.sh $@

$ cat quotes.sh
#!/bin/bash
echo_args.sh "$@"

$ cat echo_args.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4

$ ./no_quotes.sh first second
Received: first
Received: second
Received:
Received:

$ ./no_quotes.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:

$ ./quotes.sh first second
Received: first
Received: second
Received:
Received:

$ ./quotes.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

installing vmware tools: location of GCC binary?

Entering: /usr/bin/gcc worked for me.

How do I do an OR filter in a Django query?

You want to make filter dynamic then you have to use Lambda like

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]) is equivalent to

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

PHPmailer sending HTML CODE

all you need to do is just add $mail->IsHTML(true); to the code it works fine..

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

pixels = np.array(pixels) in this line you reassign pixels. So, it may not a list anyhow. Though pixels is not a list it has no attributes append. Does it make sense?

How do I create a batch file timer to execute / call another batch throughout the day

I would use the scheduler (control panel) rather than a cmd line or other application.

Control Panel -> Scheduled tasks

How can I get the external SD card path for Android 4.0+?

I was using Dmitriy Lozenko's solution until i checked on an Asus Zenfone2, Marshmallow 6.0.1 and the solution is not working. The solution failed when getting EMULATED_STORAGE_TARGET, specifically for microSD path, i.e: /storage/F99C-10F4/. I edited the code to get the emulated root paths directly from emulated application paths with context.getExternalFilesDirs(null); and add more known phone-model-specific physical paths.

To make our life easier, I made a library here. You can use it via gradle, maven, sbt, and leiningen build system.

If you like the old-fashioned way, you can also copy paste the file directly from here, but you will not know if there is an update in the future without checking it manually.

If you have any question or suggestion, please let me know

Read next word in java

You already get the next line in this line of your code:

 String line = sc.nextLine();  

To get the words of a line, I would recommend to use:

String[] words = line.split(" ");

JavaScript unit test tools for TDD

You might also be interested in the unit testing framework that is part of qooxdoo, an open source RIA framework similar to Dojo, ExtJS, etc. but with quite a comprehensive tool chain.

Try the online version of the testrunner. Hint: hit the gray arrow at the top left (should be made more obvious). It's a "play" button that runs the selected tests.

To find out more about the JS classes that let you define your unit tests, see the online API viewer.

For automated UI testing (based on Selenium RC), check out the Simulator project.

Integrity constraint violation: 1452 Cannot add or update a child row:

that means that the value for column project_id on table comments you are inserting not only doesn't exist on table projects BUT also project_id probably doesn't have default value. E.g. in my case I set it as NULL.

As for Laravel you can consider this expressions as a chunk of code of a migration php file, for example:

class ForeinToPhotosFromUsers extends Migration

{ /** * Run the migrations. * * @return void */

public function up()
{
    Schema::table('users', function (Blueprint $table) {
    $table->unsignedBigInteger('photo_id')->nullable();// ! ! ! THIS STRING ! ! !
    $table->foreign('photo_id')->references('id')->on('photos');
});
}

}

Obviously you had to create the Model class(in my case it was Photo) next to all these.

Close Current Tab

Try this:

<script>
    var myWindow = window.open("ANYURL", "MyWindowName", "width=700,height=700");
    this.window.close();
</script>

This worked for me in some cases in Google Chrome 50. It does not seem to work when put inside a javascript function, though.

How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

https://github.com/leoselig/jsFancyScroll/

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

Windows Batch Files: if else

An alternative would be to set a variable, and check whether it is defined:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1 directly with DEFINED doesn't work.

Laravel 5.4 create model, controller and migration in single artisan command

Updated

Laravel 6 Through the model

To Generate a migration, seeder, factory, and resource controller for the model

php artisan make:model Todo -a

Or

php artisan make:model Todo -all

Other Options

-c, --controller Create a new controller for the model

-f, --factory Create a new factory for the model

--force Create the class even if the model already exists

-m, --migration Create a new migration file for the model

-s, --seed Create a new seeder file for the model

-p, --pivot Indicates if the generated model should be a custom inte rmediate table model

-r, --resource Indicates if the generated controller should be a resour ce controller

For More Help

php artisan make:model Todo -help

Hope Newbies will get help.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

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

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I have seen reports of people having and additional, self terminating node in the machine.config file. Removing it resolved their issue. machine.config is found in \Windows\Microsoft.net\Framework\vXXXX\Config. You could have a multitude of config files based on how many versions of the framework are installed, including 32 and 64 bit variants.

<system.data>
    <DbProviderFactories>
        <add name="Odbc Data Provider" invariant="System.Data.Odbc" ... />
        <add name="OleDb Data Provider" invariant="System.Data.OleDb" ... />
        <add name="OracleClient Data Provider" invariant="System.Data ... />
        <add name="SqlClient Data Provider" invariant="System.Data ... />
        <add name="IBM DB2 for i .NET Provider" invariant="IBM.Data ... />
        <add name="Microsoft SQL Server Compact Data Provider" ... />     
    </DbProviderFactories>

    <DbProviderFactories/>  //remove this one!
</system.data>

Produce a random number in a range using C#

Here is updated version from Darrelk answer. It is implemented using C# extension methods. It does not allocate memory (new Random()) every time this method is called.

public static class RandomExtensionMethods
{
    public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber)
    {
        return random.NextDouble() * (maxNumber - minNumber) + minNumber;
    }
}

Usage (make sure to import the namespace that contain the RandomExtensionMethods class):

var random = new System.Random();
double rx = random.NextDoubleRange(0.0, 1.0);
double ry = random.NextDoubleRange(0.0f, 1.0f);
double vx = random.NextDoubleRange(-0.005f, 0.005f);
double vy = random.NextDoubleRange(-0.005f, 0.005f);

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

What are valid values for the id attribute in HTML?

Strictly it should match

[A-Za-z][-A-Za-z0-9_:.]*

But jquery seems to have problems with colons so it might be better to avoid them.

Python | change text color in shell

This is so simple to do on a PC: Windows OS: Send the os a command to change the text: import os

os.system('color a') #green text
print 'I like green' 
raw_input('do you?')

SQL Server Group By Month

Restrict the dimension of the NVARCHAR to 7, supplied to CONVERT to show only "YYYY-MM"

SELECT CONVERT(NVARCHAR(7),PaymentDate,120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(7),PaymentDate,120)
ORDER BY [Month]

YYYY-MM-DD format date in shell script

In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).

As such:

# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1 

# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1 

# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal

In bash (<4.2):

# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')

# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')

# print current date directly
echo $(date '+%Y-%m-%d')

Other available date formats can be viewed from the date man pages (for external non-bash specific command):

man date

Get index of clicked element in collection with jQuery

Siblings

$(this).index() can be used to get the index of the clicked element if the elements are siblings.

<div id="container">
    <a href="#" class="link">1</a>
    <a href="#" class="link">2</a>
    <a href="#" class="link">3</a>
    <a href="#" class="link">4</a>
</div>

_x000D_
_x000D_
$('#container').on('click', 'a', function() {
  console.log($(this).index());
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="container">
  <a href="#" class="link">1</a>
  <a href="#" class="link">2</a>
  <a href="#" class="link">3</a>
  <a href="#" class="link">4</a>
</div>
_x000D_
_x000D_
_x000D_


Not siblings

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Pass the selector to the index(selector).

$(this).index(selector);

Example:

Find the index of the <a> element that is clicked.

<tr>
    <td><a href="#" class="adwa">0001</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0002</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0003</a></td>
</tr>
<tr>
    <td><a href="#" class="adwa">0004</a></td>
</tr>

Fiddle

_x000D_
_x000D_
$('#table').on('click', '.adwa', function() {
    console.log($(this).index(".adwa"));
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="table">
    <thead>
        <tr>
            <th>vendor id</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a href="#" class="adwa">0001</a></td>
        </tr>
        <tr>
            <td><a href="#" class="adwa">0002</a></td>
        </tr>
        <tr>
            <td><a href="#" class="adwa">0003</a></td>
        </tr>
        <tr>
            <td><a href="#" class="adwa">0004</a></td>
        </tr>
    </tbody>
</table>
_x000D_
_x000D_
_x000D_

“tag already exists in the remote" error after recreating the git tag

Edit, 24 Nov 2016: this answer is apparently popular, so I am adding a note here. If you replace a tag on a central server, anyone who has the old tag—any clone of that central-server repository that already has the tag—could retain its old tag. So while this tells you how to do it, be really sure you want to do it. You'll need to get everyone who already has the "wrong" tag to delete their "wrong tag" and replace it with the new "right tag".

Testing in Git 2.10/2.11 shows that retaining the old tag is the default behavior for clients running git fetch, and updating is the default behavior for clients running git fetch --tags.

(Original answer follows.)


When you ask to push tags, git push --tags sends (along with any commits and other objects needed and any other ref updates from the push settings) to the remote an update request of the form new-sha1 refs/tags/name. (Well, it sends however many: one of those for each tag.)

The update request is modified by the remote to add an old-sha1 (or again, one for each tag), then delivered to the pre-receive and/or update hooks (whichever hooks exist on the remote). Those hooks can decide whether to allow or reject the tag create/delete/update.

The old-sha1 value is the all-zeros "null" SHA-1 if the tag is being created. The new-sha1 is the null SHA-1 if the tag is being deleted. Otherwise both SHA-1 values are real, valid values.

Even with no hooks, there's a sort of "built-in hook" that is also run: the remote will refuse to move a tag unless you use the "force" flag (though the "built-in hook" is always OK with both "add" and "delete"). The rejection message you're seeing is coming from this built-in hook. (Incidentally, this same built-in hook also rejects branch updates that are not fast-forwards.)1

But—here's one of the keys to understanding what's going on—the git push step has no idea whether the remote has that tag now, and if so, what SHA-1 value it has. It only says "here's my complete list of tags, along with their SHA-1 values". The remote compares the values and if there are additions and/or changes, runs the hooks on those. (For tags that are the same, it does nothing at all. For tags you don't have that they do, it also does nothing!)

If you delete the tag locally, then push, your push simply does not transfer the tag. The remote assumes no change should be made.

If you delete the tag locally, then create it pointing to a new place, then push, your push transfers the tag, and the remote sees this as a tag-change and rejects the change, unless it's a force-push.

Thus, you have two options:

  • do a force-push, or
  • delete the tag on the remote.

The latter is possible via git push2 even though deleting the tag locally and pushing has no effect. Assuming the name of the remote is origin, and the tag you want it to delete is dev:

git push origin :refs/tags/dev

This asks the remote to delete the tag. The presence or absence of the tag dev in your local repository is irrelevant; this kind of push, with :remoteref as a refspec, is a pure-delete push.

The remote may or may not allow tag deletion (depending on any extra hooks added). If it allows the deletion, then the tag will be gone, and a second git push --tags, when you have a local dev tag pointing to some commit or annotated tag repo object, send your new dev tag. On the remote, dev will now be a newly created tag, so the remote will probably allow the push (again this depends on any extra hooks added).

The force-push is simpler. If you want to be sure not to update anything other than the tag, just tell git push to push only that one refspec:

git push --force origin refs/tags/dev:refs/tags/dev

(note: you don't need --tags if you're explicitly pushing just one tag ref-spec).


1Of course, the reason for this built-in hook is to help enforce the behavior that other users of that same remote-repo expect: that branches are not rewound, and tags do not move. If you force-push, you should let the other users know you are doing this, so that they can correct for it. Note that "tags don't move at all" is newly enforced by Git 1.8.2; previous versions would allow the tag to "move forward" in the commit graph, much like branch names. See the git 1.8.2 release notes.

2It's trivial if you can log in on the remote. Just go to the Git repository there and run git tag -d dev. Note that either way—deleting the tag on the remote, or using git push to delete it—there's a period of time when anyone who accesses the remote will find that the dev tag is missing. (They will continue to have their own old tag, if they already have it, and they might even push their old tag back up before you can push the new one.)

Program to find largest and second largest number in array

Try Out with this:

    firstMax = arr[0];

    for (int i = 0; i<n; i++) {

        if (firstMax < arr[i]  ) {
            secondMax = firstMax;
            firstMax = arr[i];
        }
    }

Lambda expression to convert array/List of String to array/List of Integers

For List :

List<Integer> intList 
 = stringList.stream().map(Integer::valueOf).collect(Collectors.toList());

For Array :

int[] intArray = Arrays.stream(stringArray).mapToInt(Integer::valueOf).toArray();

Can't subtract offset-naive and offset-aware datetimes

The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:

from datetime import datetime, timezone

now = datetime.now(timezone.utc)

On older Python versions, you could define the utc tzinfo object yourself (example from datetime docs):

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTC(tzinfo):
  def utcoffset(self, dt):
    return ZERO
  def tzname(self, dt):
    return "UTC"
  def dst(self, dt):
    return ZERO

utc = UTC()

then:

now = datetime.now(utc)

Find out time it took for a python script to complete execution

import time 

startTime = time.time()
# Your code here !
print ('The script took {0} second !'.format(time.time() - startTime))

The previous code works for me with no problem !

endforeach in loops?

It's mainly so you can make start and end statements clearer when creating HTML in loops:

<table>
<? while ($record = mysql_fetch_assoc($rs)): ?>
    <? if (!$record['deleted']): ?>
        <tr>
        <? foreach ($display_fields as $field): ?>
            <td><?= $record[$field] ?></td>
        <? endforeach; ?>
        <td>
        <select name="action" onChange="submit">
        <? foreach ($actions as $action): ?>
            <option value="<?= $action ?>"><?= $action ?>
        <? endforeach; ?>
        </td>
        </tr>
    <? else: ?>
         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
    <? endif; ?>
<? endwhile; ?>
</table>

versus

<table>
<? while ($record = mysql_fetch_assoc($rs)) { ?>
    <? if (!$record['deleted']) { ?>
        <tr>
        <? foreach ($display_fields as $field) { ?>
            <td><?= $record[$field] ?></td>
        <? } ?>
        <td>
        <select name="action" onChange="submit">
        <? foreach ($actions as $action) { ?>
            <option value="<?= $action ?>"><?= action ?>
        <? } ?>
        </td>
        </tr>
    <? } else { ?>
         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
    <? } ?>
<? } ?>
</table>

Hopefully my example is sufficient to demonstrate that once you have several layers of nested loops, and the indenting is thrown off by all the PHP open/close tags and the contained HTML (and maybe you have to indent the HTML a certain way to get your page the way you want), the alternate syntax (endforeach) form can make things easier for your brain to parse. With the normal style, the closing } can be left on their own and make it hard to tell what they're actually closing.

How to implement an STL-style iterator and avoid common pitfalls?

And now a keys iterator for range-based for loop.

template<typename C>
class keys_it
{
    typename C::const_iterator it_;
public:
    using key_type        = typename C::key_type;
    using pointer         = typename C::key_type*;
    using difference_type = std::ptrdiff_t;

    keys_it(const typename C::const_iterator & it) : it_(it) {}

    keys_it         operator++(int               ) /* postfix */ { return it_++         ; }
    keys_it&        operator++(                  ) /*  prefix */ { ++it_; return *this  ; }
    const key_type& operator* (                  ) const         { return it_->first    ; }
    const key_type& operator->(                  ) const         { return it_->first    ; }
    keys_it         operator+ (difference_type v ) const         { return it_ + v       ; }
    bool            operator==(const keys_it& rhs) const         { return it_ == rhs.it_; }
    bool            operator!=(const keys_it& rhs) const         { return it_ != rhs.it_; }
};

template<typename C>
class keys_impl
{
    const C & c;
public:
    keys_impl(const C & container) : c(container) {}
    const keys_it<C> begin() const { return keys_it<C>(std::begin(c)); }
    const keys_it<C> end  () const { return keys_it<C>(std::end  (c)); }
};

template<typename C>
keys_impl<C> keys(const C & container) { return keys_impl<C>(container); }

Usage:

std::map<std::string,int> my_map;
// fill my_map
for (const std::string & k : keys(my_map))
{
    // do things
}

That's what i was looking for. But nobody had it, it seems.

You get my OCD code alignment as a bonus.

As an exercise, write your own for values(my_map)

const vs constexpr on variables

A constexpr symbolic constant must be given a value that is known at compile time. For example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    constexpr int c2 = n+7;   // Error: we don’t know the value of c2
    // ...
}

To handle cases where the value of a “variable” that is initialized with a value that is not known at compile time but never changes after initialization, C++ offers a second form of constant (a const). For Example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    const int c2 = n+7; // OK, but don’t try to change the value of c2
    // ...
    c2 = 7; // error: c2 is a const
}

Such “const variables” are very common for two reasons:

  1. C++98 did not have constexpr, so people used const.
  2. List item “Variables” that are not constant expressions (their value is not known at compile time) but do not change values after initialization are in themselves widely useful.

Reference : "Programming: Principles and Practice Using C++" by Stroustrup

Tools for making latex tables in R

I have a few tricks and work arounds to interesting 'features' of xtable and Latex that I'll share here.

Trick #1: Removing Duplicates in Columns and Trick #2: Using Booktabs

First, load packages and define my clean function

<<label=first, include=FALSE, echo=FALSE>>= 
    library(xtable)
    library(plyr)

    cleanf <- function(x){     
        oldx <- c(FALSE, x[-1]==x[-length(x)])  
        # is the value equal to the previous?    
        res <- x
        res[oldx] <- NA
        return(res)} 

Now generate some fake data

data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
            colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
            size=rnorm(100,mean=500, sd=150),
            age=rlnorm(100, meanlog=3, sdlog=0.5))

    #generate a table
    datatable<-ddply(data, .(animal, colour), function(df) {
                return(data.frame(size=mean(df$size), age=mean(df$age)))
            })

Now we can generate a table, and use the clean function to remove duplicate entries in the label columns.

cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
@ 

this is a normal xtable

<<label=normal, results=tex, echo=FALSE>>=
print(
    xtable(
        datatable
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

this is a normal xtable where a custom function has turned duplicates to NA

<<label=cleandata, results=tex, echo=FALSE>>=
print(
    xtable(
        cleandata
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

This table uses the booktab package (and needs a \usepackage{booktabs} in the headers)

\begin{table}[!h] 
        \centering
        \caption{table using booktabs.}
        \label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>= 
            mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
            foo<-0:(length(mat$animal))
            bar<-foo[!is.na(mat$animal)]
            print(mat, 
                  sanitize.text.function = function(x){x},
                  floating=FALSE,
                  include.rownames=FALSE,
                  hline.after=NULL, 
                  add.to.row=list(pos=list(-1,bar,nrow(mat)), 
                  command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
  #could extend this with \cmidrule to have a partial line over
  #a sub category column and \addlinespace to add space before a total row
@ 

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

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

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Handling ExecuteScalar() when no results are returned

I just used this:

    int? ReadTerminalID()
    {
        int? terminalID = null;

        using (FbConnection conn = connManager.CreateFbConnection())
        {
            conn.Open();
            FbCommand fbCommand = conn.CreateCommand();
            fbCommand.CommandText = "SPSYNCGETIDTERMINAL";
            fbCommand.CommandType = CommandType.StoredProcedure;

            object result = fbCommand.ExecuteScalar(); // ExecuteScalar fails on null
            if (result.GetType() != typeof(DBNull))
            {
                terminalID = (int?)result;
            }
        }

        return terminalID;
    }

How can I define a composite primary key in SQL?

In Oracle database we can achieve like this.

CREATE TABLE Student(
  StudentID Number(38, 0) not null,
  DepartmentID Number(38, 0) not null,
  PRIMARY KEY (StudentID, DepartmentID)
);

How can I get the root domain URI in ASP.NET?

string domainName = Request.Url.Host

Table and Index size in SQL Server

--Gets the size of each index for the specified table
DECLARE @TableName sysname = N'SomeTable';

SELECT i.name AS IndexName
      ,8 * SUM(s.used_page_count) AS IndexSizeKB
FROM sys.indexes AS i
    INNER JOIN sys.dm_db_partition_stats AS s 
        ON i.[object_id] = s.[object_id] AND i.index_id = s.index_id
WHERE s.[object_id] = OBJECT_ID(@TableName, N'U')
GROUP BY i.name
ORDER BY i.name;

SELECT i.name AS IndexName
      ,8 * SUM(a.used_pages) AS IndexSizeKB
FROM sys.indexes AS i
    INNER JOIN sys.partitions AS p 
        ON i.[object_id]  = p.[object_id] AND i.index_id = p.index_id
    INNER JOIN sys.allocation_units AS a 
        ON p.partition_id = a.container_id
WHERE i.[object_id] = OBJECT_ID(@TableName, N'U')
GROUP BY i.name
ORDER BY i.name;

VBScript How can I Format Date?

For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.

Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)

Which will result in 11-22-2019 (depending on the current date)

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Django: Redirect to previous page after login

In registration/login.html (nested within templates folder) if you insert the following line, the page will render like Django's original admin login page:

{% include "admin/login.html" %}

Note: The file should contain above lines only.

Automatically run %matplotlib inline in IPython Notebook

The setting was disabled in Jupyter 5.X and higher by adding below code

pylab = Unicode('disabled', config=True,
    help=_("""
    DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
    """)
)

@observe('pylab')
def _update_pylab(self, change):
    """when --pylab is specified, display a warning and exit"""
    if change['new'] != 'warn':
        backend = ' %s' % change['new']
    else:
        backend = ''
    self.log.error(_("Support for specifying --pylab on the command line has been removed."))
    self.log.error(
        _("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
    )
    self.exit(1)

And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels and you can find kernel for your project by running below command

$ jupyter kernelspec list
Available kernels:
  python3    /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3

This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json file, I see something like below

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
 ],
 "display_name": "Python 3",
 "language": "python"
}

So you can see what command is executed to launch the kernel. So if you run the below command

$ python -m ipykernel_launcher --help
IPython: an enhanced interactive Python shell.

Subcommands
-----------

Subcommands are launched as `ipython-kernel cmd [args]`. For information on
using subcommand 'cmd', do: `ipython-kernel cmd -h`.

install
    Install the IPython kernel

Options
-------

Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.

....
--pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Pre-load matplotlib and numpy for interactive use, selecting a particular
    matplotlib backend and loop integration.
--matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Configure matplotlib for interactive use with the default matplotlib
    backend.
...    
To see all available configurables, use `--help-all`

So now if we update our kernel.json file to

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
  "--pylab",
  "inline"
 ],
 "display_name": "Python 3",
 "language": "python"
}

And if I run jupyter notebook the graphs are automatically inline

Auto Inline

Note the below approach also still works, where you create a file on below path

~/.ipython/profile_default/ipython_kernel_config.py

c = get_config()
c.IPKernelApp.matplotlib = 'inline'

But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.

So choose which approach you would like to use based on your requirement

Python urllib2, basic HTTP authentication, and tr.im

The recommended way is to use requests module:

#!/usr/bin/env python
import requests # $ python -m pip install requests
####from pip._vendor import requests # bundled with python

url = 'https://httpbin.org/hidden-basic-auth/user/passwd'
user, password = 'user', 'passwd'

r = requests.get(url, auth=(user, password)) # send auth unconditionally
r.raise_for_status() # raise an exception if the authentication fails

Here's a single source Python 2/3 compatible urllib2-based variant:

#!/usr/bin/env python
import base64
try:
    from urllib.request import Request, urlopen
except ImportError: # Python 2
    from urllib2 import Request, urlopen

credentials = '{user}:{password}'.format(**vars()).encode()
urlopen(Request(url, headers={'Authorization': # send auth unconditionally
    b'Basic ' + base64.b64encode(credentials)})).close()

Python 3.5+ introduces HTTPPasswordMgrWithPriorAuth() that allows:

..to eliminate unnecessary 401 response handling, or to unconditionally send credentials on the first request in order to communicate with servers that return a 404 response instead of a 401 if the Authorization header is not sent..

#!/usr/bin/env python3
import urllib.request as urllib2

password_manager = urllib2.HTTPPasswordMgrWithPriorAuth()
password_manager.add_password(None, url, user, password,
                              is_authenticated=True) # to handle 404 variant
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

opener.open(url).close()

It is easy to replace HTTPBasicAuthHandler() with ProxyBasicAuthHandler() if necessary in this case.

How do I add BundleConfig.cs to my project?

If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html

If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/

Change the value in app.config file dynamically

It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.

MySQL: When is Flush Privileges in MySQL really needed?

Privileges assigned through GRANT option do not need FLUSH PRIVILEGES to take effect - MySQL server will notice these changes and reload the grant tables immediately.

From MySQL documentation:

If you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE, your changes have no effect on privilege checking until you either restart the server or tell it to reload the tables. If you change the grant tables directly but forget to reload them, your changes have no effect until you restart the server. This may leave you wondering why your changes seem to make no difference!

To tell the server to reload the grant tables, perform a flush-privileges operation. This can be done by issuing a FLUSH PRIVILEGES statement or by executing a mysqladmin flush-privileges or mysqladmin reload command.

If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

javax.persistence.NoResultException: No entity found for query

Another option is to use uniqueResultOptional() method, which gives you Optional in result:

String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
Query query=em.createQuery(hql);
query.setParameter("today",new LocalDate());

Optional<DrawUnusedBalance> drawUnusedBalance=query.uniqueResultOptional();

Position Absolute + Scrolling

You need to wrap the text in a div element and include the absolutely positioned element inside of it.

<div class="container">
    <div class="inner">
        <div class="full-height"></div>
        [Your text here]
    </div>
</div>

Css:

.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }

Setting the inner div's position to relative makes the absolutely position elements inside of it base their position and height on it rather than on the .container div, which has a fixed height. Without the inner, relatively positioned div, the .full-height div will always calculate its dimensions and position based on .container.

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  border: solid 1px red;_x000D_
  height: 256px;_x000D_
  width: 256px;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
  margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  position: relative;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 128px;_x000D_
  bottom: 0;_x000D_
  height: 100%;_x000D_
  background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="full-height">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="inner">_x000D_
    <div class="full-height">_x000D_
    </div>_x000D_
_x000D_
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
    maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
    cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
    quidem._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/M5cTN/

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

Get Request and Session Parameters and Attributes from JSF pages

You can either use

<h:outputText value="#{param['id']}" /> or

<h:outputText value="#{request.getParameter('id')}" />

However if you want to pass the parameters to your backing beans, using f:viewParam is probably what you want. "A view parameter is a mapping between a query string parameter and a model value."

<f:viewParam name="id" value="#{blog.entryId}"/>

This will set the id param of the GET parameter to the blog bean's entryId field. See http://java.dzone.com/articles/bookmarkability-jsf-2 for the details.

Link to Flask static files with url_for

In my case I had special instruction into nginx configuration file:

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

All clients have received '404' because nginx nothing known about Flask.

I hope it help someone.

Pointer to 2D arrays in C

Ok, this is actually four different question. I'll address them one by one:

are both equals for the compiler? (speed, perf...)

Yes. The pointer dereferenciation and decay from type int (*)[100][280] to int (*)[280] is always a noop to your CPU. I wouldn't put it past a bad compiler to generate bogus code anyways, but a good optimizing compiler should compile both examples to the exact same code.

is one of these solutions eating more memory than the other?

As a corollary to my first answer, no.

what is the more frequently used by developers?

Definitely the variant without the extra (*pointer) dereferenciation. For C programmers it is second nature to assume that any pointer may actually be a pointer to the first element of an array.

what is the best way, the 1st or the 2nd?

That depends on what you optimize for:

  • Idiomatic code uses variant 1. The declaration is missing the outer dimension, but all uses are exactly as a C programmer expects them to be.

  • If you want to make it explicit that you are pointing to an array, you can use variant 2. However, many seasoned C programmers will think that there's a third dimension hidden behind the innermost *. Having no array dimension there will feel weird to most programmers.

Create a mocked list by mockito

When dealing with mocking lists and iterating them, I always use something like:

@Spy
private List<Object> parts = new ArrayList<>();

Angular routerLink does not navigate to the corresponding component

I'm aware this question is fairly old by now, and you've most likely fixed it by now, but I'd like to post here as reference for anyone that finds this post while troubleshooting this issue is that this sort of thing won't work if your Anchor tags are in the Index.html. It needs to be in one of the components

How can I do division with variables in a Linux shell?

To get the numbers after decimal point, you can do this:-

read num1 num2
div=`echo $num1 / $num2 | bc -l`
echo $div

Stop Chrome Caching My JS Files

You can click the settings icon on top right corner ... | More Tools | Developer Tools | Network | Disable cache (while DevTools is open)

For windows, this is F12 or CTRL + SHIFT + I while on mac CMD + SHIFT + I opens up DevTools.

New path for Chrome Update Sept 2018:

Click settings icon on the top right corner ... | Settings | Preferences | Developer Tools | Network | Disable cache (while DevTools is open)

Getting multiple selected checkbox values in a string in javascript and PHP

var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++) 
{
    if (checkboxes[i].checked) 
    {
        vals += ","+checkboxes[i].value;
    }
}
if (vals) vals = vals.substring(1);

phpMyAdmin - config.inc.php configuration?

Do Ctrl+alt+t and then:

  1. sudo chmod 777 /opt/lampp/phpmyadmin/config.inc.php

  2. open config.inc.php

  3. test

    1. change config to cookie
      $cfg['Servers'][$i]['auth_type'] = 'config';
    2. donot change this
      $cfg['Servers'][$i]['user'] = 'root';
    3. change '' to 'root'
      $cfg['Servers'][$i]['password'] = '';
  4. save config.inc.php

  5. sudo chmod 644 /opt/lampp/phpmyadmin/config.inc.php

  6. restart the xampp and check phpmyadmin

If it works i think i am glad to help you!!!

How do I add a new sourceset to Gradle?

If you're using

To get IntelliJ to recognize custom sourceset as test sources root:

plugin {
    idea
}

idea {
    module {
        testSourceDirs = testSourceDirs + sourceSets["intTest"].allJava.srcDirs
        testResourceDirs = testResourceDirs + sourceSets["intTest"].resources.srcDirs
    }
}

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

let me as a thank you to the StackOverflow community, share something nice with you, where I have used the above example in Android code for HTTP calls, which now turns MODAL instead of the usual extra thread and the complexities of merging the threads by use of the a bit peculiar threading. (This is working in our app right now - 15 Oct 2020)

public JSONArray genericHttpModal(Context context, final String url, final JSONObject request) {

    this.url = url;    
    genericHttpRequestQueue = Volley.newRequestQueue(context);      
    class MyJsonReturn {
        JSONArray returnJsonArray;

        public void set(JSONArray i) {
            returnJsonArray = i;
        }

        public void set(String i) {
            try {
                returnJsonArray.put(0, i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        public JSONArray get() {
            return returnJsonArray;
        }
    }

    final MyJsonReturn mymy = new MyJsonReturn();

    // Positive Response / HTTP OK.
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            throw new RuntimeException();
        }
    };

    final Response.Listener responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                mymy.set(new JSONArray(response));
            } catch (JSONException e) {
                mymy.set("[{\"JSONException:\"" + e.getMessage() + "\"}]");
            }
            handler.sendMessage(handler.obtainMessage());
        }
    };

    // Negative Response / HTTP NOT OK
    final Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            result = "fail";

            try {
                mymy.set(new JSONArray("[{\"JSONException:\"" + result + "\"}]"));
            } catch (JSONException e) {
                mymy.set("[{\"JSONException:\"" + e.getMessage() + "\"}]");
            }
            handler.sendMessage(handler.obtainMessage());
        }
    };


    final StringRequest httpRequest = new StringRequest(Request.Method.POST, URL_POINTER + url,
            responseListener,
            errorListener) {

        // Here the mRequestQueue handler will get the parameters for this request here.
        // Ref: https://stackoverflow.com/questions/33573803/how-to-send-a-post-request-using-volley-with-string-body#33578202
        // Ref: Multi Threaded solution 14 Oct 2020 (David Svarrer) : https://stackoverflow.com/questions/2028697/dialogs-alertdialogs-how-to-block-execution-while-dialog-is-up-net-style (This stackoverflow here)
        @Override
        protected java.util.Map<String, String> getParams() throws AuthFailureError {
            return jsonObjectToMap(request);
        }
    };
    httpRequest.setShouldCache(false); // Elijah: Could work on dropping the cache !!!
    genericHttpRequestQueue.add(httpRequest);    

    try {
        Looper.loop();
    } catch (RuntimeException re) {
    }
    return mymy.get();
}

Android: how to parse URL String with spaces to URI object?

java.net.URLEncoder.encode(finalPartOfString, "utf-8");

This will URL-encode the string.

finalPartOfString is the part after the last slash - in your case, the name of the song, as it seems.

HTML anchor link - href and onclick both?

Just return true instead?

The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.

VBA check if file exists

For checking existence one can also use (works for both, files and folders):

Not Dir(DirFile, vbDirectory) = vbNullString

The result is True if a file or a directory exists.

Example:

If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then
    MsgBox "exists"
Else
    MsgBox "does not exist"
End If

How do I convert strings in a Pandas data frame to a 'date' data type?

If you want to get the DATE and not DATETIME format:

df["id_date"] = pd.to_datetime(df["id_date"]).dt.date

Should I use string.isEmpty() or "".equals(string)?

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

How do we download a blob url video

The process can differ depending on where and how the video is being hosted. Knowing that can help to answer the question in more detail.

As an example; this is how you can download videos with blob links on Vimeo.

  1. View the source code of the video player iframe
  2. Search for mp4
  3. Copy link with token query
  4. Download before token expires

Source & step-by-step instructions here.

enter image description here

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

If username or password has the @ character, then use it like this:

mongoose
    .connect(
        'DB_url',
        { user: '@dmin', pass: 'p@ssword', useNewUrlParser: true }
    )
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.log('Could not connect to MongoDB', err));

Calling Oracle stored procedure from C#?

In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:

using System.Data.OracleClient;

There are some system requirements here that you should verify are OK in your scenario.

Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.

Chrome doesn't delete session cookies

Have you tried to Remove hangouts extension in Google Chrome? because it forces chrome to keep running even you close all the windows.

I was also facing the problem but it resolved now.

Get name of object or class

As this was already answered, I just wanted to point out the differences in approaches on getting the constructor of an object in JavaScript. There is a difference between the constructor and the actual object/class name. If the following adds to the complexity of your decision then maybe you're looking for instanceof. Or maybe you should ask yourself "Why am I doing this? Is this really what I am trying to solve?"

Notes:

The obj.constructor.name is not available on older browsers. Matching (\w+) should satisfy ES6 style classes.

Code:

var what = function(obj) {
  return obj.toString().match(/ (\w+)/)[1];
};

var p;

// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// ES6 class.
class NPC { 
  constructor() {
  }
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// ES6 class extended
class Boss extends NPC {
  constructor() {
    super();
  }
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

Result:

enter image description here

Code: https://jsbin.com/wikiji/edit?js,console

Set height 100% on absolute div

http://jsbin.com/ubalax/1/edit .You can see the results here

body {
    position: relative;
    float: left;
    height: 3000px;
    width: 100%;
}
body div {
    position: absolute;
    height: 100%;
    width: 100%;
    top:0;
    left:0;
    background-color: yellow;
}

grid controls for ASP.NET MVC?

If it's just for viewing data, I use simple foreach or even aspRepeater. For editing I build specialized views and actions. Didn't like webforms GridView inline edit capabilities anyway, this is kinda much clearer and better - one view for viewing and another for edit/new.

MySQL - sum column value(s) based on row from the same table

I think you're making this a bit more complicated than it needs to be.

SELECT
    ProductID,
    SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
    -- snip
    SUM(Amount) AS Total
FROM
    Payments
WHERE
    SaleDate = '2012-02-10'
GROUP BY
    ProductID

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

tsql returning a table from a function or store procedure

Use this as a template

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE FUNCTION <Table_Function_Name, sysname, FunctionName> 
(
    -- Add the parameters for the function here
    <@param1, sysname, @p1> <data_type_for_param1, , int>, 
    <@param2, sysname, @p2> <data_type_for_param2, , char>
)
RETURNS 
<@Table_Variable_Name, sysname, @Table_Var> TABLE 
(
    -- Add the column definitions for the TABLE variable here
    <Column_1, sysname, c1> <Data_Type_For_Column1, , int>, 
    <Column_2, sysname, c2> <Data_Type_For_Column2, , int>
)
AS
BEGIN
    -- Fill the table variable with the rows for your result set

    RETURN 
END
GO

That will define your function. Then you would just use it as any other table:

Select * from MyFunction(Param1, Param2, etc.)

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Just enable the "Build Active Architecture Only" option

in PROJECT >> Build Settings >> Build Active Architecture Only >> Yes

screenshot of the path to the configuration

remember to check if they are also enabled in each target

Map<String, String>, how to print both the "key string" and "value string" together

Inside of your loop, you have the key, which you can use to retrieve the value from the Map:

for (String key: mss1.keySet()) {
    System.out.println(key + ": " + mss1.get(key));
}

Changing SVG image color with javascript

Here's a full example that shows how to modify the fill color of an svg referenced via <embed>, <object> and <iframe>.

Also see How to apply a style to an embedded SVG?

WordPress query single post by slug

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Your indexes probably contains duplicated values.

import pandas as pd

T1_INDEX = [
    0,
    1,  # <= !!! if I write e.g.: "0" here then it fails
    0.2,
]
T1_COLUMNS = [
    'A', 'B', 'C', 'D'
]
T1 = [
    [1.0, 1.1, 1.2, 1.3],
    [2.0, 2.1, 2.2, 2.3],
    [3.0, 3.1, 3.2, 3.3],
]

T2_INDEX = [
    1.2,
    2.11,
]

T2_COLUMNS = [
    'D', 'E', 'F',
]
T2 = [
    [54.0, 5324.1, 3234.2],
    [55.0, 14.5324, 2324.2],
    # [3.0, 3.1, 3.2],
]
df1 = pd.DataFrame(T1, columns=T1_COLUMNS, index=T1_INDEX)
df2 = pd.DataFrame(T2, columns=T2_COLUMNS, index=T2_INDEX)


print(pd.concat([pd.DataFrame({})] + [df2, df1], axis=1))

Javascript + Regex = Nothing to repeat error?

for example I faced this in express node.js when trying to create route for paths not starting with /internal

app.get(`\/(?!internal).*`, (req, res)=>{

and after long trying it just worked when passing it as a RegExp Object using new RegExp()

app.get(new RegExp("\/(?!internal).*"), (req, res)=>{

this may help if you are getting this common issue in routing

Building a fat jar using maven

An alternative is to use the maven shade plugin to build an uber-jar.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version> Your Version Here </version>
    <configuration>
            <!-- put your configurations here -->
    </configuration>
    <executions>
            <execution>
                    <phase>package</phase>
                    <goals>
                            <goal>shade</goal>
                    </goals>
            </execution>
    </executions>
</plugin>

How to get a value of an element by name instead of ID

Only one thing more: when you´re using the "crasis variable assignment" you need to use double cotes too AND you do not need to use the "input" word!:

valInput  = $(`[name="${inputNameHere}"]`).val();

How to play .mp4 video in videoview in android?

Finally it works for me.

private VideoView videoView;

videoView = (VideoView) findViewById(R.id.videoView);

Uri video = Uri.parse("http://www.servername.com/projects/projectname/videos/1361439400.mp4");
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
  @Override       
  public void onPrepared(MediaPlayer mp) {
       mp.setLooping(true);
       videoView.start();
    }
});

Hope this would help others.

Check if Internet Connection Exists with jQuery?

A much simpler solution:

<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>

and later in the code:

var online;
// check whether this function works (online only)
try {
  var x = google.maps.MapTypeId.TERRAIN;
  online = true;
} catch (e) {
  online = false;
}
console.log(online);

When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

SQL - using alias in Group By

SQL is implemented as if a query was executed in the following order:

  1. FROM clause
  2. WHERE clause
  3. GROUP BY clause
  4. HAVING clause
  5. SELECT clause
  6. ORDER BY clause

For most relational database systems, this order explains which names (columns or aliases) are valid because they must have been introduced in a previous step.

So in Oracle and SQL Server, you cannot use a term in the GROUP BY clause that you define in the SELECT clause because the GROUP BY is executed before the SELECT clause.

There are exceptions though: MySQL and Postgres seem to have additional smartness that allows it.

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

Running Jupyter via command line on Windows

I got Jupyter notebook running in Windows 10. I found the easiest way to accomplish this task without relying upon a distro like Anaconda was to use Cygwin.

In Cygwin install python2, python2-devel, python2-numpy, python2-pip, tcl, tcl-devel, (I have included a image below of all packages I installed) and any other python packages you want that are available. This is by far the easiest option.

Then run this command to just install jupyter notebook:

python -m pip install jupyter

Below is the actual commands I ran to add more libraries just in case others need this list too:

python -m pip install scipy

python -m pip install scikit-learn

python -m pip install sklearn

python -m pip install pandas

python -m pip install matplotlib

python -m pip install jupyter

If any of the above commands fail do not worry the solution is pretty simple most of the time. What you do is look at the build failure for whatever missing package / library.

Say it is showing a missing pyzmq then close Cygwin, re-open the installer, get to the package list screen, show "full" for all, then search for the name like zmq and install those libraries and re-try the above commands.

Using this approach it was fairly simple to eventually work through all the missing dependencies successfully.

Cygwin package list

Once everything is installed then run in Cygwin goto the folder you want to be the "root" for the notebook ui tree and type:

jupyter notebook

This will start up the notebook and show some output like below:

$ jupyter notebook
[I 19:05:30.459 NotebookApp] Serving notebooks from local directory: 
[I 19:05:30.459 NotebookApp] 0 active kernels
[I 19:05:30.459 NotebookApp] The Jupyter Notebook is running at: 
[I 19:05:30.459 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

Copy/paste this URL into your browser when you connect for the first time, to login with a token:

http://localhost:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

jQuery UI Slider (setting programmatically)

For me this perfectly triggers slide event on UI Slider :

hs=$('#height_slider').slider();
hs.slider('option', 'value',h);
hs.slider('option','slide')
       .call(hs,null,{ handle: $('.ui-slider-handle', hs), value: h });

Don't forget to set value by hs.slider('option', 'value',h); before the trigger. Else slider handler will not be in sync with value.

One thing to note here is that h is index/position (not value) in case you are using html select.

How to pause javascript code execution for 2 seconds

There's no (safe) way to pause execution. You can, however, do something like this using setTimeout:

function writeNext(i)
{
    document.write(i);

    if(i == 5)
        return;

    setTimeout(function()
    {
        writeNext(i + 1);

    }, 2000);
}

writeNext(1);

Is null check needed before calling instanceof?

Using a null reference as the first operand to instanceof returns false.

Debugging with Android Studio stuck at "Waiting For Debugger" forever

Restarting Testing device fix the issue for me.

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

In bootstrap 3, this works well for me:

.btn-link.btn-anchor {
    outline: none !important;
    padding: 0;
    border: 0;
    vertical-align: baseline;
}

Used like:

<button type="button" class="btn-link btn-anchor">My Button</button>

Demo

HTML5 Canvas: Zooming

IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.

Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.

where is gacutil.exe?

  1. Open Developer Command prompt.
  2. type

where gacutil

Where does Android emulator store SQLite database?

In Android Studio 3.4.1, you can use the search feature of Android Studio to find "Device File Explorer" and then go to the /data/data/package_name/database directory of your emulator.

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How do I connect to a specific Wi-Fi network in Android programmatically?

The earlier answer works, but the solution can actually be simpler. Looping through the configured networks list is not required as you get the network id when you add the network through the WifiManager.

So the complete, simplified solution would look something like this:

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);

WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

Text in a flex container doesn't wrap in IE11

I did not find my solution here, maybe someone will be useful:

.child-with-overflowed-text{
  word-wrap: break-all;
}

Good luck!

How can I change the color of my prompt in zsh (different from normal text)?

Put this in ~/.zshrc:

autoload -U colors && colors
PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%~ %{$reset_color%}%% "

Supported Colors:
red, blue, green, cyan, yellow, magenta, black, & white (from this answer) although different computers may have different valid options.

Surround color codes (and any other non-printable chars) with %{....%}. This is for the text wrapping to work correctly.

Additionally, here is how you can get this to work with the directory-trimming from here.

PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%(5~|%-1~/.../%3~|%4~) %{$reset_color%}%% "

How does Python manage int and long?

Just to continue to all the answers that were given here, especially @James Lanes

the size of the integer type can be expressed by this formula:

total range = (2 ^ bit system)

lower limit = -(2 ^ bit system)*0.5 upper limit = ((2 ^ bit system)*0.5) - 1

Convert hex string to int in Python

with '0x' prefix, you might also use eval function

For example

>>a='0xff'
>>eval(a)
255

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric

geom_segment(data=tmpp, 
   aes(x=start_pos, 
   y=lib.complexity, 
   xend=end_pos, 
   yend=lib.complexity)
)
# to 
geom_segment(data=tmpp, 
   aes(x=as.numeric(start_pos), 
   y=as.numeric(lib.complexity), 
   xend=as.numeric(end_pos), 
   yend=as.numeric(lib.complexity))
)

How to take last four characters from a varchar?

You can select last characters with -

WHERE SUBSTR('Hello world', -4)

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

calling javascript function on OnClientClick event of a Submit button

OnClientClick="SomeMethod()" event of that BUTTON, it return by default "true" so after that function it do postback

for solution use

//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"

//and your function like this
<script type="text/javascript">
  function SomeMethod(){
    // put your code here 
    return false;
  }
</script>

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

For those, who wonder how it goes in VS.

MSVC 2015 Update 1, cl.exe version 19.00.24215.1:

#include <iostream>

template<typename X, typename Y>
struct A
{
  template<typename Z>
  static void f()
  {
    std::cout << "from A::f():" << std::endl
      << __FUNCTION__ << std::endl
      << __func__ << std::endl
      << __FUNCSIG__ << std::endl;
  }
};

void main()
{
  std::cout << "from main():" << std::endl
    << __FUNCTION__ << std::endl
    << __func__ << std::endl
    << __FUNCSIG__ << std::endl << std::endl;

  A<int, float>::f<bool>();
}

output:

from main():
main
main
int __cdecl main(void)

from A::f():
A<int,float>::f
f
void __cdecl A<int,float>::f<bool>(void)

Using of __PRETTY_FUNCTION__ triggers undeclared identifier error, as expected.

Algorithm to randomly generate an aesthetically-pleasing color palette

I would use a color wheel and given a random position you could add the golden angle (137,5 degrees)

http://en.wikipedia.org/wiki/Golden_angle

in order to get different colours each time that do not overlap.

Adjusting the brightness for the color wheel you could get also different bright/dark color combinations.

I've found this blog post that explains really well the problem and the solution using the golden ratio.

http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

UPDATE: I've just found this other approach:

It's called RYB(red, yellow, blue) method and it's described in this paper:

http://threekings.tk/mirror/ryb_TR.pdf

as "Paint Inspired Color Compositing".

The algorithm generates the colors and each new color is chosen to maximize its euclidian distance to the previously selected ones.

Here you can find a a good implementation in javascript:

http://afriggeri.github.com/RYB/

UPDATE 2:

The Sciences Po Medialb have just released a tool called "I want Hue" that generate color palettes for data scientists. Using different color spaces and generating the palettes by using k-means clustering or force vectors ( repulsion graphs) The results from those methods are very good, they show the theory and an implementation in their web page.

http://tools.medialab.sciences-po.fr/iwanthue/index.php

Java - remove last known item from ArrayList

First error: You're casting a ClientThread as a String for some reason.

Second error: You're not calling remove on your List.

Is is homework? If so, you might want to use the tag.

Remove last character of a StringBuilder?

if(sb.length() > 0){
    sb.deleteCharAt(sb.length() - 1);
}

Extracting substrings in Go

It looks like you're confused by the working of slices and the string storage format, which is different from what you have in C.

  • any slice in Go stores the length (in bytes), so you don't have to care about the cost of the len operation : there is no need to count
  • Go strings aren't null terminated, so you don't have to remove a null byte, and you don't have to add 1 after slicing by adding an empty string.

To remove the last char (if it's a one byte char), simply do

inputFmt:=input[:len(input)-1]

How to update Xcode from command line

I got this error after deleting Xcode. I fixed it by resetting the command line tools path with sudo xcode-select -r.

Before:

navin@Radiant ~$ /usr/bin/clang
xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
Use `sudo xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools, or use `xcode-select --install` to install the standalone command line developer tools.
See `man xcode-select` for more details.

navin@Radiant ~$ xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates

After:

navin@Radiant ~$ /usr/bin/clang
clang: error: no input files

How to set a text box for inputing password in winforms?

To set a text box for password input:

textBox1.PasswordChar = '*';

you can also change this property in design time by editing properties of the text box.

To show if "Capslock is ON":

using System;  
using System.Windows.Forms;  
//...
if (Control.IsKeyLocked(Keys.CapsLock)) {  
    MessageBox.Show("The Caps Lock key is ON.");  
}  

How to select all the columns of a table except one column?

This is not a generic solution, but some databases allow you to use regular expressions to specify the columns.

For instance, in the case of Hive, the following query selects all columns except ds and hr:

SELECT `(ds|hr)?+.+` FROM sales

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select#LanguageManualSelect-REGEXColumnSpecification

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

if you want to use "System.Data.Objects.EntityFunctions"

use "System.Data.Entity.DbFunctions" in EF 6.1+

How to get Django and ReactJS to work together?

The first approach is building separate Django and React apps. Django will be responsible for serving the API built using Django REST framework and React will consume these APIs using the Axios client or the browser's fetch API. You'll need to have two servers, both in development and production, one for Django(REST API) and the other for React (to serve static files).

The second approach is different the frontend and backend apps will be coupled. Basically you'll use Django to both serve the React frontend and to expose the REST API. So you'll need to integrate React and Webpack with Django, these are the steps that you can follow to do that

First generate your Django project then inside this project directory generate your React application using the React CLI

For Django project install django-webpack-loader with pip:

pip install django-webpack-loader

Next add the app to installed apps and configure it in settings.py by adding the following object

WEBPACK_LOADER = {
    'DEFAULT': {
            'BUNDLE_DIR_NAME': '',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
}

Then add a Django template that will be used to mount the React application and will be served by Django

{ % load render_bundle from webpack_loader % }

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Django + React </title>
  </head>
  <body>
    <div id="root">
     This is where React will be mounted
    </div>
    { % render_bundle 'main' % }
  </body>
</html>

Then add an URL in urls.py to serve this template

from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [

    url(r'^', TemplateView.as_view(template_name="main.html")),

]

If you start both the Django and React servers at this point you'll get a Django error saying the webpack-stats.json doesn't exist. So next you need to make your React application able to generate the stats file.

Go ahead and navigate inside your React app then install webpack-bundle-tracker

npm install webpack-bundle-tracker --save

Then eject your Webpack configuration and go to config/webpack.config.dev.js then add

var BundleTracker  = require('webpack-bundle-tracker');
//...

module.exports = {

    plugins: [
          new BundleTracker({path: "../", filename: 'webpack-stats.json'}),
    ]
}

This add BundleTracker plugin to Webpack and instruct it to generate webpack-stats.json in the parent folder.

Make sure also to do the same in config/webpack.config.prod.js for production.

Now if you re-run your React server the webpack-stats.json will be generated and Django will be able to consume it to find information about the Webpack bundles generated by React dev server.

There are some other things to. You can find more information from this tutorial.

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

Vue equivalent of setTimeout?

It is likely a scope issue. Try the following instead:

addToBasket: function(){
    item = this.photo;
    this.$http.post('/api/buy/addToBasket', item);
    this.basketAddSuccess = true;
    var self = this;
    setTimeout(function(){
        self.basketAddSuccess = false;
    }, 2000);
}

Regular expression for decimal number

As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.

double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))

Not relevant to the original question asked but confirming that TryParse() indeed is a good option.

List all indexes on ElasticSearch server?

You can also get specific index using

curl -X GET "localhost:9200/<INDEX_NAME>"
e.g.   curl -X GET "localhost:9200/twitter"
You may get output like:
{
  "twitter": {
     "aliases": { 

     },
     "mappings": { 

     },
     "settings": {
     "index": {
        "creation_date": "1540797250479",
        "number_of_shards": "3",
        "number_of_replicas": "2",
        "uuid": "CHYecky8Q-ijsoJbpXP95w",
        "version": {
            "created": "6040299"
        },
       "provided_name": "twitter"
      }
    }
  }
}

For more info

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-index.html

Download a file by jQuery.Ajax

I have created little function as workaround solution (inspired by @JohnCulviner plugin):

// creates iframe and form in it with hidden field,
// then submit form with provided data
// url - form url
// data - data to form field
// input_name - form hidden input name

function ajax_download(url, data, input_name) {
    var $iframe,
        iframe_doc,
        iframe_html;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"
                   ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" +
                  "<input type=hidden name='" + input_name + "' value='" +
                  JSON.stringify(data) +"'/></form>" +
                  "</body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

Demo with click event:

$('#someid').on('click', function() {
    ajax_download('/download.action', {'para1': 1, 'para2': 2}, 'dataname');
});

Convert data.frame columns from factors to characters

Or you can try transform:

newbob <- transform(bob, phenotype = as.character(phenotype))

Just be sure to put every factor you'd like to convert to character.

Or you can do something like this and kill all the pests with one blow:

newbob_char <- as.data.frame(lapply(bob[sapply(bob, is.factor)], as.character), stringsAsFactors = FALSE)
newbob_rest <- bob[!(sapply(bob, is.factor))]
newbob <- cbind(newbob_char, newbob_rest)

It's not good idea to shove the data in code like this, I could do the sapply part separately (actually, it's much easier to do it like that), but you get the point... I haven't checked the code, 'cause I'm not at home, so I hope it works! =)

This approach, however, has a downside... you must reorganize columns afterwards, while with transform you can do whatever you like, but at cost of "pedestrian-style-code-writting"...

So there... =)

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

MySQL - Get row number on select

Swamibebop's solution works, but by taking advantage of table.* syntax, we can avoid repeating the column names of the inner select and get a simpler/shorter result:

SELECT @r := @r+1 , 
       z.* 
FROM(/* your original select statement goes in here */)z, 
(SELECT @r:=0)y;

So that will give you:

SELECT @r := @r+1 , 
       z.* 
FROM(
     SELECT itemID, 
     count(*) AS ordercount
     FROM orders
     GROUP BY itemID
     ORDER BY ordercount DESC
    )z,
    (SELECT @r:=0)y;

wp_nav_menu change sub-menu class name?

To change the default "sub-menu" class name, there is simple way. You can just change it in wordpress file.

location : www/project_name/wp-includes/nav-menu-template.php.

open this file and at line number 49, change the name of sub-menu class with your custom class.

Or you can also add your custom class next to sub-menu.

Done.

It worked for me.I used wordpress-4.4.1.

Iframe transparent background

<style type="text/css">
body {background:none transparent;
}
</style>

that might work (if you put in the iframe) along with

<iframe src="stuff.htm" allowtransparency="true">

Loop through properties in JavaScript object with Lodash

For your stated desire to "check if a property exists" you can directly use Lo-Dash's has.

var exists = _.has(myObject, propertyNameToCheck);

Append an int to a std::string

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

Selected value for JSP drop down using JSTL

I tried the accepted answer, it did not work.

However the simple way to do it is below:-

<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>

Enjoy!!

Python List vs. Array - when to use?

For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see docs), with access to more C-like types such as signed/unsigned short or double, which are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.

How to wrap text in LaTeX tables?

To change the text AB into A \r B in a table cell, put this into the cell position: \makecell{A \\ B}.

Before doing that, you also need to include package makecell.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

How to replace a string in multiple files in linux command line

To replace a string in multiple files you can use:

grep -rl string1 somedir/ | xargs sed -i 's/string1/string2/g'

E.g.

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

Source blog

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);

Of course, one can make unixEpoch a global static, so it only needs to appear once in your project, and one can use AddSeconds if the UNIX time is in seconds.

To go the other way:

double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;

Truncate to Int64 and/or use TotalSeconds as needed.

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

In order to use a CLR 2.0 mixed mode assembly, you need to modify your App.Config file to include:

<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

The key is the useLegacyV2RuntimeActivationPolicy flag. This causes the CLR to use the latest version (4.0) to load your mixed mode assembly. Without this, it will not work.

Note that this only matters for mixed mode (C++/CLI) assemblies. You can load all managed CLR 2 assemblies without specifying this in app.config.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

An alternative to the custom filter is to create an extension method to serialize any object to JSON.

public static class ObjectExtensions
{
    /// <summary>Serializes the object to a JSON string.</summary>
    /// <returns>A JSON string representation of the object.</returns>
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new List<JsonConverter> { new StringEnumConverter() }
        };

        return JsonConvert.SerializeObject(value, settings);
    }
}

Then call it when returning from the controller action.

return Content(person.ToJson(), "application/json");

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

Get the filename of a fileupload in a document through JavaScript

To get only uploaded file Name use this,

fake_path=document.getElementById('FileUpload1').value
alert(fake_path.split("\\").pop())

FileUpload1 value contains fake path, that you probably don't want, to avoid that use split and pop last element from your file.

Jquery Hide table rows

This should do the trick.

$(textInput).closest("tr").hide();

How do I make a JSON object with multiple arrays?

On the outermost level, a JSON object starts with a { and end with a }.

Sample data:

{
    "cars": {
        "Nissan": [
            {"model":"Sentra", "doors":4},
            {"model":"Maxima", "doors":4},
            {"model":"Skyline", "doors":2}
        ],
        "Ford": [
            {"model":"Taurus", "doors":4},
            {"model":"Escort", "doors":4}
        ]
    }
}

If the JSON is assigned to a variable called data, then accessing it would be like the following:

data.cars['Nissan'][0].model   // Sentra
data.cars['Nissan'][1].model   // Maxima
data.cars['Nissan'][2].doors   // 2

for (var make in data.cars) {
    for (var i = 0; i < data.cars[make].length; i++) {
        var model = data.cars[make][i].model;
        var doors = data.cars[make][i].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Another approach (using an associative array for car models rather than an indexed array):

{
    "cars": {
        "Nissan": {
            "Sentra": {"doors":4, "transmission":"automatic"},
            "Maxima": {"doors":4, "transmission":"automatic"}
        },
        "Ford": {
            "Taurus": {"doors":4, "transmission":"automatic"},
            "Escort": {"doors":4, "transmission":"automatic"}
        }
    }
}

data.cars['Nissan']['Sentra'].doors   // 4
data.cars['Nissan']['Maxima'].doors   // 4
data.cars['Nissan']['Maxima'].transmission   // automatic

for (var make in data.cars) {
    for (var model in data.cars[make]) {
        var doors = data.cars[make][model].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Edit:

Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].

Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.

See:

Hide strange unwanted Xcode logs

This is still not fixed in Xcode Version 8.0 beta 2 (8S162m) for me and extra logs are also appearing in the Xcode console

** EDIT 8/1/16: This has been acknowledged in the release notes for Xcode 8 Beta 4 (8S188o) as an issues still persisting.

Known Issues in Xcode 8 beta 4 – IDE

Debugging

• Xcode Debug Console shows extra logging from system frameworks when debugging applications in the Simulator. (27331147, 26652255)

Presumably this will be resolved by the GM release. Until then patience and although not ideal but a workaround I'm using is below...

Similar to the previous answer I am having to:

  • prefix my print logs with some kind of special character (eg * or ^ or ! etc etc)

  • Then use the search box on the bottom right of the console pane to filter my console logs by inputing my chosen special character to get the console to display my print logs as intended

console

SQL Query to search schema of all tables

I would query the information_schema - this has views that are much more readable than the underlying tables.

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%create%'

How to find the .NET framework version of a Visual Studio project?

It's as easy as in your Visual studio.

  1. go to the 4th menu option on top, 'website'.
  2. under websites go to option, 'start options'.
  3. under start options, go to 'build' option.
  4. change the target framework there to what so ever framework.

What should every programmer know about security?

Rule #1 of security for programmers: Don't roll your own

Unless you are yourself a security expert and/or cryptographer, always use a well-designed, well-tested, and mature security platform, framework, or library to do the work for you. These things have spent years being thought out, patched, updated, and examined by experts and hackers alike. You want to gain those advantages, not dismiss them by trying to reinvent the wheel.

Now, that's not to say you don't need to learn anything about security. You certainly need to know enough to understand what you're doing and make sure you're using the tools correctly. However, if you ever find yourself about to start writing your own cryptography algorithm, authentication system, input sanitizer, etc, stop, take a step back, and remember rule #1.

How to include an HTML page into another HTML page without frame/iframe?

You could use HTML5 for this:

<link rel="import" href="/path/to/file.html">

Update – July 2020: This feature is no longer supported by most major browsers, and generally considered obsolete. See caniuse for the list of browsers which do still support it.

Dart SDK is not configured

Just go to File > Settings > Languages & Frameworks > Dart

Click on check box Enable Dart Support for project 'projectName' Paste the Dart SDK path.

This is how you get Dart SDK path, follow the given steps copy the Dart SDK Path, which is in Flutter SDK, Go to location where your Flutter SDK Situated, then,

Flutter/bin/cache/dart-sdk , till dart-sdk, copy the path and paste it.

How to run a script as root on Mac OS X?

sudo ./scriptname

sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.

Java ElasticSearch None of the configured nodes are available

I know I'm a bit late, incase the above answers didn't work, I recommend checking the logs in elasticsearch terminal. I found out that the error message says that i need to update my version from 5.0.0-rc1 to 6.8.0, i resolved it by updating my maven dependencies to:

<dependency>
  <groupId>org.elasticsearch</groupId>
  <artifactId>elasticsearch</artifactId>
  <version>6.8.0</version>
</dependency>
  <dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>transport</artifactId>
  <version>6.8.0</version>
</dependency>

This changes my code as well, since InetSocketTransportAddress is deprecated. I have to change it to TransportAddress

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
               .addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));

And you also need to add this to your config/elasticsearch.yml file (use your host address)

transport.host: localhost

What is Model in ModelAndView from Spring MVC?

The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.

Example 1

If you have...

return new ModelAndView("welcomePage","WelcomeMessage","Welcome!");

... then in your jsp, to display the message, you will do:-

Hello Stranger! ${WelcomeMessage} // displays Hello Stranger! Welcome!

Example 2

If you have...

MyBean bean = new MyBean();
bean.setName("Mike!");
bean.setMessage("Meow!");

return new ModelAndView("welcomePage","model",bean);

... then in your jsp, you can do:-

Hello ${model.name}! {model.message} // displays Hello Mike! Meow!

Python matplotlib multiple bars

after looking for a similar solution and not finding anything flexible enough, I decided to write my own function for it. It allows you to have as many bars per group as you wish and specify both the width of a group as well as the individual widths of the bars within the groups.

Enjoy:

from matplotlib import pyplot as plt


def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):
    """Draws a bar plot with multiple bars per data point.

    Parameters
    ----------
    ax : matplotlib.pyplot.axis
        The axis we want to draw our plot on.

    data: dictionary
        A dictionary containing the data we want to plot. Keys are the names of the
        data, the items is a list of the values.

        Example:
        data = {
            "x":[1,2,3],
            "y":[1,2,3],
            "z":[1,2,3],
        }

    colors : array-like, optional
        A list of colors which are used for the bars. If None, the colors
        will be the standard matplotlib color cyle. (default: None)

    total_width : float, optional, default: 0.8
        The width of a bar group. 0.8 means that 80% of the x-axis is covered
        by bars and 20% will be spaces between the bars.

    single_width: float, optional, default: 1
        The relative width of a single bar within a group. 1 means the bars
        will touch eachother within a group, values less than 1 will make
        these bars thinner.

    legend: bool, optional, default: True
        If this is set to true, a legend will be added to the axis.
    """

    # Check if colors where provided, otherwhise use the default color cycle
    if colors is None:
        colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

    # Number of bars per group
    n_bars = len(data)

    # The width of a single bar
    bar_width = total_width / n_bars

    # List containing handles for the drawn bars, used for the legend
    bars = []

    # Iterate over all data
    for i, (name, values) in enumerate(data.items()):
        # The offset in x direction of that bar
        x_offset = (i - n_bars / 2) * bar_width + bar_width / 2

        # Draw a bar for every value of that type
        for x, y in enumerate(values):
            bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])

        # Add a handle to the last drawn bar, which we'll need for the legend
        bars.append(bar[0])

    # Draw legend if we need
    if legend:
        ax.legend(bars, data.keys())


if __name__ == "__main__":
    # Usage example:
    data = {
        "a": [1, 2, 3, 2, 1],
        "b": [2, 3, 4, 3, 1],
        "c": [3, 2, 1, 4, 2],
        "d": [5, 9, 2, 1, 8],
        "e": [1, 3, 2, 2, 3],
        "f": [4, 3, 1, 1, 4],
    }

    fig, ax = plt.subplots()
    bar_plot(ax, data, total_width=.8, single_width=.9)
    plt.show()

Output:

enter image description here

Creating an Array from a Range in VBA

If we do it just like this:

Dim myArr as Variant
myArr = Range("A1:A10")

the new array will be with two dimensions. Which is not always somehow comfortable to work with:

enter image description here

To get away of the two dimensions, when getting a single column to array, we may use the built-in Excel function “Transpose”. With it, the data becomes in one dimension:

enter image description here

If we have the data in a row, a single transpose will not do the job. We need to use the Transpose function twice:

enter image description here

Note: As you see from the screenshots, when generated this way, arrays start with 1, not with 0. Just be a bit careful.

How to implement my very own URI scheme on Android

I strongly recommend that you not define your own scheme. This goes against the web standards for URI schemes, which attempts to rigidly control those names for good reason -- to avoid name conflicts between different entities. Once you put a link to your scheme on a web site, you have put that little name into entire the entire Internet's namespace, and should be following those standards.

If you just want to be able to have a link to your own app, I recommend you follow the approach I described here:

How to register some URL namespace (myapp://app.start/) for accessing your program by calling a URL in browser in Android OS?

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

Difference between SurfaceView and View?

The main difference is that SurfaceView can be drawn on by background theads but Views can't. SurfaceViews use more resources though so you don't want to use them unless you have to.

how to set the default value to the drop down list control?

if you know the index of the item of default value,just

lstDepartment.SelectedIndex = 1;//the second item

or if you know the value you want to set, just

lstDepartment.SelectedValue = "the value you want to set";

What is the facade design pattern?

As explained in the previous answer it provides a simple interface to the consuming client. For example: "watch ESPN" is the intended function. But it involves several steps like:

  1. Switch on TV if required;
  2. Check for satellite/cable functioning;
  3. Switch to ESPN if required.

But the facade will simplify this and just provide "watch ESPN" function to the client.

How can I access getSupportFragmentManager() in a fragment?

All you need to do is using

getFragmentManager()

method on your fragment. It will give you the support fragment manager, when you used it while adding this fragment.

Fragment Documentation

JWT authentication for ASP.NET Web API

I've managed to achieve it with minimal effort (just as simple as with ASP.NET Core).

For that I use OWIN Startup.cs file and Microsoft.Owin.Security.Jwt library.

In order for the app to hit Startup.cs we need to amend Web.config:

<configuration>
  <appSettings>
    <add key="owin:AutomaticAppStartup" value="true" />
    ...

Here's how Startup.cs should look:

using MyApp.Helpers;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;

[assembly: OwinStartup(typeof(MyApp.App_Start.Startup))]

namespace MyApp.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidAudience = ConfigHelper.GetAudience(),
                        ValidIssuer = ConfigHelper.GetIssuer(),
                        IssuerSigningKey = ConfigHelper.GetSymmetricSecurityKey(),
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true
                    }
                });
        }
    }
}

Many of you guys use ASP.NET Core nowadays, so as you can see it doesn't differ a lot from what we have there.

It really got me perplexed first, I was trying to implement custom providers, etc. But I didn't expect it to be so simple. OWIN just rocks!

Just one thing to mention - after I enabled OWIN Startup NSWag library stopped working for me (e.g. some of you might want to auto-generate typescript HTTP proxies for Angular app).

The solution was also very simple - I replaced NSWag with Swashbuckle and didn't have any further issues.


Ok, now sharing ConfigHelper code:

public class ConfigHelper
{
    public static string GetIssuer()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["Issuer"];
        return result;
    }

    public static string GetAudience()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["Audience"];
        return result;
    }

    public static SigningCredentials GetSigningCredentials()
    {
        var result = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);
        return result;
    }

    public static string GetSecurityKey()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["SecurityKey"];
        return result;
    }

    public static byte[] GetSymmetricSecurityKeyAsBytes()
    {
        var issuerSigningKey = GetSecurityKey();
        byte[] data = Encoding.UTF8.GetBytes(issuerSigningKey);
        return data;
    }

    public static SymmetricSecurityKey GetSymmetricSecurityKey()
    {
        byte[] data = GetSymmetricSecurityKeyAsBytes();
        var result = new SymmetricSecurityKey(data);
        return result;
    }

    public static string GetCorsOrigins()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["CorsOrigins"];
        return result;
    }
}

Another important aspect - I sent JWT Token via Authorization header, so typescript code looks for me as follows:

(the code below is generated by NSWag)

@Injectable()
export class TeamsServiceProxy {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44384";
    }

    add(input: TeamDto | null): Observable<boolean> {
        let url_ = this.baseUrl + "/api/Teams/Add";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(input);

        let options_ : any = {
            body: content_,
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Content-Type": "application/json", 
                "Accept": "application/json",
                "Authorization": "Bearer " + localStorage.getItem('token')
            })
        };

See headers part - "Authorization": "Bearer " + localStorage.getItem('token')

Generate MD5 hash string with T-SQL

Solution:

SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)

What is the difference between single-quoted and double-quoted strings in PHP?

Both kinds of enclosed characters are strings. One type of quote is conveniently used to enclose the other type of quote. "'" and '"'. The biggest difference between the types of quotes is that enclosed identifier references are substituted for inside double quotes, but not inside single quotes.

Hibernate: Automatically creating/updating the db tables based on entity classes

You might try changing this line in your persistence.xml from

<property name="hbm2ddl.auto" value="create"/>

to:

<property name="hibernate.hbm2ddl.auto" value="update"/>

This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.

Got this from JavaRanch

mysqldump Error 1045 Access denied despite correct passwords etc

This worked for me

mysqldump -u root -p mydbscheme > mydbscheme_dump.sql

after issuing the command it asks for a password:

Enter password:

entering the password will make the dump file.

Escape text for HTML

Didn't see this here

System.Web.HttpUtility.JavaScriptStringEncode("Hello, this is Satan's Site")

it was the only thing that worked (asp 4.0+) when dealing with html like this. The&apos; gets rendered as ' (using htmldecode) in the html, causing it to fail:

<a href="article.aspx?id=268" onclick="tabs.open('modules/xxx/id/268', 'It&apos;s Allstars'); return false;">It's Allstars</a>

Understanding the Rails Authenticity Token

What happens

When the user views a form to create, update, or destroy a resource, the Rails app creates a random authenticity_token, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for the authenticity_token, compares it to the one stored in the session, and if they match the request is allowed to continue.

Why it happens

Since the authenticity token is stored in the session, the client cannot know its value. This prevents people from submitting forms to a Rails app without viewing the form within that app itself. Imagine that you are using service A, you logged into the service and everything is ok. Now imagine that you went to use service B, and you saw a picture you like, and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to http://serviceA.com/close_account. This is what is known as CSRF (Cross Site Request Forgery).

If service A is using authenticity tokens, this attack vector is no longer applicable, since the request from service B would not contain the correct authenticity token, and will not be allowed to continue.

API docs describes details about meta tag:

CSRF protection is turned on with the protect_from_forgery method, which checks the token and resets the session if it doesn't match what was expected. A call to this method is generated for new Rails applications by default. The token parameter is named authenticity_token by default. The name and value of this token must be added to every layout that renders forms by including csrf_meta_tags in the HTML head.

Notes

Keep in mind, Rails only verifies not idempotent methods (POST, PUT/PATCH and DELETE). GET request are not checked for authenticity token. Why? because the HTTP specification states that GET requests is idempotent and should not create, alter, or destroy resources at the server, and the request should be idempotent (if you run the same command multiple times, you should get the same result every time).

Also the real implementation is a bit more complicated as defined in the beginning, ensuring better security. Rails does not issue the same stored token with every form. Neither does it generate and store a different token every time. It generates and stores a cryptographic hash in a session and issues new cryptographic tokens, which can be matched against the stored one, every time a page is rendered. See request_forgery_protection.rb.

Lessons

Use authenticity_token to protect your not idempotent methods (POST, PUT/PATCH, and DELETE). Also make sure not to allow any GET requests that could potentially modify resources on the server.


EDIT: Check the comment by @erturne regarding GET requests being idempotent. He explains it in a better way than I have done here.

Access non-numeric Object properties by index?

The only way I can think of doing this is by creating a method that gives you the property using Object.keys();.

var obj = {
    dog: "woof",
    cat: "meow",
    key: function(n) {
        return this[Object.keys(this)[n]];
    }
};
obj.key(1); // "meow"

Demo: http://jsfiddle.net/UmkVn/

It would be possible to extend this to all objects using Object.prototype; but that isn't usually recommended.

Instead, use a function helper:

var object = {
  key: function(n) {
    return this[ Object.keys(this)[n] ];
  }
};

function key(obj, idx) {
  return object.key.call(obj, idx);
}

key({ a: 6 }, 0); // 6

Remove padding from columns in Bootstrap 3

Bootstrap 4 has a native class to do this : add the class .no-gutters to the parent .row

C# function to return array

return Labels; should do the trick!

public static ArtworkData[] GetDataRecords(int UsersID)
{
    ArtworkData[] Labels;
    Labels = new ArtworkData[3];

    return Labels;
}