Programs & Examples On #Riff

RIFF(Resource Interchange File Format) is a generic file container format for storing data in tagged chunks. It is primarily used to store multimedia such as sound and video, though it may also be used to store any arbitrary data.

Angular 2 @ViewChild annotation returns undefined

My solution to this was to replace *ngIf with [hidden]. Downside was all the child components were present in the code DOM. But worked for my requirements.

What's the difference between the Window.Loaded and Window.ContentRendered events

This is not about the difference between Window.ContentRendered and Window.Loaded but about what how the Window.Loaded event can be used:

I use it to avoid splash screens in all applications which need a long time to come up.

    // initializing my main window
    public MyAppMainWindow()
    {
        InitializeComponent();

        // Set the event
        this.ContentRendered += MyAppMainWindow_ContentRendered;
    }

    private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
    {
        // ... comes up quick when the controls are loaded and rendered

        // unset the event
        this.ContentRendered -= MyAppMainWindow_ContentRendered;

        // ... make the time comsuming init stuff here
    }

Initialize Array of Objects using NSArray

There is also a shorthand of doing this:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

Check that you are extending CI_Controller class in your controller and in the view you have to echo base_url($path) function, otherwise it will not work.

Why is exception.printStackTrace() considered bad practice?

I think your list of reasons is a pretty comprehensive one.

One particularly bad example that I've encountered more than once goes like this:

    try {
      // do stuff
    } catch (Exception e) {
        e.printStackTrace(); // and swallow the exception
    }

The problem with the above code is that the handling consists entirely of the printStackTrace call: the exception isn't really handled properly nor is it allowed to escape.

On the other hand, as a rule I always log the stack trace whenever there's an unexpected exception in my code. Over the years this policy has saved me a lot of debugging time.

Finally, on a lighter note, God's Perfect Exception.

How can I compare two ordered lists in python?

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

Skip a submodule during a Maven build

Maven version 3.2.1 added this feature, you can use the -pl switch (shortcut for --projects list) with ! or - (source) to exclude certain submodules.

mvn -pl '!submodule-to-exclude' install
mvn -pl -submodule-to-exclude install

Be careful in bash the character ! is a special character, so you either have to single quote it (like I did) or escape it with the backslash character.

The syntax to exclude multiple module is the same as the inclusion

mvn -pl '!submodule1,!submodule2' install
mvn -pl -submodule1,-submodule2 install

EDIT Windows does not seem to like the single quotes, but it is necessary in bash ; in Windows, use double quotes (thanks @awilkinson)

mvn -pl "!submodule1,!submodule2" install

How to enumerate an enum with String type?

enum Rank: Int
{
    case Ace = 0
    case Two, Three, Four, Five, Six, Seve, Eight, Nine, Ten
    case Jack, Queen, King
    case Count
}

enum Suit : Int
{
    case Spades = 0
    case Hearts, Diamonds, Clubs
    case Count
}

struct Card
{
    var rank:Rank
    var suit:Suit
}

class Test
{
    func makeDeck() -> Card[]
    {
        let suitsCount:Int = Suit.Count.toRaw()
        let rankCount:Int = Rank.Count.toRaw()
        let repeatedCard:Card = Card(rank:Rank.Ace, suit:Suit.Spades)
        let deck:Card[] = Card[](count:suitsCount*rankCount, repeatedValue:repeatedCard)

        for i:Int in 0..rankCount
        {
            for j:Int in 0..suitsCount
            {
                deck[i*suitsCount+j] = Card(rank: Rank.fromRaw(i)!, suit: Suit.fromRaw(j)!)
            }
        }
        return deck
    }
}

Based on Rick answer: this is 5 times faster

Tab separated values in awk

You can set the Field Separator:

... | awk 'BEGIN {FS="\t"}; {print $1}'

Excellent read:

https://docs.freebsd.org/info/gawk/gawk.info.Field_Separators.html

IntelliJ: Working on multiple projects

Prequisite

Having all the related projects in the same root directory.

Steps

1) First you create a new Empty project

New empty project


2) Then you select the root directory of all you projects.

This will create a empty project, with a .idea directory that will simply remember the module organisation we are about to do in the next step

Select root directory


3) Then, in the next window, you import the different projects as modules

Import projects as modules


4) In the next window, to import each project, simply double click on the build.gradle, or pom.xml

The project will be imported as a new module. Select build file


5) Done, you now have all your projects as modules, opened on the same IntelliJ project

Result

Android Transparent TextView?

Below code for black:-

<color name="black">#000000</color>

Now if i want to use opacity than you can use below code :-

 <color name="black">#99000000</color> 

and below for opacity code:-

Hex Opacity Values

100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

refer Understanding colors on Android (six characters)

How to replace all strings to numbers contained in each string in Notepad++?

Replace (.*")\d+(")

With $1x$2

Where x is your "value inside scopes".

How to remove a field completely from a MongoDB document?

I was trying to do something similar to this but instead remove the column from an embedded document. It took me a while to find a solution and this was the first post I came across so I thought I would post this here for anyone else trying to do the same.

So lets say instead your data looks like this:

{ 
  name: 'book',
  tags: [
    {
      words: ['abc','123'],
      lat: 33,
      long: 22
    }, {
      words: ['def','456'],
      lat: 44,
      long: 33
    }
  ]
}

To remove the column words from the embedded document, do this:

db.example.update(
  {'tags': {'$exists': true}},
  { $unset: {'tags.$[].words': 1}},
  {multi: true}
)

or using the updateMany

db.example.updateMany(
  {'tags': {'$exists': true}},
  { $unset: {'tags.$[].words': 1}}
)

The $unset will only edit it if the value exists but it will not do a safe navigation (it wont check if tags exists first) so the exists is needed on the embedded document.

This uses the all positional operator ($[]) which was introduced in version 3.6

How to get week number of the month from the date in sql server 2008

You can simply get week number by getting minimum week number of month and deduct it from week number. Suppose you have a table with dates

select
    emp_id, dt , datepart(wk,dt) - (select min(datepart(wk,dt))
from
    workdates ) + 1 from workdates

How to add images to README.md on GitHub?

Many of the posted solutions are incomplete or not to my taste.

  • An external CDN like imgur adds another tool to the chain. Meh.
  • Creating a dummy issue in the issue tracker is a hack. It creates clutter and confuses users. It's a pain to migrate this solution to a fork, or off GitHub.
  • Using the gh-pages branch makes the URLs brittle. Another person working on the project maintaining the gh-page may not know something external depends on the path to these images. The gh-pages branch has a particular behavior on GitHub which is not necessary for hosting CDN images.
  • Tracking assets in version control is a good thing. As a project grows and changes it's a more sustainable way to manage and track changes by multiple users.
  • If an image applies to a specific revision of the software, it may be preferable to link an immutable image. That way, if the image is later updated to reflect changes to the software, anyone reading that revision's readme will find the correct image.

My preferred solution, inspired by this gist, is to use an assets branch with permalinks to specific revisions.

git checkout --orphan assets
git reset --hard
cp /path/to/cat.png .
git add .
git commit -m 'Added cat picture'
git push -u origin assets
git rev-parse HEAD  # Print the SHA, which is optional, you'll see below.

Construct a "permalink" to this revision of the image, and wrap it in Markdown.

Looking up the commit SHA by hand is inconvenient, however, so as a shortcut press Y to a permalink to a file in a specific commit as this help.github page says.

To always show the latest image on the assets branch, use the blob URL:

https://github.com/github/{repository}/blob/assets/cat.png 

(From the same GitHub help page File views show the latest version on a branch)

Round up value to nearest whole number in SQL UPDATE

For MS SQL CEILING(your number) will round it up. FLOOR(your number) will round it down

Generic List - moving an item within the list

List<T>.Remove() and List<T>.RemoveAt() do not return the item that is being removed.

Therefore you have to use this:

var item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);

Pretty-Printing JSON with PHP

If you are working with MVC

try doing this in your controller

public function getLatestUsers() {
    header('Content-Type: application/json');
    echo $this->model->getLatestUsers(); // this returns json_encode($somedata, JSON_PRETTY_PRINT)
}

then if you call /getLatestUsers you will get a pretty JSON output ;)

C# How do I click a button by hitting Enter whilst textbox has focus?

Add this to the Form's constructor:

this.textboxName.KeyDown += (sender, args) => {
    if (args.KeyCode == Keys.Return)
    {
        buttonName.PerformClick();
    }
};

How do I convert Word files to PDF programmatically?

I went through the Word to PDF pain when someone dumped me with 10000 word files to convert to PDF. Now I did it in C# and used Word interop but it was slow and crashed if I tried to use PC at all.. very frustrating.

This lead me to discovering I could dump interops and their slowness..... for Excel I use (EPPLUS) and then I discovered that you can get a free tool called Spire that allows converting to PDF... with limitations!

http://www.e-iceblue.com/Introduce/free-doc-component.html#.VtAg4PmLRhE

Try/catch does not seem to have an effect

In my case, it was because I was only catching specific types of exceptions:

try
  {
    get-item -Force -LiteralPath $Path -ErrorAction Stop

    #if file exists
    if ($Path -like '\\*') {$fileType = 'n'}  #Network
    elseif ($Path -like '?:\*') {$fileType = 'l'} #Local
    else {$fileType = 'u'} #Unknown File Type

  }
catch [System.UnauthorizedAccessException] {$fileType = 'i'} #Inaccessible
catch [System.Management.Automation.ItemNotFoundException]{$fileType = 'x'} #Doesn't Exist

Added these to handle additional the exception causing the terminating error, as well as unexpected exceptions

catch [System.Management.Automation.DriveNotFoundException]{$fileType = 'x'} #Doesn't Exist
catch {$fileType='u'} #Unknown

Select all columns except one in MySQL?

To the best of my knowledge, there isn't. You can do something like:

SELECT col1, col2, col3, col4 FROM tbl

and manually choose the columns you want. However, if you want a lot of columns, then you might just want to do a:

SELECT * FROM tbl 

and just ignore what you don't want.

In your particular case, I would suggest:

SELECT * FROM tbl

unless you only want a few columns. If you only want four columns, then:

SELECT col3, col6, col45, col 52 FROM tbl

would be fine, but if you want 50 columns, then any code that makes the query would become (too?) difficult to read.

Create a date time with month and day only, no year

There is no such thing like a DateTime without a year!

From what I gather your design is a bit strange:

I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.

After the event occurs you calculate the next and store that etc.

How can I list all foreign keys referencing a given table in SQL Server?

I am using this script to find all details related to foreign key. I am using INFORMATION.SCHEMA. Below is a SQL Script:

SELECT 
    ccu.table_name AS SourceTable
    ,ccu.constraint_name AS SourceConstraint
    ,ccu.column_name AS SourceColumn
    ,kcu.table_name AS TargetTable
    ,kcu.column_name AS TargetColumn
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
    INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
        ON ccu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME 
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu 
        ON kcu.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME  
ORDER BY ccu.table_name

How to pass a user / password in ansible command

you can use --extra-vars like this:

$ ansible all --inventory=10.0.1.2, -m ping \
    --extra-vars "ansible_user=root ansible_password=yourpassword"

If you're authenticating to a Linux host that's joined to a Microsoft Active Directory domain, this command line works.

ansible --module-name ping --extra-vars 'ansible_user=domain\user ansible_password=PASSWORD' --inventory 10.10.6.184, all

What is "git remote add ..." and "git push origin master"?

  1. The .git at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git. The git client and protocol honours this convention by testing for project.git when only project is specified.

  2. git://[email protected]/peter/first_app.git is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git is the ssh url mentioned on that page.

  3. git is flexible. It allows you to track your local branch against almost any branch of any repository. While master (your local default branch) tracking origin/master (the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push is so verbose. It tells git what to do with the local master branch when you do a git pull or a git push.

  4. The default for git push and git pull is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.

git is fairly elegant and comprehensible but there is a learning curve to walk through.

How to "Open" and "Save" using java

You want to use a JFileChooser object. It will open and be modal, and block in the thread that opened it until you choose a file.

Open:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // load from file
}

Save:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // save to file
}

There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser for details. There is also a page for "How to Use File Choosers" on Oracle's site:

http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

How to generate a simple popup using jQuery

