Programs & Examples On #Pydev

PyDev is an Eclipse plugin for Python development.

Close pre-existing figures in matplotlib when running from eclipse

It will kill not only all plot windows, but all processes that are called python3, except the current script you run. It works for python3. So, if you are running any other python3 script it will be terminated. As I only run one script at once, it does the job for me.

import os
import subprocess
subprocess.call(["bash","-c",'pyIDs=($(pgrep python3));for x in "${pyIDs[@]}"; do if [ "$x" -ne '+str(os.getpid())+' ];then  kill -9 "$x"; fi done'])

Python main call within class

That entire block is misplaced.

class Example(object):
    def main(self):     
        print "Hello World!"

if __name__ == '__main__':
    Example().main()

But you really shouldn't be using a class just to run your main code.

How do I fix PyDev "Undefined variable from import" errors?

An approximation of what I was doing:

import module.submodule

class MyClass:
    constant = submodule.constant

To which pylint said: E: 4,15: Undefined variable 'submodule' (undefined-variable)

I resolved this by changing my import like:

from module.submodule import CONSTANT

class MyClass:
    constant = CONSTANT

Note: I also renamed by imported variable to have an uppercase name to reflect its constant nature.

Where does Anaconda Python install on Windows?

To find where Anaconda was installed I used the "where" command on the command line in Windows.

C:\>where anaconda

which for me returned:

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

Which allowed me to find the Anaconda Python interpreter at

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\python.exe

to update PyDev

Unresolved Import Issues with PyDev and Eclipse

Here is what worked for me (sugested by soulBit):

1) Restart using restart from the file menu
2) Once it started again, manually close and open it.

This is the simplest solution ever and it completely removes the annoying thing.

How do I add a Maven dependency in Eclipse?

I have faced same problem with maven dependencies, eg: unfortunetly your maven dependencies deleted from your buildpath,then you people get lot of exceptions,if you follow below process you can easily resolve this issue.

 Right click on project >> maven >> updateProject >> selectProject >> OK

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

#!/usr/bin/env node --max-old-space-size=4096 in the ionic-app-scripts.js dint work

Modifying

node_modules/.bin/ionic-app-scripts.cmd

By adding:

@IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0..@ionic\app-scripts\bin\ionic-app-scripts.js" %* ) ELSE ( @SETLOCAL @SET PATHEXT=%PATHEXT:;.JS;=;% node --max_old_space_size=4096 "%~dp0..@ionic\app-scripts\bin\ionic-app-scripts.js" %* )

Worked fianlly

Is it possible to make abstract classes in Python?

Here's a very easy way without having to deal with the ABC module.

In the __init__ method of the class that you want to be an abstract class, you can check the "type" of self. If the type of self is the base class, then the caller is trying to instantiate the base class, so raise an exception. Here's a simple example:

class Base():
    def __init__(self):
        if type(self) is Base:
            raise Exception('Base is an abstract class and cannot be instantiated directly')
        # Any initialization code
        print('In the __init__  method of the Base class')

class Sub(Base):
    def __init__(self):
        print('In the __init__ method of the Sub class before calling __init__ of the Base class')
        super().__init__()
        print('In the __init__ method of the Sub class after calling __init__ of the Base class')

subObj = Sub()
baseObj = Base()

When run, it produces:

In the __init__ method of the Sub class before calling __init__ of the Base class
In the __init__  method of the Base class
In the __init__ method of the Sub class after calling __init__ of the Base class
Traceback (most recent call last):
  File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 16, in <module>
    baseObj = Base()
  File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 4, in __init__
    raise Exception('Base is an abstract class and cannot be instantiated directly')
Exception: Base is an abstract class and cannot be instantiated directly

This shows that you can instantiate a subclass that inherits from a base class, but you cannot instantiate the base class directly.

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

How to check db2 version

Another one in v11:

select CURRENT APPLICATION COMPATIBILITY from sysibm.sysdummy1

Result:

V11R1

It's not the current version, but the current configured level for the application.

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

The use of the deprecated new Buffer() constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.

According to the deprecation warning new Buffer() should be replaced with one of:

  • Buffer.alloc()
  • Buffer.allocUnsafe() or
  • Buffer.from()

Another option in order to avoid this issue would be using the safe-buffer package instead.

You can also try (when using yarn..):

yarn global add yarn

as mentioned here: Link

Another suggestion from the comments (thx to gkiely): self-update

Note: self-update is not available. See policies for enforcing versions within a project

In order to update your version of Yarn, run

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

when I run mockito test occurs WrongTypeOfReturnValue Exception

In my case, I was using both @RunWith(MockitoJUnitRunner.class) and MockitoAnnotations.initMocks(this). When I removed MockitoAnnotations.initMocks(this) it worked correctly.

jQuery Validation using the class instead of the name value

Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

nvarchar(max) still being truncated

To see the dynamic SQL generated, change to text mode (shortcut: Ctrl-T), then use SELECT

PRINT LEN(@Query) -- Prints out 4273, which is correct as far as I can tell
--SET NOCOUNT ON
SELECT @Query

As for sp_executesql, try this (in text mode), it should show the three aaaaa...'s the middle one being the longest with 'SELECT ..' added. Watch the Ln... Col.. indicator in the status bar at bottom right showing 4510 at the end of the 2nd output.