I use a jQuery plugin called ColorBox, it is

  1. Very easy to use
  2. lightweight
  3. customizable
  4. the nicest popup dialog I have seen for jQuery yet

Best way to convert string to bytes in Python 3?

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

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

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

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

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

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

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

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

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

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

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

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

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

TypeError: 'str' object cannot be interpreted as an integer

You will have to put:

X = input("give starting number") 
X = int(X)
Y = input("give ending number") 
Y = int(Y)

Create a .csv file with values from a Python list

Here is another solution that does not require the csv module.

print ', '.join(['"'+i+'"' for i in myList])

Example :

>>> myList = [u'value 1', u'value 2', u'value 3']
>>> print ', '.join(['"'+i+'"' for i in myList])
"value 1", "value 2", "value 3"

However, if the initial list contains some ", they will not be escaped. If it is required, it is possible to call a function to escape it like that :

print ', '.join(['"'+myFunction(i)+'"' for i in myList])

Turning off eslint rule for a specific file

As of today, the answer does not work for me, but putting this at the top of the file does work:

/* eslint-disable @typescript-eslint/no-unused-vars */

It is important to know that at least in my case, the type of comment makes a difference. The previous comment works for me, but the following won't work:

// eslint-disable @typescript-eslint/no-unused-vars

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

Check space of your database.this error comes when space increased compare to space given to database.

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

std::atan2 allows calculating the arctangent of all four quadrants. std::atan only allows calculating from quadrants 1 and 4.

ionic build Android | error: No installed build tools found. Please install the Android build tools

For me, the problem was that ANDROID_HOME was pointing to an old Android SDK path. After installing Android Studio, I had to update ~/.bash_profile accordingly for MAC (El Capitan)

export ANDROID_HOME="/Users/corneliusparkin/Library/Android/sdk"

Remember to re-start terminal or run this command after updating ~/.bash_profile

source ~/.bash_profile

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

I run this

var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);

$.ajax({
    type: 'GET',
    url: 'linkserverApi',
    success: function(success) {
        console.log('Success!');
        console.log(success);
    },
    error: function() {
        console.log('Uh Oh!');
    },
    jsonp: 'jsonp'

});

And edit header in the response

'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'

'Access-Control-Max-Age' , '3628800'

'Access-Control-Allow-Origin', 'websiteresponseUrl'

'Content-Type', 'text/javascript; charset=utf8'

Preventing HTML and Script injections in Javascript

I use this function htmlentities($string):

$msg = "<script>alert("hello")</script> <h1> Hello World </h1>"
$msg = htmlentities($msg);
echo $msg;

AngularJS accessing DOM elements inside directive template

I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:

{
     template: '<div>' +
    '<div class="title">{{title}}</div>' +
    '<div class="body" ng-transclude></div>' +
    '</div>',

    link: function(scope, element, attrs) {
        // Title element
        var title = angular.element(element.children()[0]),
        // ...
    }
}

Change R default library path using .libPaths in Rprofile.site fails to work

just change the default folder for your R libraries in a directory with no Administrator rights, e.g.

.libPaths("C:/R/libs")

Can I embed a .png image into an html page?

There are a few base64 encoders online to help you with this, this is probably the best I've seen:

http://www.greywyvern.com/code/php/binary2base64

As that page shows your main options for this are CSS:

div.image {
  width:100px;
  height:100px;
  background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>); 
}

Or the <img> tag itself, like this:

<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />

Blurry text after using CSS transform: scale(); in Chrome

you can use css filter to fix this.

.element {
    filter: blur(0);
}

about vendor-prefix, please do it by yourself.-webkit-filter,-ms-filter. detail is here http://browser.colla.me/show/css_transformation_scale_cause_blurring

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The latest docker supports setting ulimits through the command line and the API. For instance, docker run takes --ulimit <type>=<soft>:<hard> and there can be as many of these as you like. So, for your nofile, an example would be --ulimit nofile=262144:262144

GitHub Error Message - Permission denied (publickey)

In case you are not accessing your own repository, or cloning inside a cloned repository (using some "git submodule... " commands):

In the home directory of your repository:

$ ls -a

1. Open ".gitmodules", and you will find something like this:

[submodule "XXX"]
    path = XXX
    url = [email protected]:YYY/XXX.git

Change the last line to be the HTTPS of the repository you need to pull:

[submodule "XXX"]
    path = XXX
    https://github.com/YYY/XXX.git

Save ".gitmodules", and run the command for submodules, and ".git" will be updated.

2. Open ".git", go to "config" file, and you will find something like this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/YYY/XXX.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[submodule "XXX"]
    url = [email protected]:YYY/XXX.git

Change the last line to be the HTTPS of the repository you need to pull:

    url = https://github.com/YYY/XXX.git

So, in this case, the main problem is simply with the url. HTTPS of any repository can be found now on top of the repository page.

Accessing dict_keys element by index in Python3

Python 3

mydict = {'a': 'one', 'b': 'two', 'c': 'three'}
mykeys = [*mydict]          #list of keys
myvals = [*mydict.values()] #list of values

print(mykeys)
print(myvals)

Output

['a', 'b', 'c']
['one', 'two', 'three']

Also see this detailed answer

Calculate percentage Javascript

You can use this

function percentage(partialValue, totalValue) {
   return (100 * partialValue) / totalValue;
} 

Example to calculate the percentage of a course progress base in their activities.

const totalActivities = 10;
const doneActivities = 2;

percentage(doneActivities, totalActivities) // Will return 20 that is 20%

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

See https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html .

To solve some long-standing issues, m2e 1.0 requires explicit instructions what to do with all Maven plugins bound to "interesting" phases of project build lifecycle. We call these instructions "project build lifecycle mapping" or simply "lifecycle mapping" because they define how m2e maps information from project pom.xml file to Eclipse workspace project configuration and behaviour during Eclipse workspace build.

Project build lifecycle mapping configuration can be specified in project pom.xml, contributed by Eclipse plugins and there is also default configuration for some commonly used Maven plugins shipped with m2e. We call these "lifecycle mapping metadata sources". m2e will create error marker like below for all plugin executions that do not have lifecycle mapping in any of the mapping metadata sources.

Plugin execution not covered by lifecycle configuration:
org.apache.maven.plugins:maven-antrun-plugin:1.3:run
   (execution: generate-sources-input, phase: generate-sources)

m2e matches plugin executions to actions using combination of plugin groupId, artifactId, version range and goal. There are three basic actions that m2e can be instructed to do with a plugin execution -- ignore, execute and delegate to a project configurator.

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Select elements by attribute

simply:

$('input[name*="value"]')

more info: official docs

Getting attribute of element in ng-click function in angularjs

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value;

Which would return exampleData.

Here's a full jsFiddle.

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

Import error No module named skimage

You can use pip install scikit-image.

Also see the recommended procedure.

Instantiate and Present a viewController in Swift

Swift 4:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let yourVC: YourVC = storyboard.instantiateViewController(withIdentifier: "YourVC") as! YourVC

Check if a key is down?

The following code is what I'm using:

var altKeyDownCount = 0;
window.onkeydown = function (e) {
    if (!e) e = window.event;
    if (e.altKey) {
        altKeyDownCount++;
        if (30 < altKeyDownCount) {
            $('.key').removeClass('hidden');
            altKeyDownCount = 0;
        }
        return false;
    }
}

window.onkeyup = function (e) {
    if (!e) e = window.event;
    altKeyDownCount = 0;
    $('.key').addClass('hidden');
}

When the user keeps holding down the Alt key for some time (about 2 seconds), a group of labels (class='key hidden') appears. When the Alt key is released, the labels disappear. jQuery and Bootstrap are both used.

Creating a directory in /sdcard fails

I had same issue after I updated my Android phone to 6.0 (API level 23). The following solution works on me. Hopefully it helps you as well.

Please check your android version. If it is >= 6.0 (API level 23), you need to not only include

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

in your AndroidManifest.xml, but also request permission before calling mkdir(). Code snopshot.

public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
public int mkFolder(String folderName){ // make a folder under Environment.DIRECTORY_DCIM
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)){
        Log.d("myAppName", "Error: external storage is unavailable");
        return 0;
    }
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        Log.d("myAppName", "Error: external storage is read only.");
        return 0;
    }
    Log.d("myAppName", "External storage is not read only or unavailable");

    if (ContextCompat.checkSelfPermission(this, // request permission when it is not granted. 
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        Log.d("myAppName", "permission:WRITE_EXTERNAL_STORAGE: NOT granted!");
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
    File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),folderName);
    int result = 0;
    if (folder.exists()) {
        Log.d("myAppName","folder exist:"+folder.toString());
        result = 2; // folder exist
    }else{
        try {
            if (folder.mkdir()) {
                Log.d("myAppName", "folder created:" + folder.toString());
                result = 1; // folder created
            } else {
                Log.d("myAppName", "creat folder fails:" + folder.toString());
                result = 0; // creat folder fails
            }
        }catch (Exception ecp){
            ecp.printStackTrace();
        }
    }
    return result;
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

More information please read "Requesting Permissions at Run Time"

How do I truncate a .NET string?

The popular library Humanizer has a Truncate method. To install with NuGet:

Install-Package Humanizer

Sorting dropdown alphabetically in AngularJS

Angular has an orderBy filter that can be used like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>

See this fiddle for an example.

It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>

How to get the squared symbol (²) to display in a string

No need to get too complicated. If all you need is ² then use the unicode representation.

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

(which is how I assume you got the ² to appear in your question. )

PKIX path building failed: unable to find valid certification path to requested target

On Mac OS I had to open the server's self-signed certificate with system Keychain Access tool, import it, dobubleclick it and then select "Always trust" (even though I set the same in importer). Before that, of course I ran java key took with -importcert to import same file to cacert storage.

Git:nothing added to commit but untracked files present

Follow all the steps.

Step 1: initialize git

$ git init

Step 2: Check files are exist or not.

$git ls

Step 3 : Add the file

$git add filename

Step 4: Add comment to show

$git commit -m "your comment"

Step 5: Link to your repository

$git remote add origin  "copy repository link  and paste here"

Step 6: Push on Git

$ git push -u origin master

support FragmentPagerAdapter holds reference to old fragments

My solution: I set almost every View as static. Now my app interacts perfect. Being able to call the static methods from everywhere is maybe not a good style, but why to play around with code that doesn't work? I read a lot of questions and their answers here on SO and no solution brought success (for me).

I know it can leak the memory, and waste heap, and my code will not be fit on other projects, but I don't feel scared about this - I tested the app on different devices and conditions, no problems at all, the Android Platform seems to be able handle this. The UI gets refreshed every second and even on a S2 ICS (4.0.3) device the app is able to handle thousands of geo-markers.

SQL INSERT INTO from multiple tables

You only need one INSERT:

INSERT INTO table4 ( name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id
INNER JOIN table3 n ON p.Id = n.Id

How to fix Error: listen EADDRINUSE while using nodejs?

I have seen this error before (in node) with http.client, and as I recall, the problem had to do with not initializing the httpClient or setting bad options in the httpClient creation and/or in the url request.

Best practice for instantiating a new Android Fragment

While @yydl gives a compelling reason on why the newInstance method is better:

If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.

it's still quite possible to use a constructor. To see why this is, first we need to see why the above workaround is used by Android.

Before a fragment can be used, an instance is needed. Android calls YourFragment() (the no arguments constructor) to construct an instance of the fragment. Here any overloaded constructor that you write will be ignored, as Android can't know which one to use.

In the lifetime of an Activity the fragment gets created as above and destroyed multiple times by Android. This means that if you put data in the fragment object itself, it will be lost once the fragment is destroyed.

To workaround, android asks that you store data using a Bundle (calling setArguments()), which can then be accessed from YourFragment. Argument bundles are protected by Android, and hence are guaranteed to be persistent.

One way to set this bundle is by using a static newInstance method:

public static YourFragment newInstance (int data) {
    YourFragment yf = new YourFragment()
    /* See this code gets executed immediately on your object construction */
    Bundle args = new Bundle();
    args.putInt("data", data);
    yf.setArguments(args);
    return yf;
}

However, a constructor:

public YourFragment(int data) {
    Bundle args = new Bundle();
    args.putInt("data", data);
    setArguments(args);
}

can do exactly the same thing as the newInstance method.

Naturally, this would fail, and is one of the reasons Android wants you to use the newInstance method:

public YourFragment(int data) {
    this.data = data; // Don't do this
}

As further explaination, here's Android's Fragment Class:

/**
 * Supply the construction arguments for this fragment.  This can only
 * be called before the fragment has been attached to its activity; that
 * is, you should call it immediately after constructing the fragment.  The
 * arguments supplied here will be retained across fragment destroy and
 * creation.
 */
public void setArguments(Bundle args) {
    if (mIndex >= 0) {
        throw new IllegalStateException("Fragment already active");
    }
    mArguments = args;
}

Note that Android asks that the arguments be set only at construction, and guarantees that these will be retained.

EDIT: As pointed out in the comments by @JHH, if you are providing a custom constructor that requires some arguments, then Java won't provide your fragment with a no arg default constructor. So this would require you to define a no arg constructor, which is code that you could avoid with the newInstance factory method.

EDIT: Android doesn't allow using an overloaded constructor for fragments anymore. You must use the newInstance method.

TypeError: 'builtin_function_or_method' object is not subscriptable

Can't believe this thread was going on for so long. You would get this error if you got distracted and used [] instead of (), at least my case.

Pop is a method on the list data type, https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Therefore, you shouldn't be using pop as if it was a list itself, pop[0]. It's a method that takes an optional parameter representing an index, so as Tushar Palawat pointed out in one of the answers that didn't get approved, the correct adjustment which will fix the example above is:

listb.pop(0)

If you don't believe, run a sample such as:

if __name__ == '__main__':
  listb = ["-test"]
  if( listb[0] == "-test"):
    print(listb.pop(0))

Other adjustments would work as well, but it feels as they are abusing the Python language. This thread needs to get fixed, not to confuse users.

Addition, a.pop() removes and returns the last item in the list. As a result, a.pop()[0] will get the first character of that last element. It doesn't seem that is what the given code snippet is aiming to achieve.

DateTimePicker time picker in 24 hour but displaying in 12hr?

this will display current ate & time. Working on my side perfectly

$("#datePicker").datetimepicker({
    format: 'DD-MM-YYYY HH:mm A',
    defaultDate: new Date(),
});

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

How to describe "object" arguments in jsdoc?

By now there are 4 different ways to document objects as parameters/types. Each has its own uses. Only 3 of them can be used to document return values, though.

For objects with a known set of properties (Variant A)

/**
 * @param {{a: number, b: string, c}} myObj description
 */

This syntax is ideal for objects that are used only as parameters for this function and don't require further description of each property. It can be used for @returns as well.

For objects with a known set of properties (Variant B)

Very useful is the parameters with properties syntax:

/**
 * @param {Object} myObj description
 * @param {number} myObj.a description
 * @param {string} myObj.b description
 * @param {} myObj.c description
 */

This syntax is ideal for objects that are used only as parameters for this function and that require further description of each property. This can not be used for @returns.

For objects that will be used at more than one point in source

In this case a @typedef comes in very handy. You can define the type at one point in your source and use it as a type for @param or @returns or other JSDoc tags that can make use of a type.

/**
 * @typedef {Object} Person
 * @property {string} name how the person is called
 * @property {number} age how many years the person lived
 */

You can then use this in a @param tag:

/**
 * @param {Person} p - Description of p
 */

Or in a @returns:

/**
 * @returns {Person} Description
 */

For objects whose values are all the same type

/**
 * @param {Object.<string, number>} dict
 */

The first type (string) documents the type of the keys which in JavaScript is always a string or at least will always be coerced to a string. The second type (number) is the type of the value; this can be any type. This syntax can be used for @returns as well.

Resources

Useful information about documenting types can be found here:

https://jsdoc.app/tags-type.html

PS:

to document an optional value you can use []:

/**
 * @param {number} [opt_number] this number is optional
 */

or:

/**
 * @param {number|undefined} opt_number this number is optional
 */

Align button to the right

Bootstrap 4 uses .float-right as opposed to .pull-right in Bootstrap 3. Also, don't forget to properly nest your rows with columns.

<div class="row">
    <div class="col-lg-12">
        <h3 class="one">Text</h3>
        <button class="btn btn-secondary float-right">Button</button>
    </div>
</div>

When should I use a struct rather than a class in C#?

MYTH #1: STRUCTS ARE LIGHTWEIGHT CLASSES

This myth comes in a variety of forms. Some people believe that value types can’t or shouldn’t have methods or other significant behavior—they should be used as simple data transfer types, with just public fields or simple properties. The DateTime type is a good counterexample to this: it makes sense for it to be a value type, in terms of being a fundamental unit like a number or a character, and it also makes sense for it to be able to perform calculations based on its value. Looking at things from the other direction, data transfer types should often be reference types anyway—the decision should be based on the desired value or reference type semantics, not the simplicity of the type. Other people believe that value types are “lighter” than reference types in terms of performance. The truth is that in some cases value types are more performant— they don’t require garbage collection unless they’re boxed, don’t have the type identification overhead, and don’t require dereferencing, for example. But in other ways, reference types are more performant—parameter passing, assigning values to variables, returning values, and similar operations only require 4 or 8 bytes to becopied (depending on whether you’re running the 32-bit or 64-bit CLR) rather than copying all the data. Imagine if ArrayList were somehow a “pure” value type, and passing an ArrayList expression to a method involved copying all its data! In almost all cases, performance isn’t really determined by this sort of decision anyway. Bottlenecks are almost never where you think they’ll be, and before you make a design decision based on performance, you should measure the different options. It’s worth noting that the combination of the two beliefs doesn’t work either. It doesn’t matter how many methods a type has (whether it’s a class or a struct)—the memory taken per instance isn’t affected. (There’s a cost in terms of the memory taken up for the code itself, but that’s incurred once rather than for each instance.)

MYTH #2: REFERENCE TYPES LIVE ON THE HEAP; VALUE TYPES LIVE ON THE STACK

This one is often caused by laziness on the part of the person repeating it. The first part is correct—an instance of a reference type is always created on the heap. It’s the second part that causes problems. As I’ve already noted, a variable’s value lives wherever it’s declared, so if you have a class with an instance variable of type int, that variable’s value for any given object will always be where the rest of the data for the object is—on the heap. Only local variables (variables declared within methods) and method parameters live on the stack. In C# 2 and later, even some local variables don’t really live on the stack, as you’ll see when we look at anonymous methods in chapter 5. ARE THESE CONCEPTS RELEVANT NOW? It’s arguable that if you’re writing managed code, you should let the runtime worry about how memory is best used. Indeed, the language specification makes no guarantees about what lives where; a future runtime may be able to create some objects on the stack if it knows it can get away with it, or the C# compiler could generate code that hardly uses the stack at all. The next myth is usually just a terminology issue.

MYTH #3: OBJECTS ARE PASSED BY REFERENCE IN C# BY DEFAULT

This is probably the most widely propagated myth. Again, the people who make this claim often (though not always) know how C# actually behaves, but they don’t know what “pass by reference” really means. Unfortunately, this is confusing for people who do know what it means. The formal definition of pass by reference is relatively complicated, involving l-values and similar computer-science terminology, but the important thing is that if you pass a variable by reference, the method you’re calling can change the value of the caller’s variable by changing its parameter value. Now, remember that the value of a reference type variable is the reference, not the object itself. You can change the contents of the object that a parameter refers to without the parameter itself being passed by reference. For instance, the following method changes the contents of the StringBuilder object in question, but the caller’s expression will still refer to the same object as before:

void AppendHello(StringBuilder builder)
{
    builder.Append("hello");
}

When this method is called, the parameter value (a reference to a StringBuilder) is passed by value. If you were to change the value of the builder variable within the method—for example, with the statement builder = null;—that change wouldn’t be seen by the caller, contrary to the myth. It’s interesting to note that not only is the “by reference” bit of the myth inaccurate, but so is the “objects are passed” bit. Objects themselves are never passed, either by reference or by value. When a reference type is involved, either the variable is passed by reference or the value of the argument (the reference) is passed by value. Aside from anything else, this answers the question of what happens when null is used as a by-value argument—if objects were being passed around, that would cause issues, as there wouldn’t be an object to pass! Instead, the null reference is passed by value in the same way as any other reference would be. If this quick explanation has left you bewildered, you might want to look at my article, “Parameter passing in C#,” (http://mng.bz/otVt), which goes into much more detail. These myths aren’t the only ones around. Boxing and unboxing come in for their fair share of misunderstanding, which I’ll try to clear up next.

Reference: C# in Depth 3rd Edition by Jon Skeet

How to read file contents into a variable in a batch file?

Read file contents into a variable:

for /f "delims=" %%x in (version.txt) do set Build=%%x

or

set /p Build=<version.txt

Both will act the same with only a single line in the file, for more lines the for variant will put the last line into the variable, while set /p will use the first.

Using the variable – just like any other environment variable – it is one, after all:

%Build%

So to check for existence:

if exist \\fileserver\myapp\releasedocs\%Build%.doc ...

Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.

Git Clone: Just the files, please?

git checkout -f

There's another way to do this by splitting the repo from the working tree.

This method is useful if you need to update these git-less git files on a regular basis. For instance, I use it when I need to check out source files and build an artifact, then copy the artifact into a different repo just for deployment to a server, and I also use it when pushing source code to a server when I want the source code to checkout and build into the www directory.

We'll make two folders, one for the git one for the working files:

mkdir workingfiles
mkdir barerepo.git

initialize a bare git repo:

cd barerepo.git
git --bare init 

Then create a post-receive hook:

touch hooks/post-receive
chmod ug+x hooks/post-receive

Edit post-receive in your favorite editor:

GIT_WORK_TREE=/path/to/workingfiles git checkout -f
# optional stuff:
cd down/to/some/directory
[do some stuff]

Add this as a remote:

git remote add myserver ssh://user@host:/path/to/barerepo.git

Now every time you push to this bare repo it will checkout the working tree to /workingfiles/. But /workingfiles/ itself is not under version control; running git status in /workingfiles/ will give the error fatal: Not a git repository (or any parent up to mount point /data). It's just plain files.

Unlike other solutions rm -r .git command is not needed, so if /workingfiles/ is some other git repo you don't have to worry about the command used removing the other repo's git files.

How to decorate a class?

I would second the notion that you may wish to consider a subclass instead of the approach you've outlined. However, not knowing your specific scenario, YMMV :-)

What you're thinking of is a metaclass. The __new__ function in a metaclass is passed the full proposed definition of the class, which it can then rewrite before the class is created. You can, at that time, sub out the constructor for a new one.

Example:

def substitute_init(self, id, *args, **kwargs):
    pass

class FooMeta(type):

    def __new__(cls, name, bases, attrs):
        attrs['__init__'] = substitute_init
        return super(FooMeta, cls).__new__(cls, name, bases, attrs)

class Foo(object):

    __metaclass__ = FooMeta

    def __init__(self, value1):
        pass

Replacing the constructor is perhaps a bit dramatic, but the language does provide support for this kind of deep introspection and dynamic modification.

Where is git.exe located?

Sometimes it can be at: C:\Users\user-name\AppData\Local\Programs\Git\cmd. Checking your PATH environment variable for USER and for SYSTEM can give you that.

Accidentally committed .idea directory files into git

You should add a .gitignore file to your project and add /.idea to it. You should add each directory / file in one line.

If you have an existing .gitignore file then you should simply add a new line to the file and put /.idea to the new line.

After that run git rm -r --cached .idea command.

If you faced an error you can run git rm -r -f --cached .idea command. After all run git add . and then git commit -m "Removed .idea directory and added a .gitignore file" and finally push the changes by running git push command.

How to print a number with commas as thousands separators in JavaScript

I thought I'd share a little trick which I'm using for large number formatting. Instead of inserting commas or spaces, I insert an empty but visible span in between the "thousands". This makes thousands easily visible, but it allows to copy/paste the input in the original format, without commas/spaces.

// This function accepts an integer, and produces a piece of HTML that shows it nicely with 
// some empty space at "thousand" markers. 
// Note, these space are not spaces, if you copy paste, they will not be visible.
function valPrettyPrint(orgVal) {
  // Save after-comma text, if present
  var period = orgVal.indexOf(".");
  var frac = period >= 0 ? orgVal.substr(period) : "";
  // Work on input as an integer
  var val = "" + Math.trunc(orgVal);
  var res = "";
  while (val.length > 0) {
    res = val.substr(Math.max(0, val.length - 3), 3) + res;
    val = val.substr(0, val.length - 3);
    if (val.length > 0) {
        res = "<span class='thousandsSeparator'></span>" + res;
    }
  }
  // Add the saved after-period information
  res += frac;
  return res;
}

With this CSS:

.thousandsSeparator {
  display : inline;
  padding-left : 4px;
}

See an example JSFiddle.

How to make a window always stay on top in .Net?

Set the form's .TopMost property to true.

You probably don't want to leave it this way all the time: set it when your external process starts and put it back when it finishes.

How to drop rows from pandas data frame that contains a particular string in a particular column?

This will only work if you want to compare exact strings. It will not work in case you want to check if the column string contains any of the strings in the list.

The right way to compare with a list would be :

searchfor = ['john', 'doe']
df = df[~df.col.str.contains('|'.join(searchfor))]

Check synchronously if file/directory exists in Node.js

The answer to this question has changed over the years. The current answer is here at the top, followed by the various answers over the years in chronological order:

Current Answer

You can use fs.existsSync():

const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
    // Do something
}