declare @n nvarchar(max)
set @n = REPLICATE(convert(nvarchar(max), 'a'), 4500)
SET @N = 'SELECT ''' + @n + ''''
print @n   -- up to 4000
select @n  -- up to max
exec sp_Executesql @n

C# Java HashMap equivalent

Check out the documentation on MSDN for the Hashtable class.

Represents a collection of key-and-value pairs that are organized based on the hash code of the key.

Also, keep in mind that this is not thread-safe.

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

What is the meaning of {...this.props} in Reactjs

It's called spread attributes and its aim is to make the passing of props easier.

Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.

<Component x={} y={} z={} />

Thus instead you do this, wrap them up in an object and use the spread notation

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

which will unpack it into the props on your component, i.e., you "never" use {... props} inside your render() function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x.

design a stack such that getMinimum( ) should be O(1)

A practical implementation for finding minimum in a Stack of User Designed Object, named: School

The Stack is going to store the Schools in Stack based on the rank assigned to a school in specific region, say, findMin() gives the School where we get the maximum number of applications for Admissions, which in turn is to be defined by the comparator which uses rank associated with the schools in previous season .

The Code for same is below:


   package com.practical;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class CognitaStack {

    public School findMin(Stack<School> stack, Stack<School> minStack) {

        if (!stack.empty() && !minStack.isEmpty())
            return (School) minStack.peek();
        return null;
    }

    public School removeSchool(Stack<School> stack, Stack<School> minStack) {

        if (stack.isEmpty())
            return null;
        School temp = stack.peek();
        if (temp != null) {
            // if(temp.compare(stack.peek(), minStack.peek())<0){
            stack.pop();
            minStack.pop();
            // }

            // stack.pop();
        }
        return stack.peek();
    }

    public static void main(String args[]) {

        Stack<School> stack = new Stack<School>();
        Stack<School> minStack = new Stack<School>();

        List<School> lst = new LinkedList<School>();

        School s1 = new School("Polam School", "London", 3);
        School s2 = new School("AKELEY WOOD SENIOR SCHOOL", "BUCKINGHAM", 4);
        School s3 = new School("QUINTON HOUSE SCHOOL", "NORTHAMPTON", 2);
        School s4 = new School("OAKLEIGH HOUSE SCHOOL", " SWANSEA", 5);
        School s5 = new School("OAKLEIGH-OAK HIGH SCHOOL", "Devon", 1);
        School s6 = new School("BritishInter2", "Devon", 7);

        lst.add(s1);
        lst.add(s2);
        lst.add(s3);
        lst.add(s4);
        lst.add(s5);
        lst.add(s6);

        Iterator<School> itr = lst.iterator();
        while (itr.hasNext()) {
            School temp = itr.next();
            if ((minStack.isEmpty()) || (temp.compare(temp, minStack.peek()) < 0)) { // minStack.peek().equals(temp)
                stack.push(temp);
                minStack.push(temp);
            } else {
                minStack.push(minStack.peek());
                stack.push(temp);
            }

        }

        CognitaStack cogStack = new CognitaStack();
        System.out.println(" Minimum in Stack is " + cogStack.findMin(stack, minStack).name);
        cogStack.removeSchool(stack, minStack);
        cogStack.removeSchool(stack, minStack);

        System.out.println(" Minimum in Stack is "
                + ((cogStack.findMin(stack, minStack) != null) ? cogStack.findMin(stack, minStack).name : "Empty"));
    }

}

Also the School Object is as follows:

package com.practical;

import java.util.Comparator;

public class School implements Comparator<School> {

    String name;
    String location;
    int rank;

    public School(String name, String location, int rank) {
        super();
        this.name = name;
        this.location = location;
        this.rank = rank;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((location == null) ? 0 : location.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + rank;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        School other = (School) obj;
        if (location == null) {
            if (other.location != null)
                return false;
        } else if (!location.equals(other.location))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (rank != other.rank)
            return false;
        return true;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public int getRank() {
        return rank;
    }

    public void setRank(int rank) {
        this.rank = rank;
    }

    public int compare(School o1, School o2) {
        // TODO Auto-generated method stub
        return o1.rank - o2.rank;
    }

}

class SchoolComparator implements Comparator<School> {

    public int compare(School o1, School o2) {
        return o1.rank - o2.rank;
    }

}

This Example covers the following: 1. Implementation of Stack for User defined Objects, here, School 2. Implementation for the hashcode() and equals() method using all fields of Objects to be compared 3. A practical implementation for the scenario where we rqeuire to get the Stack contains operation to be in order of O(1)

Using SQL LOADER in Oracle to import CSV file

Try this

load data infile 'datafile location' into table schema.tablename fields terminated by ',' optionally enclosed by '|' (field1,field2,field3....)

In command prompt:

sqlldr system@databasename/password control='control file location'

Why doesn't [01-12] range work as expected?

The []s in a regex denote a character class. If no ranges are specified, it implicitly ors every character within it together. Thus, [abcde] is the same as (a|b|c|d|e), except that it doesn't capture anything; it will match any one of a, b, c, d, or e. All a range indicates is a set of characters; [ac-eg] says "match any one of: a; any character between c and e; or g". Thus, your match says "match any one of: 0; any character between 1 and 1 (i.e., just 1); or 2.

Your goal is evidently to specify a number range: any number between 01 and 12 written with two digits. In this specific case, you can match it with 0[1-9]|1[0-2]: either a 0 followed by any digit between 1 and 9, or a 1 followed by any digit between 0 and 2. In general, you can transform any number range into a valid regex in a similar manner. There may be a better option than regular expressions, however, or an existing function or module which can construct the regex for you. It depends on your language.

Eclipse: Java was started but returned error code=13

This error occurs because your Eclipse version is 64-bit. You should download and install 64-bit JRE and add the path to it in eclipse.ini. For example:

...
--launcher.appendVmargs
-vm
C:\Program Files\Java\jre1.8.0_45\bin\javaw.exe
-vmargs
...

Note: The -vm parameter should be just before -vmargs and the path should be on a separate line. It should be the full path to the javaw.exe file. Do not enclose the path in double quotes (").

If your Eclipse is 32-bit, install a 32-bit JRE and use the path to its javaw.exe file.

Imply bit with constant 1 or 0 in SQL Server

You might add the second snippet as a field definition for ICourseBased in a view.

DECLARE VIEW MyView
AS
  SELECT
  case 
  when FC.CourseId is not null then cast(1 as bit)
  else cast(0 as bit)
  end
  as IsCoursedBased
  ...

SELECT ICourseBased FROM MyView

Specifying colClasses in the read.csv

If you want to refer to names from the header rather than column numbers, you can use something like this:

fname <- "test.csv"
headset <- read.csv(fname, header = TRUE, nrows = 10)
classes <- sapply(headset, class)
classes[names(classes) %in% c("time")] <- "character"
dataset <- read.csv(fname, header = TRUE, colClasses = classes)

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

it is wrong. correct will be

P3 P2 P4 P5 P1 0 3 4 6 10 as the correct difference are these

Waiting Time (0+3+4+6+10)/5 = 4.6

Ref: http://www.it.uu.se/edu/course/homepage/oskomp/vt07/lectures/scheduling_algorithms/handout.pdf

How do you pass view parameters when navigating from an action in JSF2?

Without a nicer solution, what I found to work is simply building my query string in the bean return:

public String submit() {
    // Do something
    return "/page2.xhtml?faces-redirect=true&id=" + id;
}

Not the most flexible of solutions, but seems to work how I want it to.

Also using this approach to clean up the process of building the query string: http://www.warski.org/blog/?p=185

MySQL Workbench not opening on Windows

As per the current setup on June, 2017 Here is the downloadable link for Visual C++ 2015 Redistributable package : https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe

Hope this will help, who are struggling with the download link.

Note: This is with regards to MySQL Workbench 6.3.9

How do I calculate someone's age based on a DateTime type birthday?

I have created a SQL Server User Defined Function to calculate someone's age, given their birthdate. This is useful when you need it as part of a query:

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlInt32 CalculateAge(string strBirthDate)
    {
        DateTime dtBirthDate = new DateTime();
        dtBirthDate = Convert.ToDateTime(strBirthDate);
        DateTime dtToday = DateTime.Now;

        // get the difference in years
        int years = dtToday.Year - dtBirthDate.Year;

        // subtract another year if we're before the
        // birth day in the current year
        if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))
            years=years-1;

        int intCustomerAge = years;
        return intCustomerAge;
    }
};

Set space between divs

You need a gutter between two div gutter can be made as following

margin(gutter) = width - gutter size E.g margin = calc(70% - 2em)

<body bgcolor="gray">
<section id="main">
        <div id="left">
            Something here     
        </div>
        <div id="right">
                Someone there
        </div>
</section>
</body>
<style>
body{
    font-size: 10px;
}

#main div{
    float: left;
    background-color:#ffffff;
    width: calc(50% - 1.5em);
    margin-left: 1.5em;
}
</style>

How do I check the operating system in Python?

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.system function uses uname internally.

Android: install .apk programmatically

I solved the problem. I made mistake in setData(Uri) and setType(String).

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

That is correct now, my auto-update is working. Thanks for help. =)

Edit 20.7.2016:

After a long time, I had to use this way of updating again in another project. I encountered a number of problems with old solution. A lot of things have changed in that time, so I had to do this with a different approach. Here is the code:

    //get destination to update file and set Uri
    //TODO: First I wanted to store my update .apk file on internal storage for my app but apparently android does not allow you to open and install
    //aplication with existing package from there. So for me, alternative solution is Download directory in external storage. If there is better
    //solution, please inform us in comment
    String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
    String fileName = "AppName.apk";
    destination += fileName;
    final Uri uri = Uri.parse("file://" + destination);

    //Delete update file if exists
    File file = new File(destination);
    if (file.exists())
    //file.delete() - test this, I think sometimes it doesnt work
        file.delete();

    //get url of app on server
    String url = Main.this.getString(R.string.update_app_url);

    //set downloadmanager
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription(Main.this.getString(R.string.notification_description));
    request.setTitle(Main.this.getString(R.string.app_name));

    //set destination
    request.setDestinationUri(uri);

    // get download service and enqueue file
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = manager.enqueue(request);

    //set BroadcastReceiver to install app when .apk is downloaded
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            install.setDataAndType(uri,
                    manager.getMimeTypeForDownloadedFile(downloadId));
            startActivity(install);

            unregisterReceiver(this);
            finish();
        }
    };
    //register receiver for when .apk download is compete
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Returning JSON object as response in Spring Boot

You can either return a response as String as suggested by @vagaasen or you can use ResponseEntity Object provided by Spring as below. By this way you can also return Http status code which is more helpful in webservice call.

@RestController
@RequestMapping("/api")
public class MyRestController
{

    @GetMapping(path = "/hello", produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> sayHello()
    {
         //Get data from service layer into entityList.

        List<JSONObject> entities = new ArrayList<JSONObject>();
        for (Entity n : entityList) {
            JSONObject entity = new JSONObject();
            entity.put("aa", "bb");
            entities.add(entity);
        }
        return new ResponseEntity<Object>(entities, HttpStatus.OK);
    }
}

php_network_getaddresses: getaddrinfo failed: Name or service not known

Had such a problem (with https://github.com/PHPMailer/PHPMailer), just reload PHP and everything start worked

for Centos 6 and 7:

service php-fpm restart 

What was the strangest coding standard rule that you were forced to follow?

Using generic numbered identifier names

At my current work we have two rules which are really mean:

Rule 1: Every time we create a new field in a database table we have to add additional reserve fields for future use. These reserve fields are numbered (because no one knows which data they will hold some day) The next time we need a new field we first look for an unused reserve field.

So we end up with with customer.reserve_field_14 containing the e-mail address of the customer.

At one day our boss thought about introducing reserve tables, but fortunatly we could convince him not to do it.

Rule 2: One of our products is written in VB6 and VB6 has a limit of the total count of different identifier names and since the code is very large, we constantly run into this limit. As a "solution" all local variable names are numbered:

  • Lvarlong1
  • Lvarlong2
  • Lvarstr1
  • ...

Although that effectively circumvents the identifier limit, these two rules combined lead to beautiful code like this:

...

If Lvarbool1 Then
  Lvarbool2 = True
End If

If Lvarbool2 Or Lvarstr1 <> Lvarstr5 Then
  db.Execute("DELETE FROM customer WHERE " _ 
      & "reserve_field_12 = '" & Lvarstr1 & "'")
End If

...

You can imagine how hard it is to fix old or someone else's code...

Latest update: Now we are also using "reserve procedures" for private members:

Private Sub LSub1(Lvarlong1 As Long, Lvarstr1 As String)
  If Lvarlong1 >= 0 Then 
    Lvarbool1 = LFunc1(Lvarstr1)
  Else
    Lvarbool1 = LFunc6()
  End If
  If Lvarbool1 Then
    LSub4 Lvarstr1
  End If
End Sub

EDIT: It seems that this code pattern is becoming more and more popular. See this The Daily WTF post to learn more: Astigmatism :)

Opening a SQL Server .bak file (Not restoring!)

It doesn't seem possible with SQL Server 2008 alone. You're going to need a third-party tool's help.

It will help you make your .bak act like a live database:

http://www.red-gate.com/products/dba/sql-virtual-restore/

How to force file download with PHP

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");

AngularJS + JQuery : How to get dynamic content working in angularjs

Another Solution in Case You Don't Have Control Over Dynamic Content

This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).

Wrap up Your Content

Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.

<div class="selector">
    <grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>

Use Angular Injector

You can use the following code to get a reference to $compile if you don't have one.

$(".selector").each(function () {
    var content = $(this);
    angular.element(document).injector().invoke(function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    });
});

Summary

The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.

One Caveat of the previous code

If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.

Here is the way to remedy it:

Replace the prevous code snippet with the following overload.

...
angular.element(document).injector().invoke(
[
    "$compile", function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    }
]);
...

This caused a lot of grief for me before I pieced it together.

Button Listener for button in fragment in android

Use your code

public class FragmentOne extends Fragment implements OnClickListener{

    View view;
    Fragment fragmentTwo;
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container, false);
        Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
        buttonSayHi.setOnClickListener(this);
        return view;
    }

But I think is better handle the buttons in this way:

@Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.buttonSayHi:
            /** Do things you need to..
               fragmentTwo = new FragmentTwo();

               fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
               fragmentTransaction.addToBackStack(null);

               fragmentTransaction.commit();  
            */
            break;
        }   
    }

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I +1'd Miro's answer for the link to the header-checker site http://www.webconfs.com/http-header-check.php. It pops up an obnoxious ad every time you use it, but it is, nevertheless, very useful for verifying the presence of the Access-Control-Allow-Origin header.

I'm reading a .json file from the javascript on my web page. I found that adding the following to my .htaccess file fixed the problem when viewing my web page in IE 11 (version 11.447.14393.0):

<FilesMatch "\.(json)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

I also added the following to /etc/httpd.conf (Apache's configuration file):

AllowOverride All

The header-checker site verified that the Access-Control-Allow-Origin header is now being sent (thanks, Miro!).

However, Firefox 50.0.2, Opera 41.0.2353.69, and Edge 38.14393.0.0 all fetch the file anyhow, even without the Access-Control-Allow-Origin header. (Note: they might be checking IP addresses, since the two domains I was using are both hosted on the same server, at the same IPv4 address.)

However, Chrome 54.0.2840.99 m (64-bit) ignores the Access-Control-Allow-Origin header and fails anyhow, erroneously reporting:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{mydomain}' is therefore not allowed access.

I think this has got to be some sort of "first." IE is working correctly; Chrome, Firefox, Opera and Edge are all buggy; and Chrome is the worst. Isn't that the exact opposite of the usual case?

What is a monad?

A monad is a way of combining computations together that share a common context. It is like building a network of pipes. When constructing the network, there is no data flowing through it. But when I have finished piecing all the bits together with 'bind' and 'return' then I invoke something like runMyMonad monad data and the data flows through the pipes.

How can I return NULL from a generic method in C#?

Below are the two option you can use

return default(T);

or

where T : class, IThing
 return null;

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

This can happen when you link to msvcrt.dll instead of msvcr10.dll (or similar), which is a good plan. Because it will free you up to redistribute your Visual Studio's runtime library inside your final software package.

That workaround helps me (at Visual Studio 2008):

#if _MSC_VER >= 1400
#undef stdin
#undef stdout
#undef stderr
extern "C" _CRTIMP extern FILE _iob[];
#define stdin   _iob
#define stdout  (_iob+1)
#define stderr  (_iob+2)
#endif

This snippet is not needed for Visual Studio 6 and its compiler. Therefore the #ifdef.

HttpClient.GetAsync(...) never returns when using await/async

Since you are using .Result or .Wait or await this will end up causing a deadlock in your code.

you can use ConfigureAwait(false) in async methods for preventing deadlock

like this:

var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead)
                             .ConfigureAwait(false);

you can use ConfigureAwait(false) wherever possible for Don't Block Async Code .

Compiler error: "initializer element is not a compile-time constant"

When you define a variable outside the scope of a function, that variable's value is actually written into your executable file. This means you can only use a constant value. Since you don't know everything about the runtime environment at compile time (which classes are available, what is their structure, etc.), you cannot create objective c objects until runtime, with the exception of constant strings, which are given a specific structure and guaranteed to stay that way. What you should do is initialize the variable to nil and use +initialize to create your image. initialize is a class method which will be called before any other method is called on your class.

Example:

NSImage *imageSegment = nil;
+ (void)initialize {
    if(!imageSegment)
        imageSegment = [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
}
- (id)init {
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

VBA array sort function?

Somewhat related, but I was also looking for a native excel VBA solution since advanced data structures (Dictionaries, etc.) aren't working in my environment. The following implements sorting via a binary tree in VBA:

  • Assumes array is populated one by one
  • Removes duplicates
  • Returns a separated string ("0|2|3|4|9") which can then be split.

I used it for returning a raw sorted enumeration of rows selected for an arbitrarily selected range

Private Enum LeafType: tEMPTY: tTree: tValue: End Enum
Private Left As Variant, Right As Variant, Center As Variant
Private LeftType As LeafType, RightType As LeafType, CenterType As LeafType
Public Sub Add(x As Variant)
    If CenterType = tEMPTY Then
        Center = x
        CenterType = tValue
    ElseIf x > Center Then
        If RightType = tEMPTY Then
            Right = x
            RightType = tValue
        ElseIf RightType = tTree Then
            Right.Add x
        ElseIf x <> Right Then
            curLeaf = Right
            Set Right = New TreeList
            Right.Add curLeaf
            Right.Add x
            RightType = tTree
        End If
    ElseIf x < Center Then
        If LeftType = tEMPTY Then
            Left = x
            LeftType = tValue
        ElseIf LeftType = tTree Then
            Left.Add x
        ElseIf x <> Left Then
            curLeaf = Left
            Set Left = New TreeList
            Left.Add curLeaf
            Left.Add x
            LeftType = tTree
        End If
    End If
End Sub
Public Function GetList$()
    Const sep$ = "|"
    If LeftType = tValue Then
        LeftList$ = Left & sep
    ElseIf LeftType = tTree Then
        LeftList = Left.GetList & sep
    End If
    If RightType = tValue Then
        RightList$ = sep & Right
    ElseIf RightType = tTree Then
        RightList = sep & Right.GetList
    End If
    GetList = LeftList & Center & RightList
End Function

'Sample code
Dim Tree As new TreeList
Tree.Add("0")
Tree.Add("2")
Tree.Add("2")
Tree.Add("-1")
Debug.Print Tree.GetList() 'prints "-1|0|2"
sortedList = Split(Tree.GetList(),"|")

How to get htaccess to work on MAMP

The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with

RewriteBase /

Which doesn't seem to work in MAMP...at least for me.

How to study design patterns?

Design patterns are just tools--kind of like library functions. If you know that they are there and their approximate function, you can go dig them out of a book when needed.

There is nothing magic about design patterns, and any good programmer figured 90% of them out for themselves before any books came out. For the most part I consider the books to be most useful at simply defining names for the various patterns so we can discuss them more easily.

no module named urllib.parse (How should I install it?)

The problem was because I had a lower version of Django (1.4.10), so Django Rest Framework need at least Django 1.4.11 or bigger. Thanks for their answers guys!

Here the link for the requirements of Django Rest: http://www.django-rest-framework.org/

Remove Item in Dictionary based on Value

Dictionary<string, string> source
//
//functional programming - do not modify state - only create new state
Dictionary<string, string> result = source
  .Where(kvp => string.Compare(kvp.Value, "two", true) != 0)
  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
//
// or you could modify state
List<string> keys = source
  .Where(kvp => string.Compare(kvp.Value, "two", true) == 0)
  .Select(kvp => kvp.Key)
  .ToList();

foreach(string theKey in keys)
{
  source.Remove(theKey);
}

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select convert(varchar(11), transfer_date, 106)

got me my desired result of date formatted as 07 Mar 2018

My column transfer_date is a datetime type column and I am using SQL Server 2017 on azure

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

Use own username/password with git and bitbucket

I figured I should share my solution, since I wasn't able to find it anywhere, and only figured it out through trial and error.

I indeed was able to transfer ownership of the repository to a team on BitBucket.

Don't add the remote URL that BitBuckets suggests:

git remote add origin https://[email protected]/teamName/repo.git

Instead, add the remote URL without your username:

git remote add origin https://bitbucket.org/teamName/repo.git

This way, when you go to pull from or push to a repo, it prompts you for your username, then for your password: everyone on the team has access to it under their own credentials. This approach only works with teams on BitBucket, even though you can manage user permissions on single-owner repos.

How do you print in a Go test using the "testing" package?

The structs testing.T and testing.B both have a .Log and .Logf method that sound to be what you are looking for. .Log and .Logf are similar to fmt.Print and fmt.Printf respectively.

See more details here: http://golang.org/pkg/testing/#pkg-index

fmt.X print statements do work inside tests, but you will find their output is probably not on screen where you expect to find it and, hence, why you should use the logging methods in testing.

If, as in your case, you want to see the logs for tests that are not failing, you have to provide go test the -v flag (v for verbosity). More details on testing flags can be found here: https://golang.org/cmd/go/#hdr-Testing_flags

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

How do I fix the multiple-step OLE DB operation errors in SSIS?

'-2147217887' message 'IDispatch error #3105' source 'Microsoft OLE DB Service Components' description 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.'."

This is what I was also facing. The problem came from the fact that I changed my SQLOLEDB.1 provider to SQLNCLI11 without mentioning the compatibility mode in the connection string. When I set this DataTypeCompatibility=80; in the connection string, I got the problem solved.

How to automatically select all text on focus in WPF TextBox?

We have it so the first click selects all, and another click goes to cursor (our application is designed for use on tablets with pens).

You might find it useful.

public class ClickSelectTextBox : TextBox
{
    public ClickSelectTextBox()
    {
        AddHandler(PreviewMouseLeftButtonDownEvent, 
          new MouseButtonEventHandler(SelectivelyIgnoreMouseButton), true);
        AddHandler(GotKeyboardFocusEvent, 
          new RoutedEventHandler(SelectAllText), true);
        AddHandler(MouseDoubleClickEvent, 
          new RoutedEventHandler(SelectAllText), true);
    }

    private static void SelectivelyIgnoreMouseButton(object sender, 
                                                     MouseButtonEventArgs e)
    {
        // Find the TextBox
        DependencyObject parent = e.OriginalSource as UIElement;
        while (parent != null && !(parent is TextBox))
            parent = VisualTreeHelper.GetParent(parent);

        if (parent != null)
        {
            var textBox = (TextBox)parent;
            if (!textBox.IsKeyboardFocusWithin)
            {
                // If the text box is not yet focussed, give it the focus and
                // stop further processing of this click event.
                textBox.Focus();
                e.Handled = true;
            }
        }
    }

    private static void SelectAllText(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    }
}

load csv into 2D matrix with numpy for plotting

I think using dtype where there is a name row is confusing the routine. Try

>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111196e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111311e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29112065e+12]])
>>> r[:,0]    # Slice 0'th column
array([ 611.88243,  611.88243,  611.88243])

JetBrains / IntelliJ keyboard shortcut to collapse all methods

go to menu option Code > Folding to access all code folding related options and their shortcuts.

How to keep two folders automatically synchronized?

I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.

The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

Access Control Origin Header error using Axios in React Web throwing error in Chrome

In node js(backend), Use cors npm module

$ npm install cors

Then add these lines to support Access-Control-Allow-Origin,

const express = require('express')
const app = express()
app.use(cors())
app.get('/products/:id', cors(), function (req, res, next) {
            res.json({msg: 'This is CORS-enabled for a Single Route'});
});

You can achieve the same, without requiring any external module

app.use(function(req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            next();
});

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Show hide divs on click in HTML and CSS without jQuery

Using label and checkbox input

Keeps the selected item opened and togglable.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using label and named radio input

Similar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio" on both inputs.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using tabindex and :focus

Similar to radio inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.

_x000D_
_x000D_
.collapse > a{_x000D_
  background: #cdf;_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
  outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
  display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
  display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 1</a>_x000D_
  <div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 2</a>_x000D_
  <div>Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using :target

Similar to using radio input, you can additionally use Tab and keys to operate

_x000D_
_x000D_
.collapse a{_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
  display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_1">Collapse 1</a>_x000D_
  <div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_2">Collapse 2</a>_x000D_
  <div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using <detail> and <summary> tags (pure HTML)

You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.

_x000D_
_x000D_
<details>_x000D_
  <summary>Collapse 1</summary>_x000D_
  <p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
  <summary>Collapse 2</summary>_x000D_
  <p>Content 2...</p>_x000D_
</details>
_x000D_
_x000D_
_x000D_

iPhone Debugging: How to resolve 'failed to get the task for process'?

I Had the same issue, but resolved it by following simple following steps :

  1. Make sure you have selected debug rather than release.
  2. In Debug configurations, in project settings, you should have selected developer's profile & no need of specifying the entitlements plist.
  3. Also same setting are there under: Targets: , if not manuall change them to the above for the debug config. It will work.

All the best.

Maven: How to include jars, which are not available in reps into a J2EE project?

Create a repository folder under your project. Let's take

${project.basedir}/src/main/resources/repo

Then, install your custom jar to this repo:

mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \ 
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]

Lastly, add the following repo and dependency definitions to the projects pom.xml:

<repositories>
    <repository>
        <id>project-repo</id>
        <url>file://${project.basedir}/src/main/resources/repo</url>
    </repository>
</repositories>

<dependencies>    
    <dependency>
        <groupId>[GROUP]</groupId>
        <artifactId>[ARTIFACT]</artifactId>
        <version>[VERS]</version>
    </dependency>
</dependencies>

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Android, How can I Convert String to Date?

String source = "24/10/17";

String[] sourceSplit= source.split("/");

int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);

    GregorianCalendar calendar = new GregorianCalendar();
  calendar.set(anno,mese-1,giorno);
  Date   data1= calendar.getTime();
  SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");

    String   dayFormatted= myFormat.format(data1);

    System.out.println("data formattata,-->"+dayFormatted);

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

If you are making your own module then add CommonModule in imports in your own module

Cheap way to search a large text file for a string

If there is no way to tell where the string will be (first half, second half, etc) then there is really no optimized way to do the search other than the builtin "find" function. You could reduce the I/O time and memory consumption by not reading the file all in one shot, but at 4kb blocks (which is usually the size of an hard disk block). This will not make the search faster, unless the string is in the first part of the file, but in all case will reduce memory consumption which might be a good idea if the file is huge.

error: strcpy was not declared in this scope

When you say:

 #include <cstring>

the g++ compiler should put the <string.h> declarations it itself includes into the std:: AND the global namespaces. It looks for some reason as if it is not doing that. Try replacing one instance of strcpy with std::strcpy and see if that fixes the problem.

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

Unit test naming best practices

Class Names. For test fixture names, I find that "Test" is quite common in the ubiquitous language of many domains. For example, in an engineering domain: StressTest, and in a cosmetics domain: SkinTest. Sorry to disagree with Kent, but using "Test" in my test fixtures (StressTestTest?) is confusing.

"Unit" is also used a lot in domains. E.g. MeasurementUnit. Is a class called MeasurementUnitTest a test of "Measurement" or "MeasurementUnit"?

Therefore I like to use the "Qa" prefix for all my test classes. E.g. QaSkinTest and QaMeasurementUnit. It is never confused with domain objects, and using a prefix rather than a suffix means that all the test fixtures live together visually (useful if you have fakes or other support classes in your test project)

Namespaces. I work in C# and I keep my test classes in the same namespace as the class they are testing. It is more convenient than having separate test namespaces. Of course, the test classes are in a different project.

Test method names. I like to name my methods WhenXXX_ExpectYYY. It makes the precondition clear, and helps with automated documentation (a la TestDox). This is similar to the advice on the Google testing blog, but with more separation of preconditions and expectations. For example:

WhenDivisorIsNonZero_ExpectDivisionResult
WhenDivisorIsZero_ExpectError
WhenInventoryIsBelowOrderQty_ExpectBackOrder
WhenInventoryIsAboveOrderQty_ExpectReducedInventory

Conditional statement in a one line lambda function in python?

I found I COULD use "if-then" statements in a lambda. For instance:

eval_op = {
    '|'  : lambda x,y: eval(y) if (eval(x)==0) else eval(x),
    '&'  : lambda x,y: 0 if (eval(x)==0) else eval(y),
    '<'  : lambda x,y: 1 if (eval(x)<eval(y)) else 0,
    '>'  : lambda x,y: 1 if (eval(x)>eval(y)) else 0,
}

Dynamically fill in form values with jQuery

If you need to hit the database, you need to hit the web server again (for the most part).

What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.

AJAX calls can be made in jquery with the $.ajax() function call, so this will happen

User's browser enters input that fires a trigger that makes an AJAX call

$('input .callAjax').bind('change', function() { 
  $.ajax({ url: 'script/ajax', 
           type: json
           data: $foo,  
           success: function(data) {
             $('input .targetAjax').val(data.newValue);
           });
  );

Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.

You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.

The php function json_encode($phpobj); will be useful.

MVC4 HTTP Error 403.14 - Forbidden

I had set the new app's application pool to the DefaultAppPool in IIS which obviously is using the Classic pipeline with .NET v.2.0.

To solve the problem I created a new App Pool using the Integrated pipeline and .NET v4.0. just for this new application and then everything started working as expected.

Don't forget to assign this new app pool to the application. Select the application in IIS, click Basic Settings and then pick the new app pool for the app.

Http Servlet request lose params from POST body after read it once

First of all we should not read parameters within the filter. Usually the headers are read in the filter to do few authentication tasks. Having said that one can read the HttpRequest body completely in the Filter or Interceptor by using the CharStreams:

String body = com.google.common.io.CharStreams.toString(request.getReader());

This does not affect the subsequent reads at all.

How to install requests module in Python 3.4, instead of 2.7

i just reinstalled the pip and it works, but I still wanna know why it happened...

i used the apt-get remove --purge python-pip after I just apt-get install pyhton-pip and it works, but don't ask me why...

Datepicker: How to popup datepicker when click on edittext

This worked for me in Jan 2020

XML Part:

  <EditText
            android:id="@+id/etDOB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:editable="false"
            android:ems="10"
            android:hint="Enter Your Date of Birth" />

Java Part:

         final Calendar myCalendar = Calendar.getInstance();

         userDOBView  = (EditText)findViewById(R.id.etDOB);


    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener(){
      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear, int  dayOfMonth) {
             myCalendar.set(Calendar.YEAR, year);
             myCalendar.set(Calendar.MONTH, monthOfYear);
             myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
             updateLabel();
      }
    };

    userDOBView.setOnTouchListener(new View.OnTouchListener(){
      @Override
      public boolean onTouch(View v, MotionEvent event){
       if(event.getAction() == MotionEvent.ACTION_DOWN){
         new DatePickerDialog("YourClassName".this, date, 
             myCalendar.get(Calendar.YEAR), 
             myCalendar.get(Calendar.MONTH),         
             myCalendar.get(Calendar.DAY_OF_MONTH)).show();
          }
          return true;
       }
    });
private void updateLabel() {
  String myFormat = "MM/dd/yyyy"; //In which you need put here
  SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

  // edittext.setText(sdf.format(myCalendar.getTime()));
  userDOBView.setText(sdf.format(myCalendar.getTime()));
} 

css divide width 100% to 3 column

Just to present an alternative way to fix this problem (if you don't really care about supporting IE):

A soft coded solution would be to use display: table (no support in IE7) along with table-layout: fixed (to ensure equal width columns).

Read more about this here.

change the date format in laravel view page

In Laravel 8 you can use the Date Casting: https://laravel.com/docs/8.x/eloquent-mutators#date-casting

In your Model just set:

protected $casts = [
    'my_custom_datetime_field' => 'datetime'
];

And then in your blade template you can use the format() method:

{{ $my_custom_datetime_field->format('d. m. Y') }}

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Why I can't access remote Jupyter Notebook server?

jupyter notebook --ip 0.0.0.0 --port 8888 will work.

Access a global variable in a PHP function

PHP can be frustrating for this reason. The answers above using global did not work for me, and it took me awhile to figure out the proper use of use.

This is correct:

$functionName = function($stuff) use ($globalVar) {
 //do stuff
}
$output = $functionName($stuff);
$otherOutput = $functionName($otherStuff);

This is incorrect:

function functionName($stuff) use ($globalVar) {
 //do stuff
}
$output = functionName($stuff);
$otherOutput = functionName($otherStuff);

Using your specific example:

    $data = 'My data';

    $menugen = function() use ($data) {
        echo "[" . $data . "]";
    }

    $menugen();

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

Pandas Replace NaN with blank/empty string

df = df.fillna('')

or just

df.fillna('', inplace=True)

This will fill na's (e.g. NaN's) with ''.

If you want to fill a single column, you can use:

df.column1 = df.column1.fillna('')

One can use df['column1'] instead of df.column1.

How do I make case-insensitive queries on Mongodb?

You'd need to use a case-insensitive regular expression for this one, e.g.

db.collection.find( { "name" : { $regex : /Andrew/i } } );

To use the regex pattern from your thename variable, construct a new RegExp object:

var thename = "Andrew";
db.collection.find( { "name" : { $regex : new RegExp(thename, "i") } } );

Update: For exact match, you should use the regex "name": /^Andrew$/i. Thanks to Yannick L.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

SELECT * FROM table where Date(col) = 'date'

Looping through JSON with node.js

You may also want to use hasOwnProperty in the loop.

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        switch (prop) {
            // obj[prop] has the value
        }
    }
}

node.js is single-threaded which means your script will block whether you want it or not. Remember that V8 (Google's Javascript engine that node.js uses) compiles Javascript into machine code which means that most basic operations are really fast and looping through an object with 100 keys would probably take a couple of nanoseconds?

However, if you do a lot more inside the loop and you don't want it to block right now, you could do something like this

switch (prop) {
    case 'Timestamp':
        setTimeout(function() { ... }, 5);
        break;
    case 'Start_Value':
        setTimeout(function() { ... }, 10);
        break;
}

If your loop is doing some very CPU intensive work, you will need to spawn a child process to do that work or use web workers.

Remap values in pandas column with a dict

map can be much faster than replace

If your dictionary has more than a couple of keys, using map can be much faster than replace. There are two versions of this approach, depending on whether your dictionary exhaustively maps all possible values (and also whether you want non-matches to keep their values or be converted to NaNs):

Exhaustive Mapping

In this case, the form is very simple:

df['col1'].map(di)       # note: if the dictionary does not exhaustively map all
                         # entries then non-matched entries are changed to NaNs

Although map most commonly takes a function as its argument, it can alternatively take a dictionary or series: Documentation for Pandas.series.map

Non-Exhaustive Mapping

If you have a non-exhaustive mapping and wish to retain the existing variables for non-matches, you can add fillna:

df['col1'].map(di).fillna(df['col1'])

as in @jpp's answer here: Replace values in a pandas series via dictionary efficiently

Benchmarks

Using the following data with pandas version 0.23.1:

di = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H" }
df = pd.DataFrame({ 'col1': np.random.choice( range(1,9), 100000 ) })

and testing with %timeit, it appears that map is approximately 10x faster than replace.

Note that your speedup with map will vary with your data. The largest speedup appears to be with large dictionaries and exhaustive replaces. See @jpp answer (linked above) for more extensive benchmarks and discussion.

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

This sometimes happen if you remove Java from your path variables. To set the PATH variable again, add the full path of the jdk\bin directory to the PATH variable. Typically, the full path is:

C:\Program Files\Java\jdk-11\bin

To set the PATH variable on Microsoft Windows:

  1. Select Control Panel and then System.
  2. Click Advanced and then Environment Variables.
  3. Add the location of the bin folder of the JDK installation to the PATH variable in system variables.

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

How do I choose the URL for my Spring Boot webapp?

In Spring Boot 2 the property in e.g. application.properties is server.servlet.context-path=/myWebApp to set the context path.

https://docs.spring.io/spring-boot/docs/2.0.1.BUILD-SNAPSHOT/reference/htmlsingle/#_custom_context_path

Hibernate Group by Criteria Object

If you have to do group by using hibernate criteria use projections.groupPropery like the following,

@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
            .add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list(); 
return result;  

How can I get a count of the total number of digits in a number?

Answers already here work for unsigned integers, but I have not found good solutions for getting number of digits from decimals and doubles.

public static int Length(double number)
{
    number = Math.Abs(number);
    int length = 1;
    while ((number /= 10) >= 1)
        length++;
    return length;
}
//number of digits in 0 = 1,
//number of digits in 22.1 = 2,
//number of digits in -23 = 2

You may change input type from double to decimal if precision matters, but decimal has a limit too.

Is either GET or POST more secure than the other?

Even POST accepts GET requests. Assume you have a form having inputs like user.name and user.passwd, those are supposed to support user name and password. If we simply add a ?user.name="my user&user.passwd="my password", then request will be accepted by "bypassing the logon page".

A solution for this is to implement filters (java filters as an e) on server side and detect no string queries are passed as GET arguments.

Swift Bridging Header import issue

Had similar issue that could not be solved by any solution above. My project uses CocoaPods. I noticed that along with errors I got a warning with the following message:

Uncategorized: Target 'Pods' of project 'Pods' was rejected as an implicit dependency for 'Pods.framework' because its architectures 'arm64' didn't contain all required architectures 'armv7 arm64'

enter image description here

So solution was quite simple. For Pods project, change Build Active Architecture Only flag to No and original error went away.

How to sort a Ruby Hash by number value?

Already answered but still. Change your code to:

metrics.sort {|a1,a2| a2[1].to_i <=> a1[1].to_i }

Converted to strings along the way or not, this will do the job.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

Try this. Just add an empty option. This will solve your problem.

<select onchange="jsFunction()">
    <option></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>?

Angular 2 router no base href set

Angular 7,8 fix is in app.module.ts

import {APP_BASE_HREF} from '@angular/common';

inside @NgModule add

providers: [{provide: APP_BASE_HREF, useValue: '/'}]

How to export data from Excel spreadsheet to Sql Server 2008 table

In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:

On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.

After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

Parsing JSON using C

Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

Flutter: RenderBox was not laid out

I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.

Check if certain value is contained in a dataframe column in pandas

You can simply use this:

'07311954' in df.date.values which returns True or False


Here is the further explanation:

In pandas, using in check directly with DataFrame and Series (e.g. val in df or val in series ) will check whether the val is contained in the Index.

BUT you can still use in check for their values too (instead of Index)! Just using val in df.col_name.values or val in series.values. In this way, you are actually checking the val with a Numpy array.

And .isin(vals) is the other way around, it checks whether the DataFrame/Series values are in the vals. Here vals must be set or list-like. So this is not the natural way to go for the question.

Space between two rows in a table?

Best way is to add tr between two tr like below,

_x000D_
_x000D_
<tr>
 <td height="5" colspan="2"></td>
</tr>
_x000D_
_x000D_
_x000D_

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

First string date is converted to js date format and converted into string format again, then it is compared with original string.

function dateValidation(){
    var dateString = "34/05/2019"
    var dateParts = dateString.split("/");
    var date= new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);

    var isValid = isValid( dateString, date );
    console.log("Is valid date: " + isValid);
}

function isValidDate(dateString, date) {
    var newDateString = ( date.getDate()<10 ? ('0'+date.getDate()) : date.getDate() )+ '/'+ ((date.getMonth() + 1)<10? ('0'+(date.getMonth() + 1)) : (date.getMonth() + 1) )  + '/' +  date.getFullYear();
    return ( dateString == newDateString);
}

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

How to invoke the super constructor in Python?

Just to add an example with parameters:

class B(A):
    def __init__(self, x, y, z):
        A.__init__(self, x, y)

Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.

How can I disable a tab inside a TabControl?

This is an old question, but someone may benefit from my addition. I needed a TabControl that would show hidden tabs successively (after an action was performed on the current tab). So, I made a quick class to inherit from and called HideSuccessive() on Load:

public class RevealingTabControl : TabControl
{
    private Action _showNextRequested = delegate { };

    public void HideSuccessive()
    {
        var tabPages = this.TabPages.Cast<TabPage>().Skip(1);
        var queue = new ConcurrentQueue<TabPage>(tabPages);
        tabPages.ToList().ForEach(t => t.Parent = null);
        _showNextRequested = () =>
        {
            if (queue.TryDequeue(out TabPage tabPage))
                tabPage.Parent = this;
        };
    }

    public void ShowNext() => _showNextRequested();
}

How to do tag wrapping in VS code?

A quick search on the VSCode marketplace: https://marketplace.visualstudio.com/items/bradgashler.htmltagwrap.

  1. Launch VS Code Quick Open (Ctrl+P)

  2. paste ext install htmltagwrap and enter

  3. select HTML

  4. press Alt + W (Option + W for Mac).

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

For a more dynamic approach try this.

declare @val varchar(5)
declare @maxSpaces int
set @maxSpaces = 3
set @val = '3'
select concat(REPLICATE('0',@maxSpaces-len(@val)),@val)

Does MS SQL Server's "between" include the range boundaries?

Yes, but be careful when using between for dates.

BETWEEN '20090101' AND '20090131'

is really interpreted as 12am, or

BETWEEN '20090101 00:00:00' AND '20090131 00:00:00'

so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use:

myDate >= '20090101 00:00:00' AND myDate < '20090201 00:00:00'  --CORRECT!

or

BETWEEN '20090101 00:00:00' AND '20090131 23:59:59' --WRONG! (see update!)

UPDATE: It is entirely possible to have records created within that last second of the day, with a datetime as late as 20090101 23:59:59.997!!

For this reason, the BETWEEN (firstday) AND (lastday 23:59:59) approach is not recommended.

Use the myDate >= (firstday) AND myDate < (Lastday+1) approach instead.

Good article on this issue here.

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

Proper usage of Optional.ifPresent()

In addition to @JBNizet's answer, my general use case for ifPresent is to combine .isPresent() and .get():

Old way:

Optional opt = getIntOptional();
if(opt.isPresent()) {
    Integer value = opt.get();
    // do something with value
}

New way:

Optional opt = getIntOptional();
opt.ifPresent(value -> {
    // do something with value
})

This, to me, is more intuitive.

importing pyspark in python shell

Turns out that the pyspark bin is LOADING python and automatically loading the correct library paths. Check out $SPARK_HOME/bin/pyspark :

# Add the PySpark classes to the Python path:
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH

I added this line to my .bashrc file and the modules are now correctly found!

Download and save PDF file with Python requests module

You should use response.content in this case:

with open('/tmp/metadata.pdf', 'wb') as f:
    f.write(response.content)

From the document:

You can also access the response body as bytes, for non-text requests:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

So that means: response.text return the output as a string object, use it when you're downloading a text file. Such as HTML file, etc.

And response.content return the output as bytes object, use it when you're downloading a binary file. Such as PDF file, audio file, image, etc.


You can also use response.raw instead. However, use it when the file which you're about to download is large. Below is a basic example which you can also find in the document:

import requests

url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)

with open('/tmp/metadata.pdf', 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

chunk_size is the chunk size which you want to use. If you set it as 2000, then requests will download that file the first 2000 bytes, write them into the file, and do this again, again and again, unless it finished.

So this can save your RAM. But I'd prefer use response.content instead in this case since your file is small. As you can see use response.raw is complex.


Relates:

performSelector may cause a leak because its selector is unknown

As a workaround until the compiler allows overriding the warning, you can use the runtime

objc_msgSend(_controller, NSSelectorFromString(@"someMethod"));

instead of

[_controller performSelector:NSSelectorFromString(@"someMethod")];

You'll have to

#import <objc/message.h>

How to replace a string in a SQL Server Table Column

You can use this query

update table_name set column_name = replace (column_name , 'oldstring' ,'newstring') where column_name like 'oldstring%'

How do you log all events fired by an element in jQuery?

$('body').on("click mousedown mouseup focus blur keydown change mouseup click dblclick mousemove mouseover mouseout mousewheel keydown keyup keypress textInput touchstart touchmove touchend touchcancel resize scroll zoom focus blur select change submit reset",function(e){
     console.log(e);
}); 

SQL SELECT from multiple tables

SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2`
FROM `product`
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid`
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid`

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here

HTML

<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
    <h1>Form</h1>    
  </div>
  <hr/>
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
                  </select>
        </div>
        <div class="form-group">
          <input type="text" class="form-control" />
        </div>
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
  </label>
          </div>
        </div>
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
            </div>
          </div>
        </div>

      </form>
    </div>
  </div>
</div>

Link to CodePen

https://codepen.io/anjanasilva/pen/WgLaGZ

I hope this helps someone. Thank you.

Parse string to date with moment.js

  • How to change any string date to object date (also with moment.js):

let startDate = "2019-01-16T20:00:00.000"; let endDate = "2019-02-11T20:00:00.000"; let sDate = new Date(startDate); let eDate = new Date(endDate);

  • with moment.js:

startDate = moment(sDate); endDate = moment(eDate);

Default Xmxsize in Java 8 (max heap size)

Like you have mentioned, The default -Xmxsize (Maximum HeapSize) depends on your system configuration.

Java8 client takes Larger of 1/64th of your physical memory for your Xmssize (Minimum HeapSize) and Smaller of 1/4th of your physical memory for your -Xmxsize (Maximum HeapSize).

Which means if you have a physical memory of 8GB RAM, you will have Xmssize as Larger of 8*(1/6) and Smaller of -Xmxsizeas 8*(1/4).

You can Check your default HeapSize with

In Windows:

java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

In Linux:

java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

These default values can also be overrided to your desired amount.

Check which element has been clicked with jQuery

Answer from vpiTriumph lays out the details nicely.
Here's a small handy variation for when there are unique element ids for the data set you want to access:

$('.news-article').click(function(event){    
    var id = event.target.id;
    console.log('id = ' + id); 
});

Grep regex NOT containing string

(?<!1\.2\.3\.4).*Has exploded

You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:

grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log

Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4. Hope that helps!

How to automatically insert a blank row after a group of data

Just an idea, if you know the categories, as small, medium, and large mentioned above...

At the bottom of the sheet, make 3 rows that only say small, medium, and large, change the font to white, and then sort so that it alphabetizes, placing a blank row between each section.

jquery $(this).id return Undefined

$(this) and this aren't the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id property exists on the element, but not the jQuery object. As such, you have a few options:

  1. Access the property on the element directly:

    this.id

  2. Access it from the jQuery object:

    $(this).attr("id")

  3. Pull the object out of jQuery:

    $(this).get(0).id; // Or $(this)[0].id

  4. Get the id from the event object:

    When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items: currentTarget and target.

    Using target, you can get the id of the element that raised the event. currentTarget would simply tell you which element the event is currently bubbling through. These are not always the same.

    $("#button").on("click", function(e){ console.log( e.target.id ) });

Of all of these, the best option is to just access it directly from this itself, unless you're engaged in a series of nested events, then it might be best to use the event object of each nested event (give them all unique names) to reference elements in higher or lower scopes.

How to add a new row to datagridview programmatically

Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).

Create a clone row from RowTemplate is safer imho:

//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");

myDGV.Rows.Add(row);

GROUP_CONCAT ORDER BY

In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/

Auto-scaling input[type=text] to width of value?

A SIMPLE BUT PIXEL PERFECT SOLUTION

I have seen several ways to do this but calculating the width of fonts isn't always 100% accurate, it's just an estimate.

I managed to create a pixel perfect way of adjusting the input width by having a hidden placeholder to measure from.


jQuery (Recommended)

_x000D_
_x000D_
$(function(){_x000D_
  $('#hide').text($('#txt').val());_x000D_
  $('#txt').width($('#hide').width());_x000D_
}).on('input', function () {_x000D_
  $('#hide').text($('#txt').val());_x000D_
  $('#txt').width($('#hide').width());_x000D_
});
_x000D_
body,_x000D_
#txt,_x000D_
#hide{_x000D_
  font:inherit;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}_x000D_
#txt{_x000D_
  border:none;_x000D_
  color:#888;_x000D_
  min-width:10px;_x000D_
}_x000D_
#hide{_x000D_
  display:none;_x000D_
  white-space:pre;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Lorem ipsum _x000D_
  <span id="hide"></span><input id="txt" type="text" value="type here ...">_x000D_
  egestas arcu._x000D_
</p>
_x000D_
_x000D_
_x000D_


Pure JavaScript

I was unable to determine how jQuery calculates the width of hidden elements so a slight tweak to css was required to accomodate this solution.

_x000D_
_x000D_
var hide = document.getElementById('hide');_x000D_
var txt = document.getElementById('txt');_x000D_
resize();_x000D_
txt.addEventListener("input", resize);_x000D_
_x000D_
function resize() {_x000D_
  hide.textContent = txt.value;_x000D_
  txt.style.width = hide.offsetWidth + "px";_x000D_
}
_x000D_
body,_x000D_
#txt,_x000D_
#hide {_x000D_
  font: inherit;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#txt {_x000D_
  border: none;_x000D_
  color: #888;_x000D_
  min-width: 10px;_x000D_
}_x000D_
_x000D_
#hide {_x000D_
  position: absolute;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
  white-space: pre;_x000D_
}
_x000D_
<p>Lorem ipsum_x000D_
  <span id="hide"></span><input id="txt" type="text" value="type here ..."> egestas arcu._x000D_
</p>
_x000D_
_x000D_
_x000D_

Iterating over dictionaries using 'for' loops

You can check the implementation of CPython's dicttype on GitHub. This is the signature of method that implements the dict iterator:

_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
             PyObject **pvalue, Py_hash_t *phash)

CPython dictobject.c

Adding subscribers to a list using Mailchimp's API v3

These are good answers but detached from a full answer as to how you would get a form to send data and handle that response. This will demonstrate how to add a member to a list with v3.0 of the API from an HTML page via jquery .ajax().

In Mailchimp:

  1. Acquire your API Key and List ID
  2. Make sure you setup your list and what custom fields you want to use with it. In this case, I've set up zipcode as a custom field in the list BEFORE I did the API call.
  3. Check out the API docs on adding members to lists. We are using the create method which requires the use of HTTP POST requests. There are other options in here that require PUT if you want to be able to modify/delete subs.

HTML:

<form id="pfb-signup-submission" method="post">
  <div class="sign-up-group">
    <input type="text" name="pfb-signup" id="pfb-signup-box-fname" class="pfb-signup-box" placeholder="First Name">
    <input type="text" name="pfb-signup" id="pfb-signup-box-lname" class="pfb-signup-box" placeholder="Last Name">
    <input type="email" name="pfb-signup" id="pfb-signup-box-email" class="pfb-signup-box" placeholder="[email protected]">
    <input type="text" name="pfb-signup" id="pfb-signup-box-zip" class="pfb-signup-box" placeholder="Zip Code">
  </div>
  <input type="submit" class="submit-button" value="Sign-up" id="pfb-signup-button"></a>
  <div id="pfb-signup-result"></div>
</form>

Key things:

  1. Give your <form> a unique ID and don't forget the method="post" attribute so the form works.
  2. Note the last line #signup-result is where you will deposit the feedback from the PHP script.

PHP:

<?php
  /*
   * Add a 'member' to a 'list' via mailchimp API v3.x
   * @ http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   *
   * ================
   * BACKGROUND
   * Typical use case is that this code would get run by an .ajax() jQuery call or possibly a form action
   * The live data you need will get transferred via the global $_POST variable
   * That data must be put into an array with keys that match the mailchimp endpoints, check the above link for those
   * You also need to include your API key and list ID for this to work.
   * You'll just have to go get those and type them in here, see README.md
   * ================
   */

  // Set API Key and list ID to add a subscriber
  $api_key = 'your-api-key-here';
  $list_id = 'your-list-id-here';

  /* ================
   * DESTINATION URL
   * Note: your API URL has a location subdomain at the front of the URL string
   * It can vary depending on where you are in the world
   * To determine yours, check the last 3 digits of your API key
   * ================
   */
  $url = 'https://us5.api.mailchimp.com/3.0/lists/' . $list_id . '/members/';

  /* ================
   * DATA SETUP
   * Encode data into a format that the add subscriber mailchimp end point is looking for
   * Must include 'email_address' and 'status'
   * Statuses: pending = they get an email; subscribed = they don't get an email
   * Custom fields go into the 'merge_fields' as another array
   * More here: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   * ================
   */
  $pfb_data = array(
    'email_address' => $_POST['emailname'],
    'status'        => 'pending',
    'merge_fields'  => array(
      'FNAME'       => $_POST['firstname'],
      'LNAME'       => $_POST['lastname'],
      'ZIPCODE'     => $_POST['zipcode']
    ),
  );

  // Encode the data
  $encoded_pfb_data = json_encode($pfb_data);

  // Setup cURL sequence
  $ch = curl_init();

  /* ================
   * cURL OPTIONS
   * The tricky one here is the _USERPWD - this is how you transfer the API key over
   * _RETURNTRANSFER allows us to get the response into a variable which is nice
   * This example just POSTs, we don't edit/modify - just a simple add to a list
   * _POSTFIELDS does the heavy lifting
   * _SSL_VERIFYPEER should probably be set but I didn't do it here
   * ================
   */
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_pfb_data);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  $results = curl_exec($ch); // store response
  $response = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get HTTP CODE
  $errors = curl_error($ch); // store errors

  curl_close($ch);

  // Returns info back to jQuery .ajax or just outputs onto the page

  $results = array(
    'results' => $result_info,
    'response' => $response,
    'errors' => $errors
  );

  // Sends data back to the page OR the ajax() in your JS
  echo json_encode($results);
?>

Key things:

  1. CURLOPT_USERPWD handles the API key and Mailchimp doesn't really show you how to do this.
  2. CURLOPT_RETURNTRANSFER gives us the response in such a way that we can send it back into the HTML page with the .ajax() success handler.
  3. Use json_encodeon the data you received.

JS:

// Signup form submission
$('#pfb-signup-submission').submit(function(event) {
  event.preventDefault();

  // Get data from form and store it
  var pfbSignupFNAME = $('#pfb-signup-box-fname').val();
  var pfbSignupLNAME = $('#pfb-signup-box-lname').val();
  var pfbSignupEMAIL = $('#pfb-signup-box-email').val();
  var pfbSignupZIP = $('#pfb-signup-box-zip').val();

  // Create JSON variable of retreived data
  var pfbSignupData = {
    'firstname': pfbSignupFNAME,
    'lastname': pfbSignupLNAME,
    'email': pfbSignupEMAIL,
    'zipcode': pfbSignupZIP
  };

  // Send data to PHP script via .ajax() of jQuery
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'mailchimp-signup.php',
    data: pfbSignupData,
    success: function (results) {
      $('#pfb-signup-box-fname').hide();
      $('#pfb-signup-box-lname').hide();
      $('#pfb-signup-box-email').hide();
      $('#pfb-signup-box-zip').hide();
      $('#pfb-signup-result').text('Thanks for adding yourself to the email list. We will be in touch.');
      console.log(results);
    },
    error: function (results) {
      $('#pfb-signup-result').html('<p>Sorry but we were unable to add you into the email list.</p>');
      console.log(results);
    }
  });
});

Key things:

  1. JSON data is VERY touchy on transfer. Here, I am putting it into an array and it looks easy. If you are having problems, it is likely because of how your JSON data is structured. Check this out!
  2. The keys for your JSON data will become what you reference in the PHP _POST global variable. In this case it will be _POST['email'], _POST['firstname'], etc. But you could name them whatever you want - just remember what you name the keys of the data part of your JSON transfer is how you access them in PHP.
  3. This obviously requires jQuery ;)

How do I print bytes as hexadecimal?

Well you can convert one byte (unsigned char) at a time into a array like so

char buffer [17];
buffer[16] = 0;
for(j = 0; j < 8; j++)
    sprintf(&buffer[2*j], "%02X", data[j]);

List of remotes for a Git repository?

FWIW, I had exactly the same question, but I could not find the answer here. It's probably not portable, but at least for gitolite, I can run the following to get what I want:

$ ssh [email protected] info
hello akim, this is gitolite 2.3-1 (Debian) running on git 1.7.10.4
the gitolite config gives you the following access:
     R   W     android
     R   W     bistro
     R   W     checkpn
...

How to check if a string contains a specific text

Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.

If $a contains a string, you can use the following:

if (!empty($a)) {      // Means: if not empty
    ...
}

If you also need to confirm that $a is actually a string, use:

if (is_string($a) && !empty($a)) {      // Means: if $a is a string and not empty
    ...
}

Retrieving data from a POST method in ASP.NET

The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content

StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();

To navigate through the all inputs

foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
   string value = HttpContext.Current.Request.Form[key];
}

Can you nest html forms?

As Craig said, no.

But, regarding your comment as to why:

It might be easier to use 1 <form> with the inputs and the "Update" button, and use copy hidden inputs with the "Submit Order" button in a another <form>.

Is it possible to open a Windows Explorer window from PowerShell?

Use any of these:

  1. start .
  2. explorer .
  3. start explorer .
  4. ii .
  5. invoke-item .

You may apply any of these commands in PowerShell.

Just in case you want to open the explorer from the command prompt, the last two commands don't work, and the first three work fine.

Setting java locale settings

If you are on Mac, simply using System Preferences -> Languages and dragging the language to test to top (before English) will make sure the next time you open the App, the right locale is tried!!

Add a user control to a wpf window

Make sure there is an namespace definition (xmlns) for the namespace your control belong to.

xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>

Access to the path is denied

What Identity is your Application Pool for the Web application running as, to troubleshoot, try creating a new App Pool with say Network Service as its identity and make your web application use that new App Pool you created and see if the error persists.

async await return Task

In order to get proper responses back from async methods, you need to put await while calling those task methods. That will wait for converting it back to the returned value type rather task type.

E.g var content = await StringAsyncTask (

where public async Task<String> StringAsyncTask ())

Traversing text in Insert mode

To have a little better navigation in insert mode, why not map some keys?

imap <C-b> <Left>
imap <C-f> <Right>
imap <C-e> <End>
imap <C-a> <Home>
" <C-a> is used to repeat last entered text. Override it, if its not needed

If you can work around making the Meta key work in your terminal, you can mock emacs mode even better. The navigation in normal-mode is way better, but for shorter movements it helps to stay in insert mode.

For longer jumps, I prefer the following default translation:

<Meta-b>    maps to     <Esc><C-left>

This shifts to normal-mode and goes back a word

fill an array in C#

Write yourself an extension method

public static class ArrayExtensions {
    public static void Fill<T>(this T[] originalArray, T with) {
        for(int i = 0; i < originalArray.Length; i++){
            originalArray[i] = with;
        }
    }  
}

and use it like

int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);

will fill all the elements with 13

Setting environment variables on OS X

Login Shells

/etc/profile

The shell first executes the commands in file /etc/profile. A user working with root privileges can set up this file to establish systemwide default characteristics for users running Bash.

.bash_profile
.bash_login
.profile

Next the shell looks for ~/.bash_profile, ~/.bash_login, and ~/.profile (~/ is short- hand for your home directory), in that order, executing the commands in the first of these files it finds. You can put commands in one of these files to override the defaults set in /etc/profile. A shell running on a virtual terminal does not execute commands in these files.

.bash_logout

When you log out, bash executes commands in the ~/.bash_logout file. This file often holds commands that clean up after a session, such as those that remove temporary files.

Interactive Nonlogin Shells

/etc/bashrc

Although not called by bash directly, many ~/.bashrc files call /etc/bashrc. This setup allows a user working with root privileges to establish systemwide default characteristics for nonlogin bash shells.

.bashrc

An interactive nonlogin shell executes commands in the ~/.bashrc file. Typically a startup file for a login shell, such as .bash_profile, runs this file, so both login and nonlogin shells run the commands in .bashrc.

Because commands in .bashrc may be executed many times, and because subshells inherit exported variables, it is a good idea to put commands that add to existing variables in the .bash_profile file.

Bootstrap 4 Center Vertical and Horizontal Alignment

Use This Code In CSS :

.container {
    width: 600px;
    height: 350px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: inline-flex;
}

SQLite error 'attempt to write a readonly database' during insert?

I got this error when I tried to write to a database on an Android system.

Apparently sqlite3 not only needs write permissions to the database file and the containing directory (as @austin-hyde already said in his answer) but also the environment variable TMPDIR has to point to a (possibly writable) directory.

On my Android system I set it to TMPDIR="/data/local/tmp" and now my script runs as expected :)

Edit:

If you can't set environment variables you can use one of the other methods listed here: https://www.sqlite.org/tempfiles.html#temporary_file_storage_locations like PRAGMA temp_store_directory = 'directory-name';

PSEXEC, access denied errors

I had the same problem. And after a hard work, I found a easy and full solution:

  1. I use runas to run the script in a admin account
  2. I use the -s parameter in psExec to run in a system account
  3. Inside the PsExec, I login again with a admin account
  4. You can use & to run multiples commands
  5. Remember to replace [USERNAME], [PASSWORD], [COMPUTERNAME], [COMMAND1] and [COMMAND2] with the real values

The code looks like this:

runas /user:[USERNAME] "psexec -e -h -s -u [USERNAME] -p [PASSWORD] \\[COMPUTERNAME] cmd /C [COMMAND1] & [COMMAND2]"


If you whant to debug your script in the another machine, run the following template:

runas /user:[USERNAME] "psexec -i -e -h -s -u [USERNAME] -p [PASSWORD] \\[COMPUTERNAME] cmd /C [COMMAND1] & [COMMAND2] & pause"

R memory management / cannot allocate vector of size n Mb

The save/load method mentioned above works for me. I am not sure how/if gc() defrags the memory but this seems to work.

# defrag memory 
save.image(file="temp.RData")
rm(list=ls())
load(file="temp.RData")

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

How to change maven java home

Even if you install the Oracle JDK, your $JAVA_HOME variable should refer to the path of the JRE that is inside the JDK root. You can refer to my other answer to a similar question for more details.

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

How to limit depth for recursive file list?

All I'm really interested in is the ownership and permissions information for the first level subdirectories.

I found a easy solution while playing my fish, which fits your need perfectly.

ll `ls`

or

ls -l $(ls)

Head and tail in one line

Python 2, using lambda

>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

PHP - SSL certificate error: unable to get local issuer certificate

Another reason this error can occur is if a CA bundle has been removed from your system (and is no longer available in ca-certificates).

This is currently the situation with the GeoTrust Global CA which (among other things) is used to sign Apple's certificate for APNS used for Push Notifications.

Additional details can be found on the bug report here: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=962596

You can manually add the GeoTrust Global CA certificate on your machine as suggested by Carlos Alberto Lopez Perez:

wget --no-check-certificate -c https://www.geotrust.com/resources/root_certificates/certificates/GeoTrust_Global_CA.pem   \
&& mkdir /usr/local/share/ca-certificates/extra                                                                       \
&& mv GeoTrust_Global_CA.pem /usr/local/share/ca-certificates/extra/GeoTrust_Global_CA.crt                            \
&& update-ca-certificates

How to download all dependencies and packages to directory

I'm assuming you've got a nice fat USB HD and a good connection to the net. You can use apt-mirror to essentially create your own debian mirror.

http://apt-mirror.sourceforge.net/

Background color on input type=button :hover state sticks in IE

You need to make sure images come first and put in a comma after the background image call. then it actually does work:

    background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

Find stored procedure by name

You can use this query:

SELECT 
    ROUTINE_CATALOG AS DatabaseName ,
    ROUTINE_SCHEMA AS SchemaName,
    SPECIFIC_NAME AS SPName ,
    ROUTINE_DEFINITION AS SPBody ,
    CREATED AS CreatedDate,
    LAST_ALTERED AS LastModificationDate
FROM INFORMATION_SCHEMA.ROUTINES
WHERE 
    (ROUTINE_DEFINITION LIKE '%%')
    AND 
    (ROUTINE_TYPE='PROCEDURE')
    AND
    (SPECIFIC_NAME LIKE '%AssessmentToolDegreeDel')

As you can see, you can do search inside the body of Stored Procedure also.

Get product id and product type in magento?

<?php if( $_product->getTypeId() == 'simple' ): ?>
//your code for simple products only
<?php endif; ?>

<?php if( $_product->getTypeId() == 'grouped' ): ?>
//your code for grouped products only
<?php endif; ?>

So on. It works! Magento 1.6.1, place in the view.phtml

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

1-Go to your workspace directory » .metadata » .plugins » org.eclipse.wst.server.core folder.

2- Delete the tmp folder.

3- Restart your Eclipse IDE

Is there a PowerShell "string does not contain" cmdlet or syntax?

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}

How do I redirect to another webpage?

All way to make a redirect from the client side:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <title>JavaScript and jQuery example to redirect a page or URL </title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <div id="redirect">_x000D_
            <h2>Redirecting to another page</h2>_x000D_
        </div>_x000D_
_x000D_
        <script src="scripts/jquery-1.6.2.min.js"></script>_x000D_
        <script>_x000D_
            // JavaScript code to redirect a URL_x000D_
            window.location.replace("http://stackoverflow.com");_x000D_
            // window.location.replace('http://code.shouttoday.com');_x000D_
_x000D_
            // Another way to redirect page using JavaScript_x000D_
_x000D_
            // window.location.assign('http://code.shouttoday.com');_x000D_
            // window.location.href = 'http://code.shouttoday.com';_x000D_
            // document.location.href = '/relativePath';_x000D_
_x000D_
            //jQuery code to redirect a page or URL_x000D_
            $(document).ready(function(){_x000D_
                //var url = "http://code.shouttoday.com";_x000D_
                //$(location).attr('href',url);_x000D_
                // $(window).attr('location',url)_x000D_
                //$(location).prop('href', url)_x000D_
            });_x000D_
        </script>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

gettimeofday - the problem is that will can have lower values if you change you hardware clock (with NTP for example) Boost - not available for this project clock() - usually returns a 4 bytes integer, wich means that its a low capacity, and after some time it returns negative numbers.

I prefer to create my own class and update each 10 miliseconds, so this way is more flexible, and I can even improve it to have subscribers.

class MyAlarm {
static int64_t tiempo;
static bool running;
public:
static int64_t getTime() {return tiempo;};
static void callback( int sig){
    if(running){
        tiempo+=10L;
    }
}
static void run(){ running = true;}
};

int64_t MyAlarm::tiempo = 0L;
bool MyAlarm::running = false;

to refresh it I use setitimer:

int main(){
struct sigaction sa; 
struct itimerval timer; 

MyAlarm::run();
memset (&sa, 0, sizeof (sa)); 
sa.sa_handler = &MyAlarm::callback; 

sigaction (SIGALRM, &sa, NULL); 


timer.it_value.tv_sec = 0; 
timer.it_value.tv_usec = 10000; 



timer.it_interval.tv_sec = 0; 
timer.it_interval.tv_usec = 10000; 


setitimer (ITIMER_REAL, &timer, NULL); 
.....

Look at setitimer and the ITIMER_VIRTUAL and ITIMER_REAL.

Don't use the alarm or ualarm functions, you will have low precision when your process get a hard work.

In Laravel, the best way to pass different types of flash messages in the session

In Controller:

Redirect::to('/path')->with('message', 'your message'); 

Or

Session::flash('message', 'your message'); 

in Blade show message in Blade As ur Desired Pattern:

@if(Session::has('message'))
    <div class="alert alert-className">
        {{session('message')}}
    </div>
@endif

How do you dismiss the keyboard when editing a UITextField

try this

- (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

How do I remove an object from an array with JavaScript?

delete obj[1];

Note that this will not change array indices. Any array members you delete will remain as "slots" that contain undefined.

Classes residing in App_Code is not accessible

I found it easier to move the files into a separate Class Library project and then reference that project in the web project and apply the namespace in the using section of the file. For some reason the other solutions were not working for me, but this work around did.

How to use JNDI DataSource provided by Tomcat in Spring?

If using Spring's XML schema based configuration, setup in the Spring context like this:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
...
<jee:jndi-lookup id="dbDataSource"
   jndi-name="jdbc/DatabaseName"
   expected-type="javax.sql.DataSource" />

Alternatively, setup using simple bean configuration like this:

<bean id="DatabaseName" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/DatabaseName"/>
</bean>

You can declare the JNDI resource in tomcat's server.xml using something like this:

<GlobalNamingResources>
    <Resource name="jdbc/DatabaseName"
              auth="Container"
              type="javax.sql.DataSource"
              username="dbUser"
              password="dbPassword"
              url="jdbc:postgresql://localhost/dbname"
              driverClassName="org.postgresql.Driver"
              initialSize="20"
              maxWaitMillis="15000"
              maxTotal="75"
              maxIdle="20"
              maxAge="7200000"
              testOnBorrow="true"
              validationQuery="select 1"
              />
</GlobalNamingResources>

And reference the JNDI resource from Tomcat's web context.xml like this:

  <ResourceLink name="jdbc/DatabaseName"
   global="jdbc/DatabaseName"
   type="javax.sql.DataSource"/>

Reference documentation:

Edit: This answer has been updated for Tomcat 8 and Spring 4. There have been a few property name changes for Tomcat's default datasource resource pool setup.

Android Studio: Unable to start the daemon process

Sometimes You just open too much applications in Windows and make the gradle have no enough memory to start the daemon process.So when you come across with this situation,you can just close some applications such as Chrome and so on. Then restart your android studio.

jQuery equivalent to Prototype array.last()

with slice():

var a = [1,2,3,4];
var lastEl = a.slice(-1)[0]; // 4
// a is still [1,2,3,4]

with pop();

var a = [1,2,3,4];
var lastEl = a.pop(); // 4
// a is now [1,2,3]

see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for more information

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I got this error when I was trying to access Bundle data from One Intent by using getInt("ID").

I solved it by using getString("ID").

From Activity1 i had

Intent intent=new Intent(this,ActivityB.class);
intent.putExtra("data",data)// 
startActivity(intent);

On Activity B,

Bundle bundle=getIntent().getExtras();
if(extras!=null){
// int x=extras.getInt("Data"); This Line gave me error int 
x=Integer.parseInt(extras.getString("Data")); // This solved the problem.
}

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

How do I change Bootstrap 3 column order on mobile layout?

You cannot change the order of columns in smaller screens but you can do that in large screens.

So change the order of your columns.

<!--Main Content-->
<div class="col-lg-9 col-lg-push-3">
</div>

<!--Sidebar-->
<div class="col-lg-3 col-lg-pull-9">
</div>

By default this displays the main content first.

So in mobile main content is displayed first.

By using col-lg-push and col-lg-pull we can reorder the columns in large screens and display sidebar on the left and main content on the right.

Working fiddle here.

When to use RDLC over RDL reports?

Some of these points have been addressed above, but here's my 2-cents for VS2008 environment.

RDL (Remote reports): Much better development experience, more flexibility if you need to use some advanced features like scheduling, ad-hoc reporting, etc...

RDLC (Local reports): Better control over the data before sending it to the report (easier to validate or manipulate the data prior to sending it to the report). Much easier deployment, no need for an instance of Reporting Services.

One HUGE caveat with local reports is a known memory leak that can severely affect performance if your clients will be running numerous large reports. This is supposed to be addressed with the new VS2010 version of the report viewer.

In my case, since we have an instance of Reporting Services available, I develop new reports as RDLs and then convert them to local reports (which is easy) and deploy them as local reports.

Get DOM content of cross-domain iframe

There's a workaround to achieve it.

  1. First, bind your iframe to a target page with relative url. The browsers will treat the site in iframe the same domain with your website.

  2. In your web server, using a rewrite module to redirect request from the relative url to absolute url. If you use IIS, I recommend you check on IIRF module.

How can you tell if a value is not numeric in Oracle?

REGEXP_LIKE(column, '^[[:digit:]]+$')

returns TRUE if column holds only numeric characters

Why is Maven downloading the maven-metadata.xml every time?

I haven't studied yet, when Maven does which look-up, but to get stable and reproducible builds, I strongly recommend not to access Maven Respositories directly but to use a Maven Repository Manager such as Nexus.

Here is the tutorial how to set up your settings file:

http://books.sonatype.com/nexus-book/reference/maven-sect-single-group.html

http://maven.apache.org/repository-management.html

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>

How can I send an HTTP POST request to a server from Excel using VBA?

If you need it to work on both Mac and Windows, you can use QueryTables:

With ActiveSheet.QueryTables.Add(Connection:="URL;http://carbon.brighterplanet.com/flights.txt", Destination:=Range("A2"))
    .PostText = "origin_airport=MSN&destination_airport=ORD"
    .RefreshStyle = xlOverwriteCells
    .SaveData = True
    .Refresh
End With

Notes:

  • Regarding output... I don't know if it's possible to return the results to the same cell that called the VBA function. In the example above, the result is written into A2.
  • Regarding input... If you want the results to refresh when you change certain cells, make sure those cells are the argument to your VBA function.
  • This won't work on Excel for Mac 2008, which doesn't have VBA. Excel for Mac 2011 got VBA back.

For more details, you can see my full summary about "using web services from Excel."

Java ElasticSearch None of the configured nodes are available

possible problem:

  1. wrong port, if you use a Java or Scala client, correct port is 9300, not 9200
  2. wrong cluster name, make sure the cluster name you set in your code is the same as the cluster.name you set in $ES_HOME/config/elasticsearch.yml
  3. the sniff option, set client.transport.sniff to be true but can't connect to all nodes of ES cluster will cause this problem too. ES doc here explained why.

Why is "except: pass" a bad programming practice?

As you correctly guessed, there are two sides to it: Catching any error by specifying no exception type after except, and simply passing it without taking any action.

My explanation is “a bit” longer—so tl;dr it breaks down to this:

  1. Don’t catch any error. Always specify which exceptions you are prepared to recover from and only catch those.
  2. Try to avoid passing in except blocks. Unless explicitly desired, this is usually not a good sign.

But let’s go into detail:

Don’t catch any error

When using a try block, you usually do this because you know that there is a chance of an exception being thrown. As such, you also already have an approximate idea of what can break and what exception can be thrown. In such cases, you catch an exception because you can positively recover from it. That means that you are prepared for the exception and have some alternative plan which you will follow in case of that exception.

For example, when you ask for the user to input a number, you can convert the input using int() which might raise a ValueError. You can easily recover that by simply asking the user to try it again, so catching the ValueError and prompting the user again would be an appropriate plan. A different example would be if you want to read some configuration from a file, and that file happens to not exist. Because it is a configuration file, you might have some default configuration as a fallback, so the file is not exactly necessary. So catching a FileNotFoundError and simply applying the default configuration would be a good plan here. Now in both these cases, we have a very specific exception we expect and have an equally specific plan to recover from it. As such, in each case, we explicitly only except that certain exception.

However, if we were to catch everything, then—in addition to those exceptions we are prepared to recover from—there is also a chance that we get exceptions that we didn’t expect, and which we indeed cannot recover from; or shouldn’t recover from.

Let’s take the configuration file example from above. In case of a missing file, we just applied our default configuration, and might decided at a later point to automatically save the configuration (so next time, the file exists). Now imagine we get a IsADirectoryError, or a PermissionError instead. In such cases, we probably do not want to continue; we could still apply our default configuration, but we later won’t be able to save the file. And it’s likely that the user meant to have a custom configuration too, so using the default values is likely not desired. So we would want to tell the user about it immediately, and probably abort the program execution too. But that’s not something we want to do somewhere deep within some small code part; this is something of application-level importance, so it should be handled at the top—so let the exception bubble up.

Another simple example is also mentioned in the Python 2 idioms document. Here, a simple typo exists in the code which causes it to break. Because we are catching every exception, we also catch NameErrors and SyntaxErrors. Both are mistakes that happen to us all while programming; and both are mistakes we absolutely don’t want to include when shipping the code. But because we also caught those, we won’t even know that they occurred there and lose any help to debug it correctly.

But there are also more dangerous exceptions which we are unlikely prepared for. For example SystemError is usually something that happens rarely and which we cannot really plan for; it means there is something more complicated going on, something that likely prevents us from continuing the current task.

In any case, it’s very unlikely that you are prepared for everything in a small scale part of the code, so that’s really where you should only catch those exceptions you are prepared for. Some people suggest to at least catch Exception as it won’t include things like SystemExit and KeyboardInterrupt which by design are to terminate your application, but I would argue that this is still far too unspecific. There is only one place where I personally accept catching Exception or just any exception, and that is in a single global application-level exception handler which has the single purpose to log any exception we were not prepared for. That way, we can still retain as much information about unexpected exceptions, which we then can use to extend our code to handle those explicitly (if we can recover from them) or—in case of a bug—to create test cases to make sure it won’t happen again. But of course, that only works if we only ever caught those exceptions we were already expecting, so the ones we didn’t expect will naturally bubble up.

Try to avoid passing in except blocks

When explicitly catching a small selection of specific exceptions, there are many situations in which we will be fine by simply doing nothing. In such cases, just having except SomeSpecificException: pass is just fine. Most of the time though, this is not the case as we likely need some code related to the recovery process (as mentioned above). This can be for example something that retries the action again, or to set up a default value instead.

If that’s not the case though, for example because our code is already structured to repeat until it succeeds, then just passing is good enough. Taking our example from above, we might want to ask the user to enter a number. Because we know that users like to not do what we ask them for, we might just put it into a loop in the first place, so it could look like this:

def askForNumber ():
    while True:
        try:
            return int(input('Please enter a number: '))
        except ValueError:
            pass

Because we keep trying until no exception is thrown, we don’t need to do anything special in the except block, so this is fine. But of course, one might argue that we at least want to show the user some error message to tell him why he has to repeat the input.

In many other cases though, just passing in an except is a sign that we weren’t really prepared for the exception we are catching. Unless those exceptions are simple (like ValueError or TypeError), and the reason why we can pass is obvious, try to avoid just passing. If there’s really nothing to do (and you are absolutely sure about it), then consider adding a comment why that’s the case; otherwise, expand the except block to actually include some recovery code.

except: pass

The worst offender though is the combination of both. This means that we are willingly catching any error although we are absolutely not prepared for it and we also don’t do anything about it. You at least want to log the error and also likely reraise it to still terminate the application (it’s unlikely you can continue like normal after a MemoryError). Just passing though will not only keep the application somewhat alive (depending where you catch of course), but also throw away all the information, making it impossible to discover the error—which is especially true if you are not the one discovering it.


So the bottom line is: Catch only exceptions you really expect and are prepared to recover from; all others are likely either mistakes you should fix, or something you are not prepared for anyway. Passing specific exceptions is fine if you really don’t need to do something about them. In all other cases, it’s just a sign of presumption and being lazy. And you definitely want to fix that.

Convert an int to ASCII character

"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"

There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.

How to obtain the total numbers of rows from a CSV file in Python?

If you are working on a Unix system, the fastest method is the following shell command

cat FILE_NAME.CSV | wc -l

From Jupyter Notebook or iPython, you can use it with a !:

! cat FILE_NAME.CSV | wc -l

add allow_url_fopen to my php.ini using .htaccess

Try this, but I don't think it will work because you're not supposed to be able to change this

Put this line in an htaccess file in the directory you want the setting to be enabled:

php_value allow_url_fopen On

Note that this setting will only apply to PHP file's in the same directory as the htaccess file.

As an alternative to using url_fopen, try using curl.

How to convert ISO8859-15 to UTF8?

I found this to work for me:

iconv -f ISO-8859-14 Agreement.txt -t UTF-8 -o agreement.txt

PHP - add 1 day to date format mm-dd-yyyy

$date = DateTime::createFromFormat('m-d-Y', '04-15-2013');
$date->modify('+1 day');
echo $date->format('m-d-Y');

See it in action

Or in PHP 5.4+

echo (DateTime::createFromFormat('m-d-Y', '04-15-2013'))->modify('+1 day')->format('m-d-Y');

reference

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

Omitting the second expression when using the if-else shorthand

Another option:

x === 2 ? doSomething() : void 0;

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For me ComboBox.DropDownClosed Event did it.

private void cbValueType_DropDownClosed(object sender, EventArgs e)
    {
        if (cbValueType.SelectedIndex == someIntValue) //sel ind already updated
        {
            // change sel Index of other Combo for example
            cbDataType.SelectedIndex = someotherIntValue;
        }
    }

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

String comparison in bash. [[: not found

[[ is a bash-builtin. Your /bin/bash doesn't seem to be an actual bash.

From a comment:

Add #!/bin/bash at the top of file