It was deprecated for several years, but no longer is. From the docs:

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.promises.access if you're using async functions or fs.access (since exists is deprecated) if not:

In an async function:

try {
    await fs.promises.access("somefile");
    // The check succeeded
} catch (error) {
    // The check failed
}

Or with a callback:

fs.access("somefile", error => {
    if (!error) {
        // The check succeeded
    } else {
        // The check failed
    }
});

Historical Answers

Here are the historical answers in chronological order:

  • Original answer from 2010
    (stat/statSync or lstat/lstatSync)
  • Update September 2012
    (exists/existsSync)
  • Update February 2015
    (Noting impending deprecation of exists/existsSync, so we're probably back to stat/statSync or lstat/lstatSync)
  • Update December 2015
    (There's also fs.access(path, fs.F_OK, function(){}) / fs.accessSync(path, fs.F_OK), but note that if the file/directory doesn't exist, it's an error; docs for fs.stat recommend using fs.access if you need to check for existence without opening)
  • Update December 2016
    fs.exists() is still deprecated but fs.existsSync() is no longer deprecated. So you can safely use it now.

Original answer from 2010:

You can use statSync or lstatSync (docs link), which give you an fs.Stats object. In general, if a synchronous version of a function is available, it will have the same name as the async version with Sync at the end. So statSync is the synchronous version of stat; lstatSync is the synchronous version of lstat, etc.

lstatSync tells you both whether something exists, and if so, whether it's a file or a directory (or in some file systems, a symbolic link, block device, character device, etc.), e.g. if you need to know if it exists and is a directory:

var fs = require('fs');
try {
    // Query the entry
    stats = fs.lstatSync('/the/path');

    // Is it a directory?
    if (stats.isDirectory()) {
        // Yes it is
    }
}
catch (e) {
    // ...
}

...and similarly, if it's a file, there's isFile; if it's a block device, there's isBlockDevice, etc., etc. Note the try/catch; it throws an error if the entry doesn't exist at all.

If you don't care what the entry is and only want to know whether it exists, you can use path.existsSync (or with latest, fs.existsSync) as noted by user618408:

var path = require('path');
if (path.existsSync("/the/path")) { // or fs.existsSync
    // ...
}

It doesn't require a try/catch but gives you no information about what the thing is, just that it's there. path.existsSync was deprecated long ago.


Side note: You've expressly asked how to check synchronously, so I've used the xyzSync versions of the functions above. But wherever possible, with I/O, it really is best to avoid synchronous calls. Calls into the I/O subsystem take significant time from a CPU's point of view. Note how easy it is to call lstat rather than lstatSync:

// Is it a directory?
lstat('/the/path', function(err, stats) {
    if (!err && stats.isDirectory()) {
        // Yes it is
    }
});

But if you need the synchronous version, it's there.

Update September 2012

The below answer from a couple of years ago is now a bit out of date. The current way is to use fs.existsSync to do a synchronous check for file/directory existence (or of course fs.exists for an asynchronous check), rather than the path versions below.

Example:

var fs = require('fs');

if (fs.existsSync(path)) {
    // Do something
}

// Or

fs.exists(path, function(exists) {
    if (exists) {
        // Do something
    }
});

Update February 2015

And here we are in 2015 and the Node docs now say that fs.existsSync (and fs.exists) "will be deprecated". (Because the Node folks think it's dumb to check whether something exists before opening it, which it is; but that's not the only reason for checking whether something exists!)

So we're probably back to the various stat methods... Until/unless this changes yet again, of course.

Update December 2015

Don't know how long it's been there, but there's also fs.access(path, fs.F_OK, ...) / fs.accessSync(path, fs.F_OK). And at least as of October 2016, the fs.stat documentation recommends using fs.access to do existence checks ("To check if a file exists without manipulating it afterwards, fs.access() is recommended."). But note that the access not being available is considered an error, so this would probably be best if you're expecting the file to be accessible:

var fs = require('fs');

try {
    fs.accessSync(path, fs.F_OK);
    // Do something
} catch (e) {
    // It isn't accessible
}

// Or

fs.access(path, fs.F_OK, function(err) {
    if (!err) {
        // Do something
    } else {
        // It isn't accessible
    }
});

Update December 2016

You can use fs.existsSync():

if (fs.existsSync(path)) {
    // Do something
}

It was deprecated for several years, but no longer is. From the docs:

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

List names of all tables in a SQL Server 2012 schema

SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'schema_name';

Singleton design pattern vs Singleton beans in Spring container

There is a very fundamental difference between the two. In case of Singleton design pattern, only one instance of a class will be created per classLoader while that is not the case with Spring singleton as in the later one shared bean instance for the given id per IoC container is created.

For example, if I have a class with the name "SpringTest" and my XML file looks something like this :-

<bean id="test1" class="com.SpringTest" scope="singleton">
        --some properties here
</bean>    
<bean id="test2" class="com.SpringTest" scope="singleton">
        --some properties here   
</bean>

So now in the main class if you will check the reference of the above two it will return false as according to Spring documentation:-

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container

So as in our case, the classes are the same but the id's that we have provided are different hence resulting in two different instances being created.

Check that an email address is valid on iOS

To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.

Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$

How you can use regular expressions depends on the version of iOS you are using.

iOS 4.x and Later

You can use NSRegularExpression, which allows you to compile and test against a regular expression directly.

iOS 3.x

Does not include the NSRegularExpression class, but does include NSPredicate, which can match against regular expressions.

NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];

Read a full article about this approach at cocoawithlove.com.

iOS 2.x

Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.

How do I get the directory from a file's full path?

You can use Path.GetFullPath for most of the case. But if you want to get the path also in the case of the file name is relatively located then you can use the below generic method:

string GetPath(string filePath)
{
  return Path.GetDirectoryName(Path.GetFullPath(filePath))
}

For example:

GetPath("C:\Temp\Filename.txt") return "C:\Temp\"

GetPath("Filename.txt") return current working directory like "C:\Temp\"

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

How to indent HTML tags in Notepad++

Building on Constantin's answer, here's the essence of what I learned while transitioning to Notepad++ as my primary HTML editor.

Install Notepad++ 32-bit

There's no 64-bit version of Tidy2 and some other popular plugins. The 32-bit version of NPP has few practical downsides, so axe the 64-bit version.

Install the Plugin Manager

Plugin Manager isn't strictly necessary for plugin usage. It does make things much easier, though.

Plugin Manager was eliminated from the core package apparently because the developer didn't like some included attribution linking.

You may notice that Plugin Manager plugin has been removed from the official distribution. The reason is Plugin Manager contains the advertising in its dialog. I hate Ads in applications, and I ensure you that there was no, and there will never be Ads in Notepad++.

It's a manual install, but it's not difficult.

  1. Download the UNI (32-bit) zip package and extract it. Inside you'll see folders called plugins and updater. Each contains one file.
  2. Drag those two files to the respective identically-named folders in your Notepad++ installation directory. Typically that's C:\Program Files (x86)\Notepad++.
  3. Restart Notepad++ and follow any install/update prompts.

Now you'll see a new entry under Plugins for Plugin Manager.

Install Tidy2 (or your preferred alternative)

In Plugin Manager, check the box for Tidy2. Click Install. Restart when prompted.

To use Tidy2, select one of the preconfigured profiles in its Plugins submenu item, or create your own.

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

If you use Sqlite's REGEXP support ( see the answer at Problem with regexp python and sqlite for how to do that ) , then you can do it easily in one clause:

SELECT word FROM table WHERE word NOT REGEXP '[abc]';

Convert between UIImage and Base64 string

Swift 4.2 | Xcode 10

extension UIImage {

    /// EZSE: Returns base64 string
    public var base64: String {
        return self.jpegData(compressionQuality: 1.0)!.base64EncodedString()
    }
}

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

VBA error 1004 - select method of range class failed

You have to select the sheet before you can select the range.

I've simplified the example to isolate the problem. Try this:

Option Explicit


Sub RangeError()

    Dim sourceBook As Workbook
    Dim sourceSheet As Worksheet
    Dim sourceSheetSum As Worksheet

    Set sourceBook = ActiveWorkbook
    Set sourceSheet = sourceBook.Sheets("Sheet1")
    Set sourceSheetSum = sourceBook.Sheets("Sheet2")

    sourceSheetSum.Select

    sourceSheetSum.Range("C3").Select           'THIS IS THE PROBLEM LINE

End Sub

Replace Sheet1 and Sheet2 with your sheet names.

IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.

Null check in an enhanced for loop

With Java 8 Optional:

for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
    // do whatever
}

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

How to set ANDROID_HOME path in ubuntu?

sudo su -
gedit ~/.bashrc
export PATH=${PATH}:/your path
export PATH=${PATH}:/your path
export PATH=${PATH}:/opt/workspace/android/android-sdk-linux/tools
export PATH=${PATH}:/opt/workspace/android/android-sdk-linux/platform-tools

How to refresh or show immediately in datagridview after inserting?

Try refreshing the datagrid after each insert

datagridview1.update();
datagridview1.refresh();  

Hope this helps you!

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Since Facebook's Android SDK v4.0 (see changelog) you need to execute the following:

LoginManager.getInstance().logOut();

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Javascript array sort and unique

You can now achieve the result in just one line of code.

Using new Set to reduce the array to unique set of values. Apply the sort method after to order the string values.

var myData=['237','124','255','124','366','255']

var uniqueAndSorted = [...new Set(myData)].sort() 

UPDATED for newer methods introduced in JavaScript since time of question.

tar: file changed as we read it

I am not sure does it suit you but I noticed that tar does not fail on changed/deleted files in pipe mode. See what I mean.

Test script:

#!/usr/bin/env bash
set -ex
tar cpf - ./files | aws s3 cp - s3://my-bucket/files.tar
echo $?

Deleting random files manually...

Output:

+ aws s3 cp - s3://my-bucket/files.tar
+ tar cpf - ./files
tar: ./files/default_images: File removed before we read it
tar: ./files: file changed as we read it
+ echo 0
0

How to close existing connections to a DB

In more recent versions of SQL Server Management studio, you can now right click on a database and 'Take Database Offline'. This gives you the option to Drop All Active Connections to the database.

how to print an exception using logger?

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());

How to display a PDF via Android web browser without "downloading" first

You can use this

webView.loadUrl("https://docs.google.com/viewer?url=" + "url of pdf file"); 

How can I make a menubar fixed on the top while scrolling

This should get you started

 <div class="menuBar">
        <img class="logo" src="logo.jpg"/>
        <div class="nav"> 
            <ul>
                <li>Menu1</li>
                <li>Menu 2</li>
                <li>Menu 3</li>
            </ul> 
        </div>
    </div>



body{
    margin-top:50px;}
.menuBar{
    width:100%;
    height:50px;
    display:block;
    position:absolute;
    top:0;
    left:0;
    }
.logo{
    float:left;
    }
.nav{
    float:right;
    margin-right:10px;}
.nav ul li{
    list-style:none;
    float:left;
    }

Can't update: no tracked branch

Create a new folder and run git init in it.

Then try git remote add origin <your-repository-url>.

Copy all the files in your project folder to the new folder, except the .git folder (it may be invisible).

Then you can push your code by doing:
git add --all; or git add -A;
git commit -m "YOUR MESSAGE";
git push -u origin master.

I think it will work!

StringBuilder vs String concatenation in toString() in Java

I think we should go with StringBuilder append approach. Reason being :

  1. The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects.

  2. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.

How do I set path while saving a cookie value in JavaScript?

simply: document.cookie="name=value;path=/";

There is a negative point to it

Now, the cookie will be available to all directories on the domain it is set from. If the website is just one of many at that domain, it’s best not to do this because everyone else will also have access to your cookie information.

How can I escape a double quote inside double quotes?

Use a backslash:

echo "\""     # Prints one " character.

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

How to split a string into a list?

I think you are confused because of a typo.

Replace print(words) with print(word) inside your loop to have every word printed on a different line

Disabled form fields not submitting data

Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:

<input type="text" class="disable">

.disable{
pointer-events:none;
background:grey;
}

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Find by key deep in a nested array

This piece of code allows you to get all objects within a JSON whose key is user-defined.

function main(obj = {}, property){
 const views = [];

 function traverse(o) {
    for (var i in o) {
      if(i === property) views.push(o[i]);
      if (!!o[i] && typeof(o[i])=="object") {
        console.log(i, o[i]);
        traverse(o[i]);
      } else {
        console.log(i, o[i]);
      }
    }
    }

  traverse(obj);
  return views;

}



Here is an example:

const obj = {
    id: 'id at level 1',
    level2: {
      id: 'id at level 2',
      level3: {
        id: 'id at level 3',
        level4: {
          level5: {
            id: 'id at level 5'
          }
       }
    }
  },
  text: ''
}

main(obj, 'id');

how to include js file in php?

In your example you use the href attribute to tell where the JavaScript file can be found. This should be the src attribute:

?> <script type="text/javascript" src="file.js"></script> <?php

For more information see w3schools.

Progress during large file copy (Copy-Item & Write-Progress?)

Alternativly this option uses the native windows progress bar...

$FOF_CREATEPROGRESSDLG = "&H0&"

$objShell = New-Object -ComObject "Shell.Application"

$objFolder = $objShell.NameSpace($DestLocation) 

$objFolder.CopyHere($srcFile, $FOF_CREATEPROGRESSDLG)

How to pass command line arguments to a shell alias?

You may also find this command useful:

mkdir dirname && cd $_

where dirname is the name of the directory you want to create

Why is division in Ruby returning an integer instead of decimal value?

Change the 5 to 5.0. You're getting integer division.

Generate insert script for selected records?

If you are using Oracle SQL Developer then it would be

select /*insert*/ * from TABLE_NAME where COLUMN_NAME = 'VALUE';

Run this as a script

How to execute a stored procedure inside a select query

Create a dynamic view and get result from it.......

CREATE PROCEDURE dbo.usp_userwise_columns_value
(
    @userid BIGINT
)
AS 
BEGIN
        DECLARE @maincmd NVARCHAR(max);
        DECLARE @columnlist NVARCHAR(max);
        DECLARE @columnname VARCHAR(150);
        DECLARE @nickname VARCHAR(50);

        SET @maincmd = '';
        SET @columnname = '';
        SET @columnlist = '';
        SET @nickname = '';

        DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD
        FOR
            SELECT columnname , nickname
            FROM dbo.v_userwise_columns 
            WHERE userid = @userid

        OPEN CUR_COLUMNLIST
        IF @@ERROR <> 0
            BEGIN
                ROLLBACK
                RETURN
            END   

        FETCH NEXT FROM CUR_COLUMNLIST
        INTO @columnname, @nickname

        WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @columnlist = @columnlist + @columnname + ','

                FETCH NEXT FROM CUR_COLUMNLIST
                INTO @columnname, @nickname
            END
        CLOSE CUR_COLUMNLIST
        DEALLOCATE CUR_COLUMNLIST  

        IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
            BEGIN
                SET @maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' 
                            + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' 
                            + @columnlist + ' compcode FROM dbo.SJOTran '
            END
        ELSE
            BEGIN
                SET @maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' 
                            + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' 
                            + @columnlist + ' compcode FROM dbo.SJOTran '
            END

        EXECUTE sp_executesql @maincmd
END

-----------------------------------------------
SELECT * FROM dbo.v_userwise_columns_value

What possibilities can cause "Service Unavailable 503" error?

Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.

This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.

Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.

Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks

How to force a UIViewController to Portrait orientation in iOS 6

For Monotouch you could do it this way:

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
    {
    return UIInterfaceOrientationMask.LandscapeRight;
}

public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation()
    {
    return UIInterfaceOrientation.LandscapeRight;
}

Django CSRF Cookie Not Set

try to check if your have installed in the settings.py

 MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',)

In the template the data are formatted with the csrf_token:

<form>{% csrf_token %}
</form>

How do I pass JavaScript values to Scriptlet in JSP?

If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.

Other wise you can't do it.

How to create module-wide variables in Python?

Steveha's answer was helpful to me, but omits an important point (one that I think wisty was getting at). The global keyword is not necessary if you only access but do not assign the variable in the function.

If you assign the variable without the global keyword then Python creates a new local var -- the module variable's value will now be hidden inside the function. Use the global keyword to assign the module var inside a function.

Pylint 1.3.1 under Python 2.7 enforces NOT using global if you don't assign the var.

module_var = '/dev/hello'

def readonly_access():
    connect(module_var)

def readwrite_access():
    global module_var
    module_var = '/dev/hello2'
    connect(module_var)

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

rbenv not changing ruby version

There a lot of of misleading answers that work. I thought it was worth mentioning the steps from the rbenv README.

  1. $ brew install rbenv
  2. $ rbenv init and follow the instructions it gives you. This is what I got:
~ $ rbenv init
# Load rbenv automatically by appending
# the following to ~/.bash_profile:

eval "$(rbenv init -)"

I updated my ~/.bash_profile...

  1. Close terminal and open it again
  2. Verify it's working correctly by running:
$ curl -fsSL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-doctor | bash
  1. Now just install the version you want by doing: rbenv install <version>

INNER JOIN same table

I think the problem is in your JOIN condition.

SELECT user.user_fname,
       user.user_lname,
       parent.user_fname,
       parent.user_lname
FROM users AS user
JOIN users AS parent 
  ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]

Edit: You should probably use LEFT JOIN if there are users with no parents.

what is the most efficient way of counting occurrences in pandas?

Just an addition to the previous answers. Let's not forget that when dealing with real data there might be null values, so it's useful to also include those in the counting by using the option dropna=False (default is True)

An example:

>>> df['Embarked'].value_counts(dropna=False)
S      644
C      168
Q       77
NaN      2

Color different parts of a RichTextBox string

Selecting text as said from somebody, may the selection appear momentarily. In Windows Forms applications there is no other solutions for the problem, but today I found a bad, working, way to solve: you can put a PictureBox in overlapping to the RichtextBox with the screenshot of if, during the selection and the changing color or font, making it after reappear all, when the operation is complete.

Code is here...

//The PictureBox has to be invisible before this, at creation
//tb variable is your RichTextBox
//inputPreview variable is your PictureBox
using (Graphics g = inputPreview.CreateGraphics())
{
    Point loc = tb.PointToScreen(new Point(0, 0));
    g.CopyFromScreen(loc, loc, tb.Size);
    Point pt = tb.GetPositionFromCharIndex(tb.TextLength);
    g.FillRectangle(new SolidBrush(Color.Red), new Rectangle(pt.X, 0, 100, tb.Height));
}
inputPreview.Invalidate();
inputPreview.Show();
//Your code here (example: tb.Select(...); tb.SelectionColor = ...;)
inputPreview.Hide();

Better is to use WPF; this solution isn't perfect, but for Winform it works.

Removing the textarea border in HTML

In CSS:

  textarea { 
    border-style: none; 
    border-color: Transparent; 
    overflow: auto;        
  }

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

Now we know what the actual error is can formulate an answer.

Not allowed to load local resource

is a Security exception built into Chrome and other modern browsers. The wording may be different but in some way shape or form they all have security exceptions in place to deal with this scenario.

In the past you could override certain settings or apply certain flags such as

--disable-web-security --allow-file-access-from-files --allow-file-access

in Chrome (See https://stackoverflow.com/a/22027002/692942)

It's there for a reason

At this point though it's worth pointing out that these security exceptions exist for good reason and trying to circumvent them isn't the best idea.

There is another way

As you have access to Classic ASP already you could always build a intermediary page that serves the network based files. You do this using a combination of the ADODB.Stream object and the Response.BinaryWrite() method. Doing this ensures your network file locations are never exposed to the client and due to the flexibility of the script it can be used to load resources from multiple locations and multiple file types.

Here is a basic example (getfile.asp);

<%
Option Explicit

Dim s, id, bin, file, filename, mime

id = Request.QueryString("id")

'id can be anything just use it as a key to identify the 
'file to return. It could be a simple Case statement like this
'or even pulled from a database.
Select Case id
Case "TESTFILE1"
  'The file, mime and filename can be built-up anyway they don't 
  'have to be hard coded.
  file = "\\server\share\Projecten\Protocollen\346\Uitvoeringsoverzicht.xls"     
  mime = "application/vnd.ms-excel"
  'Filename you want to display when downloading the resource.
  filename = "Uitvoeringsoverzicht.xls"

'Assuming other files 
Case ...
End Select

If Len(file & "") > 0 Then
  Set s = Server.CreateObject("ADODB.Stream")
  s.Type = adTypeBinary 'adTypeBinary = 1 See "Useful Links"
  Call s.Open()
  Call s.LoadFromFile(file)
  bin = s.Read()

  'Clean-up the stream and free memory
  Call s.Close()
  Set s = Nothing

  'Set content type header based on mime variable
  Response.ContentType = mime
  'Control how the content is returned using the 
  'Content-Disposition HTTP Header. Using "attachment" forces the resource
  'to prompt the client to download while "inline" allows the resource to
  'download and display in the client (useful for returning images
  'as the "src" of a <img> tag).
  Call Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
  Call Response.BinaryWrite(bin)
Else
  'Return a 404 if there's no file.
  Response.Status = "404 Not Found"
End If
%>

This example is pseudo coded and as such is untested.

This script can then be used in <a> like this to return the resource;

<a href="/getfile.asp?id=TESTFILE1">Click Here</a>

The could take this approach further and consider (especially for larger files) reading the file in chunks using Response.IsConnected to check whether the client is still there and s.EOS property to check for the end of the stream while the chunks are being read. You could also add to the querystring parameters to set whether you want the file to return in-line or prompt to be downloaded.


Useful Links

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

How to iterate for loop in reverse order in swift?

You can use reversed() method for easily reverse values.

var i:Int
for i in 1..10.reversed() {
    print(i)
}

The reversed() method reverse the values.

How to convert list of key-value tuples into dictionary?

l=[['A', 1], ['B', 2], ['C', 3]]
d={}
for i,j in l:
d.setdefault(i,j)
print(d)

Sum of Numbers C++

First, you have two variables of the same name i. This calls for confusion.

Second, you should declare a variable called sum, which is initially zero. Then, in a loop, you should add to it the numbers from 1 upto and including positiveInteger. After that, you should output the sum.

Send email with PHP from html form on submit with the same script

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

How do I use this JavaScript variable in HTML?

The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.

The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.

There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).

Examples for both options:

_x000D_
_x000D_
<script>_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
</script>_x000D_
<body>_x000D_
  <p id="a"></p>_x000D_
  <p id="b"></p>_x000D_
  <script>_x000D_
    document.getElementById('a').innerHTML = name;_x000D_
document.querySelector('#b').innerHTML = name.length;</script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

adding multiple entries to a HashMap at once in one statement

Here's a simple class that will accomplish what you want

import java.util.HashMap;

public class QuickHash extends HashMap<String,String> {
    public QuickHash(String...KeyValuePairs) {
        super(KeyValuePairs.length/2);
        for(int i=0;i<KeyValuePairs.length;i+=2)
            put(KeyValuePairs[i], KeyValuePairs[i+1]);
    }
}

And then to use it

Map<String, String> Foo=QuickHash(
    "a", "1",
    "b", "2"
);

This yields {a:1, b:2}

How do I use spaces in the Command Prompt?

It can solve this problem by cd command, this command understand spaces without double quotes and you can call any program this way for example:

C:\Windows\system32>cd c:\Program Files\MongoDB\Server\3.2\bin

c:\Program Files\MongoDB\Server\3.2\bin>mongo now command prompt call mongo.exe

onclick event function in JavaScript

Check you are calling same function or not.

<script>function greeting(){document.write("hi");}</script>

<input type="button" value="Click Here" onclick="greeting();"/>

Why use Ruby's attr_accessor, attr_reader and attr_writer?

Not all attributes of an object are meant to be directly set from outside the class. Having writers for all your instance variables is generally a sign of weak encapsulation and a warning that you're introducing too much coupling between your classes.

As a practical example: I wrote a design program where you put items inside containers. The item had attr_reader :container, but it didn't make sense to offer a writer, since the only time the item's container should change is when it's placed in a new one, which also requires positioning information.

Check if boolean is true?

i personally would prefer

if(true == foo)
{
}

there is no chance for the ==/= mistype and i find it more expressive in terms of foo's type. But it is a very subjective question.

Connect to SQL Server database from Node.js

msnodesql is working out great for me. Here is a sample:

var mssql = require('msnodesql'), 
    express = require('express'),
    app = express(),
    nconf = require('nconf')

nconf.env()
     .file({ file: 'config.json' });

var conn = nconf.get("SQL_CONN");   
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";

app.get('/api/brands', function(req, res){
    var data = [];
    var jsonObject = {};    

    mssql.open(conn_str, function (err, conn) {
        if (err) {
            console.log("Error opening the connection!");
            return;
        }
        conn.queryRaw("dbo.storedproc", function (err, results) {
        if(err) {
                   console.log(err);
                   res.send(500, "Cannot retrieve records.");
                }
       else {
             //res.json(results);

             for (var i = 0; i < results.rows.length; i++) {
                 var jsonObject = new Object()
                 for (var j = 0; j < results.meta.length; j++) { 

                    paramName = results.meta[j].name;
                    paramValue = results.rows[i][j]; 
                    jsonObject[paramName] = paramValue;

                    }
                    data.push(jsonObject);  //This is a js object we are jsonizing not real json until res.send             
            } 

                res.send(data);

            }       
        });
    });
});

Install msi with msiexec in a Specific Directory

msiexec /i "msi path" INSTALLDIR="C:\myfolder" /q

Only this variant worked well.

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Cracked it. Just @Damnum steps and then follow the path to run xcode. Bad way but running like a charm.

Double click to /Applications/Xcode102.app/Contents/MacOS/Xcode

What are the advantages of NumPy over regular Python lists?

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04

C# Copy a file to another location with a different name

File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt", true);

Please do not forget to overwrite the previous file! Make sure you add the third param., by adding the third param, you allow the file to be overwritten. Else you could use a try catch for the exception.

Regards, G

Check if a string has white space

With additions to the language it is much easier, plus you can take advantage of early return:

// Use includes method on string
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return whitespaceChars.some(char => s.includes(char));
}

// Use character comparison
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return Array.from(s).some(char => whitespaceChars.includes(char));
}

const withSpace = "Hello World!";
const noSpace = "HelloWorld!";

console.log(hasWhiteSpace(withSpace));
console.log(hasWhiteSpace(noSpace));

console.log(hasWhiteSpace2(withSpace));
console.log(hasWhiteSpace2(noSpace));

I did not run performance benchmark but these should be faster than regex but for small text snippets there won't be that much difference anyway.

How to initialize an array in one step using Ruby?

You can use an array literal:

array = [ '1', '2', '3' ]

You can also use a range:

array = ('1'..'3').to_a  # parentheses are required
# or
array = *('1'..'3')      # parentheses not required, but included for clarity

For arrays of whitespace-delimited strings, you can use Percent String syntax:

array = %w[ 1 2 3 ]

You can also pass a block to Array.new to determine what the value for each entry will be:

array = Array.new(3) { |i| (i+1).to_s }

Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:

array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]

Design DFA accepting binary strings divisible by a number 'n'

Below, I have written an answer for n equals to 5, but you can apply same approach to draw DFAs for any value of n and 'any positional number system' e.g binary, ternary...

First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).

Design DFA accepting Binary numbers divisible by number 'n':

Step-1: When you divide a number ? by n then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0 that means ? is divisible by n otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r, where 0 <= r <= (n - 1), and total number of states in DFA is n.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).

In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:

  1. State q0 reached if reminder is 0. State q0 is the final state(accepting state). It is also an initial state.
  2. State q1 reaches if reminder is 1, a non-final state.
  3. State q2 if reminder is 2, a non-final state.
  4. State q3 if reminder is 3, a non-final state.
  5. State q4 if reminder is 4, a non-final state.

Using above information, we can start drawing transition diagram TD of five states as follows:

fig-1
Figure-1

So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0' at state q0, this is because decimal equivalent of any string consist of only '0' is 0 and 0 is a divisible by n.

Step-2: TD above is incomplete; and can only process strings of '0's. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:

+-------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦
+------+------+-------------+---------¦
¦One   ¦1     ¦1            ¦q1       ¦
+------+------+-------------+---------¦
¦Two   ¦10    ¦2            ¦q2       ¦
+------+------+-------------+---------¦
¦Three ¦11    ¦3            ¦q3       ¦
+------+------+-------------+---------¦
¦Four  ¦100   ¦4            ¦q4       ¦
+-------------------------------------+
  1. To process binary string '1' there should be a transition rule d:(q0, 1)?q1
  2. Two:- binary representation is '10', end-state should be q2, and to process '10', we just need to add one more transition rule d:(q1, 0)?q2
    Path: ?(q0)-1?(q1)-0?(q2)
  3. Three:- in binary it is '11', end-state is q3, and we need to add a transition rule d:(q1, 1)?q3
    Path: ?(q0)-1?(q1)-1?(q3)
  4. Four:- in binary '100', end-state is q4. TD already processes prefix string '10' and we just need to add a new transition rule d:(q2, 0)?q4
    Path: ?(q0)-1?(q1)-0?(q2)-0?(q4)

fig-2 Figure-2

Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'.
Because '101' = 5 is divisible by 5, and to accept '101' I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:

fig-3 Figure-3

Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.

Step-4: Six = 110.

We can process '11' in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.

fig-4 Figure-4

Step-5: Seven = 111

+--------------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path       ¦ Add       ¦
+------+------+-------------+---------+------------+-----------¦
¦Seven ¦111   ¦7 % 5 = 2    ¦q2       ¦ q0-11?q3   ¦ q3-1?q2    ¦
+--------------------------------------------------------------+

fig-5 Figure-5

Step-6: Eight = 1000

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Eight ¦1000  ¦8 % 5 = 3    ¦q3       ¦q0-100?q4 ¦ q4-0?q3  ¦
+----------------------------------------------------------+

fig-6 Figure-6

Step-7: Nine = 1001

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Nine  ¦1001  ¦9 % 5 = 4    ¦q4       ¦q0-100?q4 ¦ q4-1?q4  ¦
+----------------------------------------------------------+

fig-7 Figure-7

In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.

Design DFA accepting Ternary numbers divisible by number n:

Step-1 Exactly same as for binary, use figure-1.

Step-2 Add Zero, One, Two

+------------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦   Add        ¦
+-------+-------+-------------+---------+--------------¦
¦Zero   ¦0      ¦0            ¦q0       ¦ d:(q0,0)?q0  ¦
+-------+-------+-------------+---------+--------------¦
¦One    ¦1      ¦1            ¦q1       ¦ d:(q0,1)?q1  ¦
+-------+-------+-------------+---------+--------------¦
¦Two    ¦2      ¦2            ¦q2       ¦ d:(q0,2)?q3  ¦
+------------------------------------------------------+

fig-8
Figure-8

Step-3 Add Three, Four, Five

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Three  ¦10     ¦3            ¦q3       ¦ d:(q1,0)?q3 ¦
+-------+-------+-------------+---------+-------------¦
¦Four   ¦11     ¦4            ¦q4       ¦ d:(q1,1)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Five   ¦12     ¦0            ¦q0       ¦ d:(q1,2)?q0 ¦
+-----------------------------------------------------+

fig-9
Figure-9

Step-4 Add Six, Seven, Eight

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Six    ¦20     ¦1            ¦q1       ¦ d:(q2,0)?q1 ¦
+-------+-------+-------------+---------+-------------¦
¦Seven  ¦21     ¦2            ¦q2       ¦ d:(q2,1)?q2 ¦
+-------+-------+-------------+---------+-------------¦
¦Eight  ¦22     ¦3            ¦q3       ¦ d:(q2,2)?q3 ¦
+-----------------------------------------------------+

fig-10
Figure-10

Step-5 Add Nine, Ten, Eleven

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Nine   ¦100    ¦4            ¦q4       ¦ d:(q3,0)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Ten    ¦101    ¦0            ¦q0       ¦ d:(q3,1)?q0 ¦
+-------+-------+-------------+---------+-------------¦
¦Eleven ¦102    ¦1            ¦q1       ¦ d:(q3,2)?q1 ¦
+-----------------------------------------------------+

fig-11
Figure-11

Step-6 Add Twelve, Thirteen, Fourteen

+------------------------------------------------------+
¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+--------+-------+-------------+---------+-------------¦
¦Twelve  ¦110    ¦2            ¦q2       ¦ d:(q4,0)?q2 ¦
+--------+-------+-------------+---------+-------------¦
¦Thirteen¦111    ¦3            ¦q3       ¦ d:(q4,1)?q3 ¦
+--------+-------+-------------+---------+-------------¦
¦Fourteen¦112    ¦4            ¦q4       ¦ d:(q4,2)?q4 ¦
+------------------------------------------------------+

fig-12
Figure-12

Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r)!

To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).

If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).

Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n and base b read paper: Divisibility and State Complexity.

below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.

Design DFA for base 'b' number strings divisible by number 'n':

So we can apply above trick to draw DFA to recognize number strings in any base 'b' those are divisible a given number 'n'. In that DFA total number of states will be n (for n remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.

Using above trick, below I have written a Python Script to Draw DFA for input base and number. In script, function divided_by_N populates DFA's transition rules in base * number steps. In each step-num, I convert num into number string num_s using function baseN(). To avoid processing each number string, I have used a temporary data-structure lookup_table. In each step, end-state for number string num_s is evaluated and stored in lookup_table to use in next step.

For transition graph of DFA, I have written a function draw_transition_graph using Pygraphviz library (very easy to use). To use this script you need to install graphviz. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict function.

#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice

def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    """ converts a number `n` into base `b` string """
    return ((n == 0) and syms[0]) or (
        baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])

def divided_by_N(number, base):
    """
    constructs DFA that accepts given `base` number strings
    those are divisible by a given `number`
    """
    ACCEPTING_STATE = START_STATE = '0'
    SYMBOL_0 = '0'
    dfa = {
        str(from_state): {
            str(symbol): 'to_state' for symbol in range(base)
        }
        for from_state in range(number)
    }
    dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
    # `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
    lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
    for num in range(number * base):
        end_state = str(num % number)
        num_s = baseN(num, base)
        before_end_state = lookup_table(num_s[:-1], START_STATE)
        dfa[before_end_state][num_s[-1]] = end_state
        lookup_table(num_s, end_state)
    return dfa

def symcolrhexcodes(symbols):
    """
    returns dict of color codes mapped with alphabets symbol in symbols
    """
    return {
        symbol: '#'+''.join([
            rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
        ])
        for symbol in symbols
    }

def draw_transition_graph(dfa, filename="filename"):
    ACCEPTING_STATE = START_STATE = '0'
    colors = symcolrhexcodes(dfa[START_STATE].keys())
    # draw transition graph
    tg = pgv.AGraph(strict=False, directed=True, decorate=True)
    for from_state in dfa:
        for symbol, to_state in dfa[from_state].iteritems():
            tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
                        label=symbol, color=colors[symbol],
                        fontcolor=colors[symbol])

    # add intial edge from an invisible node!
    tg.add_node('null', shape='plaintext', label='start')
    tg.add_edge('null', "Q%s"%START_STATE,)

    # make end acception state as 'doublecircle'
    tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
    tg.draw(filename, prog='circo')
    tg.close()

def print_transition_table(dfa):
    print("DFA accepting number string in base '%(base)s' "
            "those are divisible by '%(number)s':" % {
                'base': len(dfa['0']),
                'number': len(dfa),})
    pprint(dfa)

if __name__ == "__main__":
    number = input ("Enter NUMBER: ")
    base = input ("Enter BASE of number system: ")
    dfa = divided_by_N(number, base)

    print_transition_table(dfa)
    draw_transition_graph(dfa)

Execute it:

~/study/divide-5/script$ python script.py 
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
 '1': {'0': '4', '1': '0', '2': '1', '3': '2'},
 '2': {'0': '3', '1': '4', '2': '0', '3': '1'},
 '3': {'0': '2', '1': '3', '2': '4', '3': '0'},
 '4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename

Output:

base_4_divided_5_best
DFA accepting number strings in base 4 those are divisible by 5

Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename to .png or .jpeg.

References those I use to write this script:
➊ Function baseN from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"

What, why or when it is better to choose cshtml vs aspx?

Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.

Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.

Imagine that you want to get a Human class, and render it. In cshtml files you write:

<div>Name is @Model.Name</div>

While in aspx files you write:

<div>Name is <%= Human.Name %></div>

As you can see, @ sign of razor makes mixing code and markup much easier.

How to build a RESTful API?

I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini lib for PHP allows you to easily transform MySQL databases into web accessible JSON APIs.

How to send json data in POST request using C#

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

Setting active profile and config location from command line in spring boot

Michael Yin's answer is correct but a better explanation seems to be required!

A lot of you mentioned that -D is the correct way to specify JVM parameters and you are absolutely right. But Michael is also right as mentioned in Spring Boot Profiles documentation.

What is not clear in the documentation, is what kind of parameter it is: --spring.profiles.active is a not a standard JVM parameter so if you want to use it in your IDE fill the correct fields (i.e. program arguments)

Google Maps API v3: How to remove all markers?

It seems that there is no such function in V3 yet.

People suggest to keep references to all markers you have on the map in an array. And then when you want to delete em all, just loop trough the array and call .setMap(null) method on each of the references.

See this question for more info/code.

My version:

google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i<this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;

google.maps.Marker.prototype.setMap = function(map) {
    if (map) {
        map.markers[map.markers.length] = this;
    }
    this._setMap(map);
}

The code is edited version of this code http://www.lootogo.com/googlemapsapi3/markerPlugin.html I removed the need to call addMarker manually.

Pros

  • Doing this way you keep the code compact and in one place (doesn't pollute the namespace).
  • You don't have to keep track of the markers yourself anymore you can always find all the markers on the map by calling map.getMarkers()

Cons

  • Using prototypes and wrappers like I did now makes my code dependent on Google code, if they make a mayor change in their source this will break.
  • If you don't understand it then you won't be able to fix it if does break. The chances are low that they're going to change anything which will break this, but still..
  • If you remove one marker manually, it's reference will still be in markers array. (You could edit my setMap method to fix it, but at the cost of looping trough markers array and removing the reference)

conversion from string to json object android

Here is the code, and you can decide which
(synchronized)StringBuffer or faster StringBuilder to use.

Benchmark shows StringBuilder is Faster.

public class Main {
            int times = 777;
            long t;

            {
                StringBuffer sb = new StringBuffer();
                t = System.currentTimeMillis();
                for (int i = times; i --> 0 ;) {
                    sb.append("");
                    getJSONFromStringBuffer(String stringJSON);
                }
                System.out.println(System.currentTimeMillis() - t);
            }

            {
                StringBuilder sb = new StringBuilder();
                t = System.currentTimeMillis();
                for (int i = times; i --> 0 ;) {
                     getJSONFromStringBUilder(String stringJSON);
                    sb.append("");
                }
                System.out.println(System.currentTimeMillis() - t);
            }
            private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
                return new StringBuffer(
                       new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
                           .append(" ")
                           .append(
                       new JSONArray(employeeID).getJSONObject(0).getString("cat"))
                      .toString();
            }
            private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
                return new StringBuffer(
                       new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
                           .append(" ")
                           .append(
                       new JSONArray(employeeID).getJSONObject(0).getString("cat"))
                      .toString();
            }
        }

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

Force youtube embed to start in 720p

The first example below does not work for me, but the second one does (in Chrome).

<iframe width="720" height="405" src="//www.youtube.com/embed/GX_c566xYcQ?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>
<iframe width="720" height="405" src="//youtube.com/v/IplDUxTQxsE?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>

I believe the first one uses the new HTML5 youtube player whereas the bottom one (which works) uses the older flash player. However, the second one doesn't seem to load correctly in Safari/Firefox etc so probably not usable.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

To this error:

# git pull
sign_and_send_pubkey: signing failed: agent refused operation
[email protected]: Permission denied (publickey).    
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

Verify or add again the public key in Github account > profile > ssh.

I solved like this:

# chmod 400 ~/.ssh/id_rsa

# ls  ~/.ssh/id_rsa -ls  
4 -r--------. 1 reinaldo reinaldo 1679 Jul 26  2017 /home/reinaldo/.ssh/id_rsa

# git pull                                 
remote: Counting objects: 35, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 35 (delta 9), reused 34 (delta 9), pack-reused 0
Unpacking objects: 100% (35/35), done.

Thank you.

How to store directory files listing into an array?

I'd use

files=(*)

And then if you need data about the file, such as size, use the stat command on each file.

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

How to display PDF file in HTML?

Portable Document Format (PDF).

  • Any Browser « Use _Embeddable Google Document Viewer to embed the PDF file in iframe.

    <iframe src="http://docs.google.com/gview?
        url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true"
        style="width:600px; height:500px;" frameborder="0">
    </iframe>
    
  • Only for chrome browser « Chrome PDF viewer using plugin. pluginspage=http://www.adobe.com/products/acrobat/readstep2.html.

    <embed type="application/pdf" 
    src="http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-guide-1720064.pdf" 
    width="100%" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html" 
    background-color="0xFF525659" top-toolbar-height="56" full-frame="" internalinstanceid="21" 
    title="CHROME">
    

Example Sippet:

_x000D_
_x000D_
<html>_x000D_
   <head></head>_x000D_
   <body style=" height: 100%;">_x000D_
      <div style=" position: relative;">_x000D_
      <div style="width: 100%; /*overflow: auto;*/ position: relative;height: auto; margin-top: 70px;">_x000D_
         <p>An _x000D_
            <a href="https://en.wikipedia.org/wiki/Image_file_formats" >image</a> is an artifact that depicts visual perception_x000D_
         </p>_x000D_
         <!-- To make div with scroll data [max-height: 500;]-->_x000D_
         <div style="/* overflow: scroll; */ max-height: 500; float: left; width: 49%; height: 100%; ">_x000D_
            <img width="" height="400" src="https://peach.blender.org/wp-content/uploads/poster_bunny_bunnysize.jpg?x11217" title="Google" style="-webkit-user-select: none;background-position: 0px 0px, 10px 10px;background-size: 20px 20px;background-image:linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee 100%),linear-gradient(45deg, #eee 25%, white 25%, white 75%, #eee 75%, #eee 100%);cursor: zoom-in;" />_x000D_
            <p>Streaming an Image form Response Stream (binary data) «  This buffers the output in smaller chunks of data rather than sending the entire image as a single block. _x000D_
               <a href="http://www.chestysoft.com/imagefile/streaming.asp" >StreamToBrowser</a>_x000D_
            </p>_x000D_
         </div>_x000D_
         <div style="float: left; width: 10%; background-color: red;"></div>_x000D_
         <div style="float: left;width: 49%; ">_x000D_
            <img width="" height="400" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot"/>_x000D_
            <p>Streaming an Image form Base64 String « embedding images directly into your HTML._x000D_
               <a href="https://en.wikipedia.org/wiki/Data_URI_scheme">_x000D_
               <sup>Data URI scheme</sup>_x000D_
               </a>_x000D_
               <a href="https://codebeautify.org/image-to-base64-converter">_x000D_
               <sup>, Convert Your Image to Base64</sup>_x000D_
               </a>_x000D_
            <pre>data:[&lt;media type&gt;][;base64],&lt;data&gt;</pre>_x000D_
            </p>_x000D_
         </div>_x000D_
      </div>_x000D_
      <div style="width: 100%;overflow: auto;position: relative;height: auto; margin-top: 70px;">_x000D_
      <video style="height: 500px;width: 100%;" name="media" controls="controls">_x000D_
         <!-- autoplay -->_x000D_
         <source src="http://download.blender.org/peach/trailer/trailer_400p.ogg" type="video/mp4">_x000D_
         <source src="http://download.blender.org/peach/trailer/trailer_400p.ogg" type="video/ogg">_x000D_
      </video>_x000D_
      <p>Video courtesy of _x000D_
         <a href="https://www.bigbuckbunny.org/" >Big Buck Bunny</a>._x000D_
      </p>_x000D_
      <div>_x000D_
         <div style="width: 100%;overflow: auto;position: relative;height: auto; margin-top: 70px;">_x000D_
            <p>Portable Document Format _x000D_
               <a href="https://acrobat.adobe.com/us/en/acrobat/about-adobe-pdf.html?promoid=CW7625ZK&mv=other" >(PDF)</a>._x000D_
            </p>_x000D_
            <div style="float: left;width: 49%; overflow: auto;position: relative;height: auto;">_x000D_
               <embed type="application/pdf" src="http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-guide-1720064.pdf" width="100%" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html" background-color="0xFF525659" top-toolbar-height="56" full-frame="" internalinstanceid="21" title="CHROME">_x000D_
               <p>Chrome PDF viewer _x000D_
                  <a href="https://productforums.google.com/forum/#!topic/chrome/MP_1qzVgemo">_x000D_
                  <sup>extension</sup>_x000D_
                  </a>_x000D_
                  <a href="https://chrome.google.com/webstore/detail/surfingkeys/gfbliohnnapiefjpjlpjnehglfpaknnc">_x000D_
                  <sup> (surfingkeys)</sup>_x000D_
                  </a>_x000D_
               </p>_x000D_
            </div>_x000D_
            <div style="float: left; width: 10%; background-color: red;"></div>_x000D_
            <div style="float: left;width: 49%; ">_x000D_
               <iframe src="https://docs.google.com/gview?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true#:page.7" style="" width="100%" height="500px" allowfullscreen="" webkitallowfullscreen=""></iframe>_x000D_
               <p>Embeddable _x000D_
                  <a href="https://googlesystem.blogspot.in/2009/09/embeddable-google-document-viewer.html" >Google</a> Document Viewer. Here's the code I used to embed the PDF file: _x000D_
<pre>_x000D_
&lt;iframe _x000D_
src="http://docs.google.com/gview?_x000D_
url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" _x000D_
style="width:600px; height:500px;" frameborder="0"&gt;&lt;/iframe&gt;_x000D_
</pre>_x000D_
               </p>_x000D_
            </div>_x000D_
         </div>_x000D_
      </div>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Finding an element in an array in Java

Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.

Get element type with jQuery

you should use tagName property and attr('type') for inputs

How do I compare two variables containing strings in JavaScript?

=== is not necessary. You know both values are strings so you dont need to compare types.

_x000D_
_x000D_
function do_check()_x000D_
{_x000D_
  var str1 = $("#textbox1").val();_x000D_
  var str2 = $("#textbox2").val();_x000D_
_x000D_
  if (str1 == str2)_x000D_
  {_x000D_
    $(":text").removeClass("incorrect");_x000D_
    alert("equal");_x000D_
  }_x000D_
  else_x000D_
  {_x000D_
    $(":text").addClass("incorrect");_x000D_
    alert("not equal");_x000D_
  }_x000D_
}
_x000D_
.incorrect_x000D_
{_x000D_
  background: #ff8888;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="textbox1" type="text">_x000D_
<input id="textbox2" type="text">_x000D_
_x000D_
<button onclick="do_check()">check</button>
_x000D_
_x000D_
_x000D_

Parse an HTML string with JS

EDIT: The solution below is only for HTML "fragments" since html,head and body are removed. I guess the solution for this question is DOMParser's parseFromString() method.


For HTML fragments, the solutions listed here works for most HTML, however for certain cases it won't work.

For example try parsing <td>Test</td>. This one won't work on the div.innerHTML solution nor DOMParser.prototype.parseFromString nor range.createContextualFragment solution. The td tag goes missing and only the text remains.

Only jQuery handles that case well.

So the future solution (MS Edge 13+) is to use template tag:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content.cloneNode(true);
}

var documentFragment = parseHTML('<td>Test</td>');

For older browsers I have extracted jQuery's parseHTML() method into an independent gist - https://gist.github.com/Munawwar/6e6362dbdf77c7865a99

Static constant string (class member)

The current standard only allows such initialization for static constant integral types. So you need to do as AndreyT explained. However, that will be available in the next standard through the new member initialization syntax.

The EntityManager is closed

// first need to reset current manager
$em->resetManager();
// and then get new
$em = $this->getContainer()->get("doctrine");
// or in this way, depending of your environment:
$em = $this->getDoctrine();

jQuery ui dialog change title after load-callback

Even better!

    jQuery( "#dialog" ).attr('title', 'Error');
    jQuery( "#dialog" ).text('You forgot to enter your first name');

Angular JS Uncaught Error: [$injector:modulerr]

Just throwing this in in case it helps, I had this issue and the reason for me was because when I bundled my Angular stuff I referenced the main app file as "AngularWebApp" instead of "AngularWebApp.js", hope this helps.

How do I drop a foreign key in SQL Server?

This will work:

ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

I tried to add ASP.net v4.0 with all permission, add NETWORK SERVICE user but nothing help. At last, added the MODIFY right of DefaultAppPool user in App_Data folder, problem solved.

mysql extract year from date format

try this code:

SELECT YEAR( str_to_date( subdateshow, '%m/%d/%Y' ) ) AS Mydate

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Apple has changed the rules on this. I read through all the Apple docs and as many of the US export regs as I could find.

My view on this was until recently even using HTTPS for most apps meant Apple would require the export certificate. Some apps such as banking would be OK but for many apps they did not fall into the excempt category which is very, very broad.

However Apple has now introduced a getout under the exempt category for apps that JUST use https. I do not know when they did this but I think it was either Dec 2016 or Jan 2017. We are now submitting our apps without the certificate from the US Govt.

How can I read a whole file into a string variable

I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.

buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
  f, _ := os.Open(filename) // Error handling elided for brevity.
  io.Copy(buf, f)           // Error handling elided for brevity.
  f.Close()
}
s := string(buf.Bytes())

This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.

Git command to checkout any branch and overwrite local changes

git reset and git clean can be overkill in some situations (and be a huge waste of time).

If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch> is the best option.

If you're like me, your other option was to clean and perform a --hard reset then recompile your project.

How to decrypt an encrypted Apple iTunes iPhone backup?

You should grab a copy of Erica Sadun's mdhelper command line utility (OS X binary & source). It supports listing and extracting the contents of iPhone/iPod Touch backups, including address book & SMS databases, and other application metadata and settings.

How can I ping a server port with PHP?

Try this :

echo exec('ping -n 1 -w 1 72.10.169.28');

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you want to allow all origins and keep credentials true, this worked for me:

app.use(cors({
  origin: function(origin, callback){
    return callback(null, true);
  },
  optionsSuccessStatus: 200,
  credentials: true
}));

Circular gradient in android

<gradient
    android:centerColor="#c1c1c1"
    android:endColor="#4f4f4f"
    android:gradientRadius="400"
    android:startColor="#c1c1c1"
    android:type="radial" >
</gradient>

curl POST format for CURLOPT_POSTFIELDS

Interestingly the way Postman does POST is a complete GET operation with these 2 additional options:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');

Just another way, and it works very well.

How to get main window handle from process id?

I don't believe Windows (as opposed to .NET) provides a direct way to get that.

The only way I know of is to enumerate all the top level windows with EnumWindows() and then find what process each belongs to GetWindowThreadProcessID(). This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...

How to install OpenSSL in windows 10?

I recently needed to document how to get a version of it installed, so I've copied my steps here, as the other answers were using different sources from what I recommend, which is Cygwin. I like Cygwin because it is well maintained and provides a wealth of other utilities for Windows. Cygwin also allows you to easily update the versions as needed when vulnerabilities are fixed. Please update your version of OpenSSL often!

Open a Windows Command prompt and check to see if you have OpenSSL installed by entering: openssl version

If you get an error message that the command is NOT recognized, then install OpenSSL by referring to Cygwin following the summary steps below:

Basically, download and run the Cygwin Windows Setup App to install and to update as needed the OpenSSL application:

  1. Select an install directory, such as C:\cygwin64. Choose a download mirror such as: http://mirror.cs.vt.edu
  2. Enter in openssl into the search and select it. You can also select/un-select other items of interest at this time. The click Next twice then click Finish.
  3. After installing, you need to edit the PATH variable. On Windows, you can access the System Control Center by pressing Windows Key + Pause. In the System window, click Advanced System Settings ? Advanced (tab) ? Environment Variables. For Windows 10, a quick access is to enter "Edit the system environment variables" in the Start Search of Windows and click the button "Environment Variables". Change the PATH variable (double-click on it or Select and Edit), and add the path where your Cywgwin is, e.g. C:\cygwin\bin.
  4. Verify you have it installed via a new Command Prompt window: openssl version. For example: C:\Program Files\mosquitto>openssl versionOpenSSL 1.1.1f 31 Mar 2020

Integer.valueOf() vs. Integer.parseInt()

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Mine is the console application (it should work for the windows application as well) and I had same problem. To solve it I used PlatformTarget as x64 as my System.Data.OracleClient.dll (64 bit file) is at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5. This will explicitly use 64 bit version of Oracle Client. This might help you if your solution works only on 64bit and if you are not using 32 bit dlls like dlls made in VB. I hope it will help you.

How to configure robots.txt to allow everything?

It means you allow every (*) user-agent/crawler to access the root (/) of your site. You're okay.

Django, creating a custom 500/404 error page

Official answer:

Here is the link to the official documentation on how to set up custom error views:

https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views

It says to add lines like these in your URLconf (setting them anywhere else will have no effect):

handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'

You can also customise the CSRF error view by modifying the setting CSRF_FAILURE_VIEW.

Default error handlers:

It's worth reading the documentation of the default error handlers, page_not_found, server_error, permission_denied and bad_request. By default, they use these templates if they can find them, respectively: 404.html, 500.html, 403.html, and 400.html.

So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS directory, you don't need to edit URLConf at all. Read the documentation to see which context variables are available.

In Django 1.10 and later, the default CSRF error view uses the template 403_csrf.html.

Gotcha:

Don't forget that DEBUG must be set to False for these to work, otherwise, the normal debug handlers will be used.

How to bring an activity to foreground (top of stack)?

In general I think this method of activity management is not recommended. The problem with reactivating an activity two Steps down in The Stack is that this activity has likely been killed. My advice into remember the state of your activities and launch them with startActivity ()

I'm sure you've Seen this page but for your convenience this link

How to find duplicate records in PostgreSQL

The basic idea will be using a nested query with count aggregation:

select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1

You can adjust the where clause in the inner query to narrow the search.


There is another good solution for that mentioned in the comments, (but not everyone reads them):

select Column1, Column2, count(*)
from yourTable
group by Column1, Column2
HAVING count(*) > 1

Or shorter:

SELECT (yourTable.*)::text, count(*)
FROM yourTable
GROUP BY yourTable.*
HAVING count(*) > 1

Javascript - Regex to validate date format

You can use regular multiple expressions with the use of OR (|) operator.

function validateDate(date){
    var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
    var dateOk=regex.test(date);
    if(dateOk){
        alert("Ok");
    }else{
        alert("not Ok");
    }
}

Above function can validate YYYY-MM-DD, DD-MM-YYYY date formats. You can simply extend the regular expression to validate any date format. Assume you want to validate YYYY/MM/DD, just replace "[-]" with "[-|/]". This expression can validate dates to 31, months to 12. But leap years and months ends with 30 days are not validated.

Error 1046 No database Selected, how to resolve?

If you are doing this through phpMyAdmin:

  • I'm assuming you already Created a new MySQL Database on Live Site (by live site I mean the company your hosting with (in my case Bluehost)).

  • Go to phpMyAdmin on live site - log in to the database you just created.

  • Now IMPORTANT! Before clicking the "import" option on the top bar, select your database on the left side of the page (grey bar, on the top has PHP Myadmin written, below it two options:information_schema and name of database you just logged into.

  • once you click the database you just created/logged into it will show you that database and then click the import option.

That did the trick for me. Really hope that helps

ImportError: No module named scipy

Your python don't know where you installed scipy. add the scipy path to PYTHONPATH and I hope it will solve your problem.

Create table with jQuery - append

You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.

$('#here_table').append(  '<table />' );

 for(i=0;i<3;i++){
    $('#here_table table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

The main problem was that you were appending the tr to the div here_table.

Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop

var doc = document;

var fragment = doc.createDocumentFragment();

for (i = 0; i < 3; i++) {
    var tr = doc.createElement("tr");

    var td = doc.createElement("td");
    td.innerHTML = "content";

    tr.appendChild(td);

    //does not trigger reflow
    fragment.appendChild(tr);
}

var table = doc.createElement("table");

table.appendChild(fragment);

doc.getElementById("here_table").appendChild(table);

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

ArrayIndexOutOfBoundsException means that you are trying to access an index of the array that does not exist or out of the bound of this array. Array indexes start from 0 and end at length - 1.

In your case

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}

ArrayIndexOutOfBoundsException happens when you are trying to access the name.length indexed element which does not exist (array index ends at length -1). just replacing <= with < would solve this problem.

for(int i = 0; i < name.length; i++) {
    System.out.print(name[i] +'\n');  // i goes from 0 to length - 1, Correct
}

How to get .app file of a xcode application

Build a release version, and the .app file is under build/Release folder of your project. Just copy it to Applications folder of your friend's machine. I don't think you need to build a installer.

Using set_facts and with_items together in Ansible

Looks like this behavior is how Ansible currently works, although there is a lot of interest in fixing it to work as desired. There's currently a pull request with the desired functionality so hopefully this will get incorporated into Ansible eventually.

Removing double quotes from a string in Java

Use replace method of string like the following way:

String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);

Output:

abcd

Necessary to add link tag for favicon.ico?

<link rel="icon" type="image/x-icon" href="http://example.com/favicon.ico" />
<link rel="icon" type="image/png" href="http://example.com/favicon.png" />
<link rel="icon" type="image/gif" href="http://example.com/favicon.gif" />
<link rel="icon" type="image/jpeg" href="http://example.com/favicon.jpeg" />
<link rel="icon" type="image/webp" href="http://example.com/favicon.webp" />

It all depends on which format of image you like to use!
if you have an icon of your website, it will be much better for UX!

demo

show logo in the browser tab

enter image description here

Are PHP Variables passed by value or by reference?

It's by value according to the PHP Documentation.

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}

$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

CSS display:table-row does not expand when width is set to 100%

Tested answer:

In the .view-row css, change:

display:table-row;

to:

display:table

and get rid of "float". Everything will work as expected.

As it has been suggested in the comments, there is no need for a wrapping table. CSS allows for omitting levels of the tree structure (in this case rows) that are implicit. The reason your code doesn't work is that "width" can only be interpreted at the table level, not at the table-row level. When you have a "table" and then "table-cell"s directly underneath, they're implicitly interpreted as sitting in a row.

Working example:

<div class="view">
    <div>Type</div>
    <div>Name</div>                
</div>

with css:

.view {
  width:100%;
  display:table;
}

.view > div {
  width:50%;
  display: table-cell;
}

Integer to IP Address - C

#include "stdio.h"

void print_ip(int ip) {
   unsigned char bytes[4];
   int i;
   for(i=0; i<4; i++) {
      bytes[i] = (ip >> i*8) & 0xFF;
   }
   printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);
}

int main() {
   int ip = 0xDEADBEEF;
   print_ip(ip);   
}

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

How to select only 1 row from oracle sql?

If you want to get back only the first row of a sorted result with the least subqueries, try this:

select *
  from ( select a.*
              , row_number() over ( order by sysdate_col desc ) as row_num
           from table_name a )
  where row_num = 1;

Java JDBC - How to connect to Oracle using Service Name instead of SID

This should be working: jdbc:oracle:thin//hostname:Port/ServiceName=SERVICE_NAME