Programs & Examples On #Pixel shader

Pixel shaders, also known as fragment shaders, compute color and other attributes of each fragment. Pixel shaders range from always outputting the same color, to applying a lighting value, to doing bump mapping, shadows, specular highlights, translucency and other phenomena.

Rename multiple files in a directory in Python

The following code should work. It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_ then it is renamed. If not nothing is done to the filename.

import os
for fileName in os.listdir("."):
    os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob 
WHERE fileid NOT IN 
       (SELECT id 
        FROM files 
        WHERE id is NOT NULL/*This line is unlikely to be needed 
                               but using NOT IN...*/
      )

React native ERROR Packager can't listen on port 8081

You should kill all processes running on port 8081 by kill -9 $(lsof -i:8081)

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

/bin/sh: pushd: not found

add

SHELL := /bin/bash

at the top of your makefile I have found it on another question How can I use Bash syntax in Makefile targets?

How to check if an alert exists using WebDriver?

public static void handleAlert(){
    if(isAlertPresent()){
        Alert alert = driver.switchTo().alert();
        System.out.println(alert.getText());
        alert.accept();
    }
}
public static boolean isAlertPresent(){
      try{
          driver.switchTo().alert();
          return true;
      }catch(NoAlertPresentException ex){
          return false;
      }
}

How to create a Date in SQL Server given the Day, Month and Year as Integers

The following code should work on all versions of sql server I believe:

SELECT CAST(CONCAT(CAST(@Year AS VARCHAR(4)), '-',CAST(@Month AS VARCHAR(2)), '-',CAST(@Day AS VARCHAR(2))) AS DATE)

Location of ini/config files in linux/unix?

You should adhere your application to the XDG Base Directory Specification. Most answers here are either obsolete or wrong.

Your application should store and load data and configuration files to/from the directories pointed by the following environment variables:

  • $XDG_DATA_HOME (default: "$HOME/.local/share"): user-specific data files.
  • $XDG_CONFIG_HOME (default: "$HOME/.config"): user-specific configuration files.
  • $XDG_DATA_DIRS (default: "/usr/local/share/:/usr/share/"): precedence-ordered set of system data directories.
  • $XDG_CONFIG_DIRS (default: "/etc/xdg"): precedence-ordered set of system configuration directories.
  • $XDG_CACHE_HOME (default: "$HOME/.cache"): user-specific non-essential data files.

You should first determine if the file in question is:

  1. A configuration file ($XDG_CONFIG_HOME:$XDG_CONFIG_DIRS);
  2. A data file ($XDG_DATA_HOME:$XDG_DATA_DIRS); or
  3. A non-essential (cache) file ($XDG_CACHE_HOME).

It is recommended that your application put its files in a subdirectory of the above directories. Usually, something like $XDG_DATA_DIRS/<application>/filename or $XDG_DATA_DIRS/<vendor>/<application>/filename.

When loading, you first try to load the file from the user-specific directories ($XDG_*_HOME) and, if failed, from system directories ($XDG_*_DIRS). When saving, save to user-specific directories only (since the user probably won't have write access to system directories).

For other, more user-oriented directories, refer to the XDG User Directories Specification. It defines directories for the Desktop, downloads, documents, videos, etc.

Run local python script on remote server

Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.

Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.

On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.

import sys
import os

def main():
    print os.name

if __name__ == '__main__':
    try:
        if sys.argv[1] == 'deploy':
            import paramiko

            # Connect to remote host
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect('remote_hostname_or_IP', username='john', password='secret')

            # Setup sftp connection and transmit this script
            sftp = client.open_sftp()
            sftp.put(__file__, '/tmp/myscript.py')
            sftp.close()

            # Run the transmitted script remotely without args and show its output.
            # SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
            stdout = client.exec_command('python /tmp/myscript.py')[1]
            for line in stdout:
                # Process each line in the remote output
                print line

            client.close()
            sys.exit(0)
    except IndexError:
        pass

    # No cmd-line args provided, run script normally
    main()

Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.

Make the image go behind the text and keep it in center using CSS

Well, put your image in the background of your website/container and put whatever you want on top of that.

Your container defined in HTML:

<div id="container">
   <input name="box" type="textbox" />
   <input name="box" type="textbox" />
   <input name="submit" type="submit" />
</div>

Your CSS would look like this:

#container {
    background-image:url(yourimage.jpg);
    background-position:center;
    width:700px;
    height:400px;
}

For this to work though, you must have height and width specified to certain values (i.e. no percentages). I could help you more specifically if you wanted, but I'd need more info.

Converting File to MultiPartFile

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

public static void main(String[] args) {
        convertFiletoMultiPart();
    }

    private static void convertFiletoMultiPart() {
        try {
            File file = new File(FILE_PATH);
            if (file.exists()) {
                System.out.println("File Exist => " + file.getName() + " :: " + file.getAbsolutePath());
            }
            FileInputStream input = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
                    IOUtils.toByteArray(input));
            System.out.println("multipartFile => " + multipartFile.isEmpty() + " :: "
                    + multipartFile.getOriginalFilename() + " :: " + multipartFile.getName() + " :: "
                    + multipartFile.getSize() + " :: " + multipartFile.getBytes());
        } catch (IOException e) {
            System.out.println("Exception => " + e.getLocalizedMessage());
        }
    }

This worked for me.

Opacity CSS not working in IE8

CSS

I used to use the following from CSS-Tricks:

.transparent_class {
  /* IE 8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

  /* IE 5-7 */
  filter: alpha(opacity=50);

  /* Netscape */
  -moz-opacity: 0.5;

  /* Safari 1.x */
  -khtml-opacity: 0.5;

  /* Good browsers */
  opacity: 0.5;
}

Compass

However, a better solution is to use the Opacity Compass mixin, all you need to do is to @include opacity(0.1); and it will take care of any cross-browser issues for you. You can find an example here.

Where is the application.properties file in a Spring Boot project?

In the your first journey in spring boot project I recommend you to start with Spring Starter Try this link here.

enter image description here

It will auto generate the project structure for you like this.application.perperties it will be under /resources.

application.properties important change,

server.port = Your PORT(XXXX) by default=8080
server.servlet.context-path=/api (SpringBoot version 2.x.)
server.contextPath-path=/api (SpringBoot version < 2.x.)

Any way you can use application.yml in case you don't want to make redundancy properties setting.

Example
application.yml

server:
   port: 8080 
   contextPath: /api

application.properties

server.port = 8080
server.contextPath = /api

Rounding a number to the nearest 5 or 10 or X

Simply ROUND(x/5)*5 should do the job.

Subset data to contain only columns whose names match a condition

This worked for me:

df[,names(df) %in% colnames(df)[grepl(str,colnames(df))]]

Javascript reduce on array of objects

To formalize what has been pointed out, a reducer is a catamorphism which takes two arguments which may be the same type by coincidence, and returns a type which matches the first argument.

function reducer (accumulator: X, currentValue: Y): X { }

That means that the body of the reducer needs to be about converting currentValue and the current value of the accumulator to the value of the new accumulator.

This works in a straightforward way, when adding, because the accumulator and the element values both happen to be the same type (but serve different purposes).

[1, 2, 3].reduce((x, y) => x + y);

This just works because they're all numbers.

[{ age: 5 }, { age: 2 }, { age: 8 }]
  .reduce((total, thing) => total + thing.age, 0);

Now we're giving a starting value to the aggregator. The starting value should be the type that you expect the aggregator to be (the type you expect to come out as the final value), in the vast majority of cases. While you aren't forced to do this (and shouldn't be), it's important to keep in mind.

Once you know that, you can write meaningful reductions for other n:1 relationship problems.

Removing repeated words:

const skipIfAlreadyFound = (words, word) => words.includes(word)
    ? words
    : words.concat(word);

const deduplicatedWords = aBunchOfWords.reduce(skipIfAlreadyFound, []);

Providing a count of all words found:

const incrementWordCount = (counts, word) => {
  counts[word] = (counts[word] || 0) + 1;
  return counts;
};
const wordCounts = words.reduce(incrementWordCount, { });

Reducing an array of arrays, to a single flat array:

const concat = (a, b) => a.concat(b);

const numbers = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
].reduce(concat, []);

Any time you're looking to go from an array of things, to a single value that doesn't match a 1:1, reduce is something you might consider.

In fact, map and filter can both be implemented as reductions:

const map = (transform, array) =>
  array.reduce((list, el) => list.concat(transform(el)), []);

const filter = (predicate, array) => array.reduce(
  (list, el) => predicate(el) ? list.concat(el) : list,
  []
);

I hope this provides some further context for how to use reduce.

The one addition to this, which I haven't broken into yet, is when there is an expectation that the input and output types are specifically meant to be dynamic, because the array elements are functions:

const compose = (...fns) => x =>
  fns.reduceRight((x, f) => f(x), x);

const hgfx = h(g(f(x)));
const hgf = compose(h, g, f);
const hgfy = hgf(y);
const hgfz = hgf(z);

nodejs module.js:340 error: cannot find module

I faced the same problem. I just copied the testNode.js file(that contain the test code) and pasted into the root of nodejs directory manually. I tried this command C:\Program Files (x86)\nodejs>node testnode.js Bingo! I received this message.

enter image description here

Then I typed this url in a browser and received the message "Hello World". Hope this help somebody.

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

Windows 8.1 gets Error 720 on connect VPN

Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:

why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.

Solution:

  1. check write permissions on registers

    a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it

    b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log

    c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"

    d. run the following command netsh int ipv6 reset reset.log and repeat step c)

  2. unistall all not-working miniports

    a. go to device managers (windows+x -> device manager)

    b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)

    c. unistall these not working devices

    d. reboot your computer

    e. Repeat steps a) - d) until you will not see any yellow mark on miniports

  3. delete your vpn connection and create a new one.

that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)

references:

http://en.remontka.pro/error-720-windows-8-and-8-1-solved/

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

how to sort an ArrayList in ascending order using Collections and Comparator

Two ways to get this done:

Collections.sort(myArray)

given elements inside myArray implements Comparable

Second

Collections.sort(myArray, new MyArrayElementComparator());

where MyArrayElementComparator is Comparator for elements inside myArray

Change Schema Name Of Table In SQL

Create Schema :

IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe')) 
BEGIN
    EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
END

ALTER Schema :

ALTER SCHEMA exe 
    TRANSFER dbo.Employees

Convert to/from DateTime and Time in Ruby

You'll need two slightly different conversions.

To convert from Time to DateTime you can amend the Time class as follows:

require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

Similar adjustments to Date will let you convert DateTime to Time .

class Date
  def to_gm_time
    to_time(new_offset, :gm)
  end

  def to_local_time
    to_time(new_offset(DateTime.now.offset-offset), :local)
  end

  private
  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
              dest.sec, usec)
  end
end

Note that you have to choose between local time and GM/UTC time.

Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.

Passing array in GET for a REST call

This worked for me.

/users?ids[]=id1&ids[]=id2

Using DateTime in a SqlParameter for Stored Procedure, format error

How are you setting up the SqlParameter? You should set the SqlDbType property to SqlDbType.DateTime and then pass the DateTime directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).

You should be able to get the value into the DB. If not, here is a very simple example of how to do it:

static void Main(string[] args)
{
    // Create the connection.
    using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
    {
        // Open the connection.
        connection.Open();

        // Create the command.
        using (SqlCommand command = new SqlCommand("xsp_Test", connection))
        {
            // Set the command type.
            command.CommandType = System.Data.CommandType.StoredProcedure;

            // Add the parameter.
            SqlParameter parameter = command.Parameters.Add("@dt",
                System.Data.SqlDbType.DateTime);

            // Set the value.
            parameter.Value = DateTime.Now;

            // Make the call.
            command.ExecuteNonQuery();
        }
    }
}

I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.

If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime struct will easily do).

All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime method, not by converting to a string) to the stored procedure.

And when you get the value back, call the ToLocalTime method to get the time in the local time zone.

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

Free tool to Create/Edit PNG Images?

ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?

Set scroll position

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

How to install gem from GitHub source?

Also you can do gem install username-projectname -s http://gems.github.com

How to clear jQuery validation error messages?

Try to use this for remove validation on the click on cancel

 function HideValidators() {
            var lblMsg = document.getElementById('<%= lblRFDChild.ClientID %>');
            lblMsg.innerHTML = "";           
            if (window.Page_Validators) {
                for (var vI = 0; vI < Page_Validators.length; vI++) {
                    var vValidator = Page_Validators[vI];
                    vValidator.isvalid = true;
                    ValidatorUpdateDisplay(vValidator);
                }
            } 
        }

How to change package name in android studio?

It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:

  1. right click on the root folder of your project.
  2. Click "Open Module Setting".
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

Can the Unix list command 'ls' output numerical chmod permissions?

You can use the following command

stat -c "%a %n" *

Also you can use any filename or directoryname instead of * to get a specific result.

On Mac, you can use

stat -f '%A %N' *

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

I'm using a similar code as those that use the while loop but I call the entry count in every loop... so I suppose it's somewhat slower

FragmentManager manager = getFragmentManager();
while (manager.getBackStackEntryCount() > 0){
        manager.popBackStackImmediate();
    }

Using Predicate in Swift

You can use filters available in swift to filter content from an array instead of using a predicate like in Objective-C.

An example in Swift 4.0 is as follows:

var stringArray = ["foundation","coredata","coregraphics"]
stringArray = stringArray.filter { $0.contains("core") }

In the above example, since each element in the array is a string you can use the contains method to filter the array.

If the array contains custom objects, then the properties of that object can be used to filter the elements similarly.

JavaFX Application Icon

What do you think about creating new package i.e image.icons in your src directory and moving there you .png images? Than you just need to write:

Image image = new Image("/image/icons/nameOfImage.png");
primaryStage.getIcons().add(image);

This solution works for me perfectly, but still I'm not sure if it's correct (beginner here).

Regular expression for decimal number

In general, i.e. unlimited decimal places:

^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$

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

Use:

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

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

Log4j2 configuration - No log4j2 configuration file found

Was following the documentations - Apache Log4j2 Configuratoin and Apache Log4j2 Maven in configuring log4j2 with yaml. As per the documentation, the following maven dependencies are required:

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.1</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.1</version>
  </dependency>

and

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.8.6</version>
</dependency>

Just adding these didn't pick the configuration and always gave error. The way of debugging configuration by adding -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE helped in seeing the logs. Later had to download the source using Maven and debugging helped in understanding the depended classes of log4j2. They are listed in org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory:

com.fasterxml.jackson.databind.ObjectMapper
com.fasterxml.jackson.databind.JsonNode
com.fasterxml.jackson.core.JsonParser
com.fasterxml.jackson.dataformat.yaml.YAMLFactory

Adding dependency mapping for jackson-dataformat-yaml will not have the first two classes. Hence, add the jackson-databind dependency to get yaml configuration working:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>

You may add the version by referring to the Test Dependencies section of log4j-api version item from MVN Repository. E.g. for 2.8.1 version of log4j-api, refer this link and locate the jackson-databind version.

Moreover, you can use the below Java code to check if the classes are available in the classpath:

System.out.println(ClassLoader.getSystemResource("log4j2.yml")); //Check if file is available in CP
ClassLoader cl = Thread.currentThread().getContextClassLoader(); //Code as in log4j2 API. Version: 2.8.1
 String [] classes = {"com.fasterxml.jackson.databind.ObjectMapper",
 "com.fasterxml.jackson.databind.JsonNode",
 "com.fasterxml.jackson.core.JsonParser",
 "com.fasterxml.jackson.dataformat.yaml.YAMLFactory"};

 for(String className : classes) {
     cl.loadClass(className);
 }

How to change xampp localhost to another folder ( outside xampp folder)?

I had to change both the httpd.conf and httpd-ssl.conf files DocumentRoot properties to get things like relative links (i.e. href="/index.html") and the favicon.ico link to work properly.

The latest Xampp control Panel makes this pretty easy.

From the control panel, there should be Apache in the first row. If it's started, stop it. Then click config and open the httpd.conf file and search for htdocs or documentRoot. Change the path to what you like. Do the same for httpd-ssl.conf. These should be the top 2 files in the list under Config's dropdown.

Then start the server again.

Hope this helps someone. Cheers.

Why is IoC / DI not common in Python?

In my opinion, things like dependency injection are symptoms of a rigid and over-complex framework. When the main body of code becomes much too weighty to change easily, you find yourself having to pick small parts of it, define interfaces for them, and then allowing people to change behaviour via the objects that plug into those interfaces. That's all well and good, but it's better to avoid that sort of complexity in the first place.

It's also the symptom of a statically-typed language. When the only tool you have to express abstraction is inheritance, then that's pretty much what you use everywhere. Having said that, C++ is pretty similar but never picked up the fascination with Builders and Interfaces everywhere that Java developers did. It is easy to get over-exuberant with the dream of being flexible and extensible at the cost of writing far too much generic code with little real benefit. I think it's a cultural thing.

Typically I think Python people are used to picking the right tool for the job, which is a coherent and simple whole, rather than the One True Tool (With A Thousand Possible Plugins) that can do anything but offers a bewildering array of possible configuration permutations. There are still interchangeable parts where necessary, but with no need for the big formalism of defining fixed interfaces, due to the flexibility of duck-typing and the relative simplicity of the language.

Default argument values in JavaScript functions

You cannot add default values for function parameters. But you can do this:

function tester(paramA, paramB){
 if (typeof paramA == "undefined"){
   paramA = defaultValue;
 }
 if (typeof paramB == "undefined"){
   paramB = defaultValue;
 }
}

Simplest way to wait some asynchronous tasks complete, in Javascript?

Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    conn.collection(name).drop( callback );
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped') - if you want it, use this instead:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    // if you really want the console.log( 'dropped' ),
    // replace the 'callback' here with an anonymous function
    conn.collection(name).drop( function(err) {
        if( err ) { return callback(err); }
        console.log('dropped');
        callback()
    });
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

set the iframe height automatically

If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>

How to force a view refresh without having it trigger automatically from an observable?

In some circumstances it might be useful to simply remove the bindings and then re-apply:

ko.cleanNode(document.getElementById(element_id))
ko.applyBindings(viewModel, document.getElementById(element_id))

Why does NULL = NULL evaluate to false in SQL server

At technet there is a good explanation for how null values work.

Null means unknown.

Therefore the Boolean expression

value=null

does not evaluate to false, it evaluates to null, but if that is the final result of a where clause, then nothing is returned. That is a practical way to do it, since returning null would be difficult to conceive.

It is interesting and very important to understand the following:

If in a query we have

where (value=@param Or @param is null) And id=@anotherParam

and

  • value=1
  • @param is null
  • id=123
  • @anotherParam=123

then

"value=@param" evaluates to null
"@param is null" evaluates to true
"id=@anotherParam" evaluates to true

So the expression to be evaluated becomes

(null Or true) And true

We might be tempted to think that here "null Or true" will be evaluated to null and thus the whole expression becomes null and the row will not be returned.

This is not so. Why?

Because "null Or true" evaluates to true, which is very logical, since if one operand is true with the Or-operator, then no matter the value of the other operand, the operation will return true. Thus it does not matter that the other operand is unknown (null).

So we finally have true=true and thus the row will be returned.

Note: with the same crystal clear logic that "null Or true" evaluates to true, "null And true" evaluates to null.

Update:
Ok, just to make it complete I want to add the rest here too which turns out quite fun in relation to the above.

"null Or false" evaluates to null, "null And false" evaluates to false. :)

The logic is of course still as self-evident as before.

How to get child element by ID in JavaScript?

Using jQuery

$('#note textarea');

or just

$('#textid');

How can I uninstall an application using PowerShell?

Use:

function remove-HSsoftware{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,
ValuefromPipeline = $true,
HelpMessage="IdentifyingNumber can be retrieved with `"get-wmiobject -class win32_product`"")]
[ValidatePattern('{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}}')]
[string[]]$ids,
[parameter(Mandatory=$false,
            ValuefromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            HelpMessage="Computer name or IP adress to query via WMI")]
[Alias('hostname,CN,computername')]
[string[]]$computers
)
begin {}
process{
    if($computers -eq $null){
    $computers = Get-ADComputer -Filter * | Select dnshostname |%{$_.dnshostname}
    }
    foreach($computer in $computers){
        foreach($id in $ids){
            write-host "Trying to uninstall sofware with ID ", "$id", "from computer ", "$computer"
            $app = Get-WmiObject -class Win32_Product -Computername "$computer" -Filter "IdentifyingNumber = '$id'"
            $app | Remove-WmiObject

        }
    }
}
end{}}
 remove-hssoftware -ids "{8C299CF3-E529-414E-AKD8-68C23BA4CBE8}","{5A9C53A5-FF48-497D-AB86-1F6418B569B9}","{62092246-CFA2-4452-BEDB-62AC4BCE6C26}"

It's not fully tested, but it ran under PowerShell 4.

I've run the PS1 file as it is seen here. Letting it retrieve all the Systems from the AD and trying to uninstall multiple applications on all systems.

I've used the IdentifyingNumber to search for the Software cause of David Stetlers input.

Not tested:

  1. Not adding ids to the call of the function in the script, instead starting the script with parameter IDs
  2. Calling the script with more then 1 computer name not automatically retrieved from the function
  3. Retrieving data from the pipe
  4. Using IP addresses to connect to the system

What it does not:

  1. It doesn't give any information if the software actually was found on any given system.
  2. It does not give any information about failure or success of the deinstallation.

I wasn't able to use uninstall(). Trying that I got an error telling me that calling a method for an expression that has a value of NULL is not possible. Instead I used Remove-WmiObject, which seems to accomplish the same.

CAUTION: Without a computer name given it removes the software from ALL systems in the Active Directory.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    </waitfor>
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    </waitfor>
    <echo>deployment ok!</echo>
</target>

${jboss.deploy.dir} is set to standalone/deployments

how to configuring a xampp web server for different root directory

You can also put in a new virtual Host entry in the

c:\xampp\apache\conf\httpd-vhosts.conf

like:

<VirtualHost *:80>
  ServerAdmin [email protected]
  DocumentRoot "C:/xampp/htdocs/myproject/web"
  ServerName localhost
  ErrorLog "logs/dummy-host2.example.com-error.log"
  CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

What is the purpose of Order By 1 in SQL select statement?

This is useful when you use set based operators e.g. union

select cola
  from tablea
union
select colb
  from tableb
order by 1;

How to set HTML5 required attribute in Javascript?

let formelems = document.querySelectorAll('input,textarea,select');
formelems.forEach((formelem) => {
  formelem.required = true;

});

If you wish to make all input, textarea, and select elements required.

avrdude: stk500v2_ReceiveMessage(): timeout

Open Terminal and type:

$ sudo usermod -a -G dialout 

(This command is optional)

$ **sudo chmod a+rw /dev/ttyACM0** 

(This command must succeed)

Accessing post variables using Java Servlets

Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.

I hope this helps you out.

<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>

Now for the Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    ....
    ....
  }
}

Add unique constraint to combination of two columns

Once you have removed your duplicate(s):

ALTER TABLE dbo.yourtablename
  ADD CONSTRAINT uq_yourtablename UNIQUE(column1, column2);

or

CREATE UNIQUE INDEX uq_yourtablename
  ON dbo.yourtablename(column1, column2);

Of course, it can often be better to check for this violation first, before just letting SQL Server try to insert the row and returning an exception (exceptions are expensive).

http://www.sqlperformance.com/2012/08/t-sql-queries/error-handling

http://www.mssqltips.com/sqlservertip/2632/checking-for-potential-constraint-violations-before-entering-sql-server-try-and-catch-logic/

If you want to prevent exceptions from bubbling up to the application, without making changes to the application, you can use an INSTEAD OF trigger:

CREATE TRIGGER dbo.BlockDuplicatesYourTable
 ON dbo.YourTable
 INSTEAD OF INSERT
AS
BEGIN
  SET NOCOUNT ON;

  IF NOT EXISTS (SELECT 1 FROM inserted AS i 
    INNER JOIN dbo.YourTable AS t
    ON i.column1 = t.column1
    AND i.column2 = t.column2
  )
  BEGIN
    INSERT dbo.YourTable(column1, column2, ...)
      SELECT column1, column2, ... FROM inserted;
  END
  ELSE
  BEGIN
    PRINT 'Did nothing.';
  END
END
GO

But if you don't tell the user they didn't perform the insert, they're going to wonder why the data isn't there and no exception was reported.


EDIT here is an example that does exactly what you're asking for, even using the same names as your question, and proves it. You should try it out before assuming the above ideas only treat one column or the other as opposed to the combination...

USE tempdb;
GO

CREATE TABLE dbo.Person
(
  ID INT IDENTITY(1,1) PRIMARY KEY,
  Name NVARCHAR(32),
  Active BIT,
  PersonNumber INT
);
GO

ALTER TABLE dbo.Person 
  ADD CONSTRAINT uq_Person UNIQUE(PersonNumber, Active);
GO

-- succeeds:
INSERT dbo.Person(Name, Active, PersonNumber)
  VALUES(N'foo', 1, 22);
GO

-- succeeds:
INSERT dbo.Person(Name, Active, PersonNumber)
  VALUES(N'foo', 0, 22);
GO

-- fails:
INSERT dbo.Person(Name, Active, PersonNumber)
  VALUES(N'foo', 1, 22);
GO

Data in the table after all of this:

ID   Name   Active PersonNumber
---- ------ ------ ------------
1    foo    1      22
2    foo    0      22

Error message on the last insert:

Msg 2627, Level 14, State 1, Line 3 Violation of UNIQUE KEY constraint 'uq_Person'. Cannot insert duplicate key in object 'dbo.Person'. The statement has been terminated.

How to set the opacity/alpha of a UIImage?

same result as others, different style:

extension UIImage {

    func withAlpha(_ alpha: CGFloat) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(at: .zero, blendMode: .normal, alpha: alpha)
        }
    }

}

How can I update npm on Windows?

Download and run the latest MSI. The MSI will update your installed node and npm.

Creating a file name as a timestamp in a batch job

used Martin's suggestion with a little tweak to add time stamp to the file name:

forfiles /p [foldername] /m rsync2.log /c "cmd /c ren @file %DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_%time:~-11,2%-%time:~-8,2%-%time:~-5,2%-@file

For the 10:17:21 23/10/2019 The result is:

20191023_10-17-21-rsync2.log

Generating random numbers in C

You should call srand() before calling rand to initialize the random number generator.

Either call it with a specific seed, and you will always get the same pseudo-random sequence

#include <stdlib.h>

int main ()
{
  srand ( 123 );
  int random_number = rand();
  return 0;
}

or call it with a changing sources, ie the time function

#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) );
  int random_number = rand();
  return 0;
}

In response to Moon's Comment rand() generates a random number with an equal probability between 0 and RAND_MAX (a macro pre-defined in stdlib.h)

You can then map this value to a smaller range, e.g.

int random_value = rand(); //between 0 and RAND_MAX

//you can mod the result
int N = 33;
int rand_capped = random_value % N;  //between 0 and 32
int S = 50;
int rand_range = rand_capped + S; //between 50 and 82

//you can convert it to a float
float unit_random = random_value / (float) RAND_MAX; //between 0 and 1 (floating point)

This might be sufficient for most uses, but its worth pointing out that in the first case using the mod operator introduces a slight bias if N does not divide evenly into RAND_MAX+1.

Random number generators are interesting and complex, it is widely said that the rand() generator in the C standard library is not a great quality random number generator, read (http://en.wikipedia.org/wiki/Random_number_generation for a definition of quality).

http://en.wikipedia.org/wiki/Mersenne_twister (source http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html ) is a popular high quality random number generator.

Also, I am not aware of arc4rand() or random() so I cannot comment.

VARCHAR to DECIMAL

You are going to have to truncate the values yourself as strings before you put them into that column.

Otherwise, if you want more decimal places, you will need to change your declaration of the decimal column.

No @XmlRootElement generated by JAXB

To soluction it you should configure a xml binding before to compile with wsimport, setting generateElementProperty as false.

     <jaxws:bindings wsdlLocation="LOCATION_OF_WSDL"
      xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"
      xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" 
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
      xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
         <jaxws:enableWrapperStyle>false</jaxws:enableWrapperStyle>
    <jaxws:bindings  node="wsdl:definitions/wsdl:types/xs:schema[@targetNamespace='NAMESPACE_OF_WSDL']">
      <jxb:globalBindings xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xjc:generateElementProperty>false</xjc:generateElementProperty> 
      </jxb:globalBindings>
  </jaxws:bindings>
</jaxws:bindings>

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I did try giving access to the folders but that did not help. My solution was to make the below highlighted options in red selected for the logged in user

This is what you see when you right click and select the username you have logged in for windows authentication mode.

Reactive forms - disabled attribute

Only who are using reactive forms : For native HTML elements [attr.disabled] will work but for material elements we need to dynamically disable the element.

this.form.get('controlname').disable();

Otherwise it will show in console warning message.

Using classes with the Arduino

I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:

class AMLed
{
    private:
          uint8_t _ledPin;
          long _turnOffTime;

    public:
          AMLed(uint8_t pin);
          void setOn();
          void setOff();
          // Turn the led on for a given amount of time (relies
          // on a call to check() in the main loop()).
          void setOnForTime(int millis);
          void check();
};

And here is the main source

AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
    pinMode(_ledPin, OUTPUT);
}

void AMLed::setOn()
{
    digitalWrite(_ledPin, HIGH);
}

void AMLed::setOff()
{
    digitalWrite(_ledPin, LOW);
}

void AMLed::setOnForTime(int p_millis)
{
    _turnOffTime = millis() + p_millis;
    setOn();
}

void AMLed::check()
{
    if (_turnOffTime != 0 && (millis() > _turnOffTime))
    {
        _turnOffTime = 0;
        setOff();
    }
}

It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html

To use, I simply do something like this in the .pde file:

#include "AM_Led.h"

#define TIME_LED    12   // The port for the LED

AMLed test(TIME_LED);

Select rows having 2 columns equal value

select * from test;
a1  a2  a3
1   1   2
1   2   2
2   1   2

select t1.a3 from test t1, test t2 where t1.a1 = t2.a1 and t2.a2 = t1.a2 and t1.a1 = t2.a2

a3
1

You can try same thing using Joins too..

How do I get DOUBLE_MAX?

Using double to store large integers is dubious; the largest integer that can be stored reliably in double is much smaller than DBL_MAX. You should use long long, and if that's not enough, you need your own arbitrary-precision code or an existing library.

Before and After Suite execution hook in jUnit 4.x

Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code:

package com.test;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({Test1.class, Test2.class})
public class TestSuite {

    @BeforeClass
    public static void setUp() {
        System.out.println("setting up");
    }

    @AfterClass
    public static void tearDown() {
        System.out.println("tearing down");
    }

}

So your Test1 class would look something like:

package com.test;

import org.junit.Test;


public class Test1 {
    @Test
    public void test1() {
        System.out.println("test1");
    }

}

...and you can imagine that Test2 looks similar. If you ran TestSuite, you would get:

setting up
test1
test2
tearing down

So you can see that the set up/tear down only run before and after all tests, respectively.

The catch: this only works if you're running the test suite, and not running Test1 and Test2 as individual JUnit tests. You mentioned you're using maven, and the maven surefire plugin likes to run tests individually, and not part of a suite. In this case, I would recommend creating a superclass that each test class extends. The superclass then contains the annotated @BeforeClass and @AfterClass methods. Although not quite as clean as the above method, I think it will work for you.

As for the problem with failed tests, you can set maven.test.error.ignore so that the build continues on failed tests. This is not recommended as a continuing practice, but it should get you functioning until all of your tests pass. For more detail, see the maven surefire documentation.

How can I clear the input text after clicking

This worked for me:

    **//Click The Button**    
    $('#yourButton').click(function(){

         **//What you want to do with your button**
         //YOUR CODE COMES HERE

         **//CLEAR THE INPUT**
         $('#yourInput').val('');

});

So first, you select your button with jQuery:

$('#button').click(function((){ //Then you get the input element $('#input')
    //Then you clear the value by adding:
    .val(' '); });

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

PHP - count specific array values

If you want to count ALL the same occurences inside the array, here's a function to count them all, and return the results as a multi-dimensional array:

function countSame($array) {

$count = count($array);
$storeArray = array();
while ($count > 0) {
$count--;

if ($array[$count]) {
$a = $array[$count];
$counts = array_count_values($array);
$counts = $counts[$a];
$tempArray = array($a, $counts);
array_push($storeArray, $tempArray);

$keys = array_keys($array, $a);
foreach ($keys as $k) {
unset($array[$k]);
} //end of foreach ($keys as $k)
} //end of if ($array[$count])

} //end of while ($count > 0)

return $storeArray;

} //end of function countSame($array)

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Database, Table and Column Naming Conventions?

Naming conventions allow the development team to design discovereability and maintainability at the heart of the project.

A good naming convention takes time to evolve but once it’s in place it allows the team to move forward with a common language. A good naming convention grows organically with the project. A good naming convention easily copes with changes during the longest and most important phase of the software lifecycle - service management in production.

Here are my answers:

  1. Yes, table names should be plural when they refer to a set of trades, securities, or counterparties for example.
  2. Yes.
  3. Yes. SQL tables are prefixed with tb_, views are prefixed vw_, stored procedures are prefixed usp_ and triggers are prefixed tg_ followed by the database name.
  4. Column name should be lower case separated by underscore.

Naming is hard but in every organisation there is someone who can name things and in every software team there should be someone who takes responsibility for namings standards and ensures that naming issues like sec_id, sec_value and security_id get resolved early before they get baked into the project.

So what are the basic tenets of a good naming convention and standards: -

  • Use the language of your client and your solution domain
  • Be descriptive
  • Be consistent
  • Disambiguate, reflect and refactor
  • Don’t use abbreviations unless they are clear to everyone
  • Don’t use SQL reserved keywords as column names

Read SQL Table into C# DataTable

Vendor independent version, solely relies on ADO.NET interfaces; 2 ways:

public DataTable Read1<T>(string query) where T : IDbConnection, new()
{
    using (var conn = new T())
    {
        using (var cmd = conn.CreateCommand())
        {
            cmd.CommandText = query;
            cmd.Connection.ConnectionString = _connectionString;
            cmd.Connection.Open();
            var table = new DataTable();
            table.Load(cmd.ExecuteReader());
            return table;
        }
    }
}

public DataTable Read2<S, T>(string query) where S : IDbConnection, new() 
                                           where T : IDbDataAdapter, IDisposable, new()
{
    using (var conn = new S())
    {
        using (var da = new T())
        {
            using (da.SelectCommand = conn.CreateCommand())
            {
                da.SelectCommand.CommandText = query;
                da.SelectCommand.Connection.ConnectionString = _connectionString;
                DataSet ds = new DataSet(); //conn is opened by dataadapter
                da.Fill(ds);
                return ds.Tables[0];
            }
        }
    }
}

I did some performance testing, and the second approach always outperformed the first.

Stopwatch sw = Stopwatch.StartNew();
DataTable dt = null;
for (int i = 0; i < 100; i++)
{
    dt = Read1<MySqlConnection>(query); // ~9800ms
    dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms

    dt = Read1<SQLiteConnection>(query); // ~4000ms
    dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms

    dt = Read1<SqlCeConnection>(query); // ~5700ms
    dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms

    dt = Read1<SqlConnection>(query); // ~850ms
    dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms

    dt = Read1<VistaDBConnection>(query); // ~3900ms
    dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms
}
sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

Read1 looks better on eyes, but data adapter performs better (not to confuse that one db outperformed the other, the queries were all different). The difference between the two depended on query though. The reason could be that Load requires various constraints to be checked row by row from the documentation when adding rows (its a method on DataTable) while Fill is on DataAdapters which were designed just for that - fast creation of DataTables.

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

HTML input number type allows "e/E" because "e" stands for exponential which is a numeric symbol.

Example 200000 can also be written as 2e5. I hope this helps thank you for the question.

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

Bash foreach loop

xargs --arg-file inputfile cat

This will output the filename followed by the file's contents:

xargs --arg-file inputfile -I % sh -c "echo %; cat %"

How to add label in chart.js for pie chart

Rachel's solution is working fine, although you need to use the third party script from raw.githubusercontent.com

By now there is a feature they show on the landing page when advertisng the "modular" script. You can see a legend there with this structure:

<div class="labeled-chart-container">
    <div class="canvas-holder">
        <canvas id="modular-doughnut" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
    </div>

<ul class="doughnut-legend">
    <li><span style="background-color:#5B90BF"></span>Core</li>
    <li><span style="background-color:#96b5b4"></span>Bar</li>
    <li><span style="background-color:#a3be8c"></span>Doughnut</li>
    <li><span style="background-color:#ab7967"></span>Radar</li>
    <li><span style="background-color:#d08770"></span>Line</li>
    <li><span style="background-color:#b48ead"></span>Polar Area</li>
</ul>
</div>

To achieve this they use the chart configuration option legendTemplate

legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"

You can find the doumentation here on chartjs.org This works for all the charts although it is not part of the global chart configuration.

Then they create the legend and add it to the DOM like this:

var legend = myPie.generateLegend();
$("#legend").html(legend);

Sample See also my JSFiddle sample

Android layout replacing a view with another view on run time

And if you do that very often, you could use a ViewSwitcher or a ViewFlipper to ease view substitution.

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

How to kill a nodejs process in Linux?

sudo netstat -lpn |grep :'3000'

3000 is port i was looking for, After first command you will have Process ID for that port

kill -9 1192

in my case 1192 was process Id of process running on 3000 PORT use -9 for Force kill the process

JavaScript Number Split into individual digits

You can try this.

  var num = 99;

  num=num.toString().split("").map(value=>parseInt(value,10)); //output [9,9]

Hope this helped!

How to amend a commit without changing commit message (reusing the previous one)?

To extend on the accepted answer, you can also do:

git commit --amend --no-edit -a

to add the currently changed files.

sizing div based on window width

Try absolute positioning:

<div style="position:relative;width:100%;">
    <div id="help" style="
    position:absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index:1;">
        <img src="/portfolio/space_1_header.png" border="0" style="width:100%;">
    </div>
</div>

NodeJS / Express: what is "app.use"?

app.use() works like that:

  1. Request event trigered on node http server instance.
  2. express does some of its inner manipulation with req object.
  3. This is when express starts doing things you specified with app.use

which very simple.

And only then express will do the rest of the stuff like routing.

Facebook Callback appends '#_=_' to Return URL

If you're using vue-router, you can append to the list of routes:

{
  path: '/_=_',
  redirect: '/', // <-- or other default route
},

Count elements with jQuery

try this:

var count_element = $('.element').length

Getting A File's Mime Type In Java

To chip in with my 5 cents:

TL,DR

I use MimetypesFileTypeMap and add any mime that is not there and I specifically need it, into mime.types file.

And now, the long read:

First of all, MIME types list is huge, see here: https://www.iana.org/assignments/media-types/media-types.xhtml

I like to use standard facilities provided by JDK first, and if that doesn't work, I'll go and look for something else.

Determine file type from file extension

Since 1.6, Java has MimetypesFileTypeMap, as pointed in one of the answers above, and it is the simplest way to determine mime type:

new MimetypesFileTypeMap().getContentType( fileName );

In its vanilla implementation this does not do much (i.e. it works for .html but it doesn't for .png). It is, however, super simple to add any content type you may need:

  1. Create file named 'mime.types' in META-INF folder in your project
  2. Add a line for every mime type you need and default implementation doesn't provide (there are hundreds of mime types and list grows as time goes by).

Example entries for png and js files would be:

image/png png PNG
application/javascript js

For mime.types file format, see more details here: https://docs.oracle.com/javase/7/docs/api/javax/activation/MimetypesFileTypeMap.html

Determine file type from file content

Since 1.7, Java has java.nio.file.spi.FileTypeDetector, which defines a standard API for determining a file type in implementation specific way.

To fetch mime type for a file, you would simply use Files and do this in your code:

Files.probeContentType(Paths.get("either file name or full path goes here"));

The API definition provides for facilities that support either for determining file mime type from file name or from file content (magic bytes). That is why probeContentType() method throws IOException, in case an implementation of this API uses Path provided to it to actually try to open the file associated with it.

Again, vanilla implementation of this (the one that comes with JDK) leaves a lot to be desired.

In some ideal world in a galaxy far, far away, all these libraries which try to solve this file-to-mime-type problem would simply implement java.nio.file.spi.FileTypeDetector, you would drop in the preferred implementing library's jar file into your classpath and that would be it.

In the real world, the one where you need TL,DR section, you should find the library with most stars next to it's name and use it. For this particular case, I don't need one (yet ;) ).

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

ls -ltrh /proc | grep YOUR-PID-HERE

For example, my Google Chrome's PID is 11583:

ls -l /proc | grep 11583
dr-xr-xr-x  7 adam       adam                     0 2011-04-20 16:34 11583

How can I view array structure in JavaScript with alert()?

If what you want is to show with an alert() the content of an array of objects, i recomend you to define in the object the method toString() so with a simple alert(MyArray); the full content of the array will be shown in the alert.

Here is an example:

//-------------------------------------------------------------------
// Defininf the Point object
function Point(CoordenadaX, CoordenadaY) {
    // Sets the point coordinates depending on the parameters defined
    switch (arguments.length) {
        case 0:
            this.x = null;
            this.y = null;
            break;
        case 1:
            this.x = CoordenadaX;
            this.y = null;
            break;
        case 2:
            this.x = CoordenadaX;
            this.y = CoordenadaY;
            break;
    }
    // This adds the toString Method to the point object so the 
    // point can be printed using alert();
    this.toString = function() {
        return " (" + this.x + "," + this.y + ") ";
    };
 }

Then if you have an array of points:

var MyArray = [];
MyArray.push ( new Point(5,6) );
MyArray.push ( new Point(7,9) );

You can print simply calling:

alert(MyArray);

Hope this helps!

Simple URL GET/POST function in Python

I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)

#!/usr/bin/env python3
import http.client
import json

print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)


print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)


print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)


print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)

How can I run a html file from terminal?

It is possible to view a html file from terminal using lynx or links. But none of those browswers support the onload javascript feature. By using lynx or links you will have to actively click the submit button.

Default passwords of Oracle 11g?

It is possible to connect to the database without specifying a password. Once you've done that you can then reset the passwords. I'm assuming that you've installed the database on your machine; if not you'll first need to connect to the machine the database is running on.

  1. Ensure your user account is a member of the dba group. How you do this depends on what OS you are running.

  2. Enter sqlplus / as sysdba in a Command Prompt/shell/Terminal window as appropriate. This should log you in to the database as SYS.

  3. Once you're logged in, you can then enter

    alter user SYS identified by "newpassword";
    

    to reset the SYS password, and similarly for SYSTEM.

(Note: I haven't tried any of this on Oracle 12c; I'm assuming they haven't changed things since Oracle 11g.)

How do you set EditText to only accept numeric values in Android?

For only digits input use android:inputType="numberPassword" along with editText.setTransformationMethod(null); to remove auto-hiding of the number.

OR

android:inputType="phone"

For only digits input, I feel these couple ways are better than android:inputType="number". The limitation of mentioning "number" as inputType is that the keyboard allows to switch over to characters and also lets other special characters be entered. "numberPassword" inputType doesn't have those issues as the keyboard only shows digits. Even "phone" inputType works as the keyboard doesnt allow you to switch over to characters. But you can still enter couple special characters like +, /, N, etc.

android:inputType="numberPassword" with editText.setTransformationMethod(null);

inputType="numberPassword"

inputType="phone"

inputType="phone"

inputType="number"

inputType="number"

java.math.BigInteger cannot be cast to java.lang.Integer

You can use:

Integer grandChildCount = ((BigInteger) result[1]).intValue();

Or perhaps cast to Number to cover both Integer and BigInteger values.

Convert int to a bit array in .NET

I would achieve it in a one-liner as shown below:

using System;
using System.Collections;

namespace stackoverflowQuestions
{
    class Program
    {
        static void Main(string[] args)
        {    
            //get bit Array for number 20
            var myBitArray = new BitArray(BitConverter.GetBytes(20));
        }
    }
}

Please note that every element of a BitArray is stored as bool as shown in below snapshot:

enter image description here

So below code works:

if (myBitArray[0] == false)
{
    //this code block will execute
}

but below code doesn't compile at all:

if (myBitArray[0] == 0)
{
    //some code
}

Do copyright dates need to be updated?

The copyright notice on a work establishes a claim to copyright. The date on the notice establishes how far back the claim is made. This means if you update the date, you are no longer claiming the copyright for the original date and that means if somebody has copied the work in the meantime and they claim its theirs on the ground that their publishing the copy was before your claim, then it will be difficult to establish who is the originator of the work.

Therefore, if the claim is based on common law copyright (not formally registered), then the date should be the date of first publication. If the claim is a registered copyright, then the date should be the date claimed in the registration. In cases where the work was substantially revised you may establish a new copyright claim to the revised work by adding another copyright notice with a newer date or by adding an additional date to the existing notice as in "© 2000, 2010". Again, the added date establishes how far back the claim is made on the revision.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

1.a. Add following in applicationContext-mvc.xml

xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc

  1. add jackson library

The type is defined in an assembly that is not referenced, how to find the cause?

For me, this was caused by the project both directly and indirectly (through another dependency) referencing two different builds of Bouncy Castle that had different assembly names. One of the Bouncy Castle builds was the NuGet package, the other one was a debug build of the source downloaded from GitHub. Both were nominally version 1.8.1, but the project settings of the GitHub code set the assembly name to BouncyCastle whereas the NuGet package had the assembly name BouncyCastle.Crypto. Changing the project settings, thus aligning the assembly names, fixed the problem.

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How to get div height to auto-adjust to background size?

I solved this using jQuery. Until new CSS rules allow for this type of behavior natively I find it is the best way to do it.

Setup your divs

Below you have your div that you want the background to appear on ("hero") and then the inner content/text you want to overlay on top of your background image ("inner"). You can (and should) move the inline styles to your hero class. I left them here so it's quick and easy to see what styles are applied to it.

<div class="hero" style="background-image: url('your-image.png'); background-size: 100%; background-repeat: no-repeat; width: 100%;">
    <div class="inner">overlay content</div>
</div>

Calculate image aspect ratio

Next calculate your aspect ratio for your image by dividing the height of your image by the width. For example, if your image height is 660 and your width is 1280 your aspect ratio is 0.5156.

Setup a jQuery window resize event to adjust height

Finally, add a jQuery event listener for window resize and then calculate your hero div's height based off of the aspect ratio and update it. This solution typically leaves an extra pixel at the bottom due to imperfect calculations using the aspect ratio so we add a -1 to the resulting size.

$(window).on("resize", function ()
{
    var aspect_ratio = .5156; /* or whatever yours is */
    var new_hero_height = ($(window).width()*aspect_ratio) - 1;
    $(".hero").height(new_hero_height);
}

Ensure it works on page load

You should perform the resize call above when the page loads to have the image sizes calculated at the outset. If you don't, then the hero div won't adjust until you resize the window. I setup a separate function to do the resize adjustments. Here's the full code I use.

function updateHeroDiv()
{
    var aspect_ratio = .5156; /* or whatever yours is */
    var new_hero_height = ($(window).width()*aspect_ratio) - 1;
    $(".hero").height(new_hero_height);
}

$(document).ready(function() 
{       
    // calls the function on page load
    updateHeroDiv(); 

    // calls the function on window resize
    $(window).on("resize", function ()
    {
        updateHeroDiv();        
    }
});

How to draw circle in html page?

It is quite possible in HTML 5. Your options are: Embedded SVG and <canvas> tag.

To draw circle in embedded SVG:

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
    <circle cx="50" cy="50" r="50" fill="red" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Circle in <canvas>:

_x000D_
_x000D_
var canvas = document.getElementById("circlecanvas");_x000D_
var context = canvas.getContext("2d");_x000D_
context.arc(50, 50, 50, 0, Math.PI * 2, false);_x000D_
context.fillStyle = "red";_x000D_
context.fill()
_x000D_
<canvas id="circlecanvas" width="100" height="100"></canvas>
_x000D_
_x000D_
_x000D_

Builder Pattern in Effective Java

To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder

Find Number of CPUs and Cores per CPU using Command Prompt

You can also enter msinfo32 into the command line.

It will bring up all your system information. Then, in the find box, just enter processor and it will show you your cores and logical processors for each CPU. I found this way to be easiest.

MySQL - Replace Character in Columns

Just running the SELECT statement will have no effect on the data. You have to use an UPDATE statement with the REPLACE to make the change occur:

UPDATE photos
   SET caption = REPLACE(caption,'"','\'')

Here is a working sample: http://sqlize.com/7FjtEyeLAh

jQuery get the id/value of <li> element after click function

you can get the value of the respective li by using this method after click

HTML:-

<!DOCTYPE html>
<html>
<head>
    <title>show the value of li</title>
    <link rel="stylesheet"  href="pathnameofcss">
</head>
<body>

    <div id="user"></div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <ul id="pageno">
    <li value="1">1</li>
    <li value="2">2</li>
    <li value="3">3</li>
    <li value="4">4</li>
    <li value="5">5</li>
    <li value="6">6</li>
    <li value="7">7</li>
    <li value="8">8</li>
    <li value="9">9</li>
    <li value="10">10</li>

    </ul>

    <script src="pathnameofjs" type="text/javascript"></script>
</body>
</html>

JS:-

$("li").click(function ()
{       
var a = $(this).attr("value");

$("#user").html(a);//here the clicked value is showing in the div name user
console.log(a);//here the clicked value is showing in the console
});

CSS:-

ul{
display: flex;
list-style-type:none;
padding: 20px;
}

li{
padding: 20px;
}

VB.Net Properties - Public Get, Private Set

If you are using VS2010 or later it is even easier than that

Public Property Name as String

You get the private properties and Get/Set completely for free!

see this blog post: Scott Gu's Blog

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

PHP float with 2 decimal places: .00

try this

$result = number_format($FloatNumber, 2);

Python in Xcode 4+?

This thread is old, but to chime in for Xcode Version 8.3.3, Tyler Crompton's method in the accepted answer still works (some of the names are very slightly different, but not enough to matter).

2 points where I struggled slightly:

Step 16: If the python executable you want is greyed out, right click it and select quick look. Then close the quick look window, and it should now be selectable.

Step 19: If this isn’t working for you, you can enter the name of just the python file in the Arguments tab, and then enter the project root directory explicitly in the Options tab under Working Directory--check the “Use custom working directory” box, and type in your project root directory in the field below it.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How to convert float number to Binary?

x = float(raw_input("enter number between 0 and 1: "))

p = 0
while ((2**p)*x) %1 != 0:
    p += 1
    # print p

    num = int (x * (2 ** p))
    # print num

    result = ''
    if num == 0:
        result = '0'
    while num > 0:
        result = str(num%2) + result
        num = num / 2

    for i in range (p - len(result)):
        result = '0' + result
    result = result[0:-p] + '.' + result[-p:]

print result #this will print result for the decimal portion

How can I make Java print quotes, like "Hello"?

Escape double-quotes in your string: "\"Hello\""

More on the topic (check 'Escape Sequences' part)

iTunes Connect: How to choose a good SKU?

SKU stands for Stock-keeping Unit. It's more for inventory tracking purpose.

The purpose of having an SKU is so that you can tie the app sales to whatever internal SKU number that your accounting is using.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Import and insert sql.gz file into database with putty

Without a separate step to extract the archive:

# import gzipped-mysql dump
gunzip < DUMP_FILE.sql.gz | mysql --user=DB_USER --password DB_NAME

I use the above snippet to re-import mysqldump-backups, and the following for backing it up.

# mysqldump and gzip (-9 ? highest compression)
mysqldump --user=DB_USER --password DB_NAME | gzip -9 > DUMP_FILE.sql.gz

ASP.NET Web Application Message Box

You want to use an Alert. Unfortunately it's not as nice as with windows forms.

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);

Similar to this question here: http://forums.asp.net/t/1461308.aspx/1

css absolute position won't work with margin-left:auto margin-right: auto

When you are defining styles for division which is positioned absolutely, they specifying margins are useless. Because they are no longer inside the regular DOM tree.

You can use float to do the trick.

.divtagABS {
    float: left;
    margin-left: auto;  
    margin-right:auto;
 }

Decimal to Hexadecimal Converter in Java

Here is the code for any number :

import java.math.BigInteger;

public class Testing {

/**
 * @param args
 */
static String arr[] ={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; 
public static void main(String[] args) {
    String value = "214";
    System.out.println(value + " : " + getHex(value));
}


public static String getHex(String value) {
    String output= "";
    try {
        Integer.parseInt(value);
        Integer number = new Integer(value);
        while(number >= 16){
            output = arr[number%16] + output;
            number = number/16;
        }
        output = arr[number]+output;

    } catch (Exception e) {
        BigInteger number = null;
        try{
            number = new BigInteger(value);
        }catch (Exception e1) {
            return "Not a valid numebr";
        }
        BigInteger hex = new BigInteger("16");
        BigInteger[] val = {};

        while(number.compareTo(hex) == 1 || number.compareTo(hex) == 0){
            val = number.divideAndRemainder(hex);
            output = arr[val[1].intValue()] + output;
            number = val[0];
        }
        output = arr[number.intValue()] + output;
    }

    return output;
}

}

jQuery - get all divs inside a div with class ".container"

To get all divs under 'container', use the following:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #id instead of div to get a particular one.

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

$(".container>div[id=]")

jQuery: get data attribute

This works for me

$('.someclass').click(function() {
    $varName = $(this).data('fulltext');
    console.log($varName);
});

How to convert string to date to string in Swift iOS?

First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

Swift 3

let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")

let dateObj = dateFormatter.date(from: dateString)

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

The printed result is: Dateobj: 10-22-2015

How to pass arguments from command line to gradle

There's a great example here:

https://kb.novaordis.com/index.php/Gradle_Pass_Configuration_on_Command_Line

Which details that you can pass parameters and then provide a default in an ext variable like so:

gradle -Dmy_app.color=blue

and then reference in Gradle as:

ext {
   color = System.getProperty("my_app.color", "red");
}

And then anywhere in your build script you can reference it as course anywhere you can reference it as project.ext.color

More tips here: https://kb.novaordis.com/index.php/Gradle_Variables_and_Properties

Converting string to byte array in C#

static byte[] GetBytes(string str)
{
     byte[] bytes = new byte[str.Length * sizeof(char)];
     System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     return bytes;
}

static string GetString(byte[] bytes)
{
     char[] chars = new char[bytes.Length / sizeof(char)];
     System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     return new string(chars);
}

Source file 'Properties\AssemblyInfo.cs' could not be found

This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.

How to create empty text file from a batch file?

copy NUL EmptyFile.txt

DOS has a few special files (devices, actually) that exist in every directory, NUL being the equivalent of UNIX's /dev/null: it's a magic file that's always empty and throws away anything you write to it. Here's a list of some others; CON is occasionally useful as well.

To avoid having any output at all, you can use

copy /y NUL EmptyFile.txt >NUL

/y prevents copy from asking a question you can't see when output goes to NUL.

How to select first child with jQuery?

Use the :first-child selector.

In your example...

$('div.alldivs div:first-child')

This will also match any first child descendents that meet the selection criteria.

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

For the first matched only, use the :first selector.

Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

$('div.alldivs > div:first-child')

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

How to get last N records with activerecord?

new way to do it in rails 3.1 is SomeModel.limit(5).order('id desc')

How to align LinearLayout at the center of its parent?

@jksschneider explation is almost right. Make sure that you haven't set any gravity to parent layout, and then set layout_gravity="center" to your view or layout.

Command line for looking at specific port

To improve upon @EndUzr's response:

To find a foreign port (IPv4 or IPv6) you can use:

netstat -an | findstr /r /c:":N [^:]*$"

To find a local port (IPv4 or IPv6) you can use:

netstat -an | findstr /r /c:":N *[^ ]*:[^ ]* "

Where N is the port number you are interested in. The "/r" switch tells it to process it as regexp. The "/c" switch allows findstr to include spaces within search strings instead of treating a space as a search string delimiter. This added space prevents longer ports being mistreated - for example, ":80" vs ":8080" and other port munging issues.

To list remote connections to the local RDP server, for example:

netstat -an | findstr /r /c:":3389 *[^ ]*:[^ ]*"

Or to see who is touching your DNS:

netstat -an | findstr /r /c:":53 *[^ ]*:[^ ]*"

If you want to exclude local-only ports you can use a series of exceptions with "/v" and escape characters with a backslash:

netstat -an | findstr /v "0.0.0.0 127.0.0.1 \[::\] \[::1\] \*\:\*" | findstr /r /c:":80 *[^ ]*:[^ ]*"

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

How to check if all of the following items are in a list?

Operators like <= in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.

Use the equivalent and more clearly-named method, set.issubset. Note that you don't need to convert the argument to a set; it'll do that for you if needed.

set(['a', 'b']).issubset(['a', 'b', 'c'])

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

If you want this behaviour everywhere in your app and don't want to add anything to individual viewDidAppear etc. then you should create a subclass

class QFNavigationController:UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()
        interactivePopGestureRecognizer?.delegate = self
        delegate = self
    }

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        super.pushViewController(viewController, animated: animated)
        interactivePopGestureRecognizer?.isEnabled = false
    }

    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        interactivePopGestureRecognizer?.isEnabled = true
    }

    // IMPORTANT: without this if you attempt swipe on
    // first view controller you may be unable to push the next one
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return viewControllers.count > 1
    }

}

Now, whenever you use QFNavigationController you get the desired experience.

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

How to run a PowerShell script

  • Give the path of the script, that is, path setting by cmd:

    $> . c:\program file\prog.ps1

  • Run the entry point function of PowerShell:

    For example, $> add or entry_func or main

Node.js client for a socket.io server

After installing socket.io-client:

npm install socket.io-client

This is how the client code looks like:

var io = require('socket.io-client'),
socket = io.connect('localhost', {
    port: 1337
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });

Thanks alessioalex.

Java 8 stream reverse order

Many of the solutions here sort or reverse the IntStream, but that unnecessarily requires intermediate storage. Stuart Marks's solution is the way to go:

static IntStream revRange(int from, int to) {
    return IntStream.range(from, to).map(i -> to - i + from - 1);
}

It correctly handles overflow as well, passing this test:

@Test
public void testRevRange() {
    assertArrayEquals(revRange(0, 5).toArray(), new int[]{4, 3, 2, 1, 0});
    assertArrayEquals(revRange(-5, 0).toArray(), new int[]{-1, -2, -3, -4, -5});
    assertArrayEquals(revRange(1, 4).toArray(), new int[]{3, 2, 1});
    assertArrayEquals(revRange(0, 0).toArray(), new int[0]);
    assertArrayEquals(revRange(0, -1).toArray(), new int[0]);
    assertArrayEquals(revRange(MIN_VALUE, MIN_VALUE).toArray(), new int[0]);
    assertArrayEquals(revRange(MAX_VALUE, MAX_VALUE).toArray(), new int[0]);
    assertArrayEquals(revRange(MIN_VALUE, MIN_VALUE + 1).toArray(), new int[]{MIN_VALUE});
    assertArrayEquals(revRange(MAX_VALUE - 1, MAX_VALUE).toArray(), new int[]{MAX_VALUE - 1});
}

<div> cannot appear as a descendant of <p>

The warning appears only because the demo code has:

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>  // <==NOTE P TAG HERE
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

Changing it like this takes care of it:

function TabPanel(props) {
    const {children, value, index, classes, ...other} = props;

    return (
        <div
            role="tabpanel"
            hidden={value !== index}
            id={`simple-tabpanel-${index}`}
            aria-labelledby={`simple-tab-${index}`}
            {...other}
        >
            {value === index && (
                <Container>
                    <Box>   // <== P TAG REMOVED
                        {children}
                    </Box>
                </Container>
            )}
        </div>
    );
}

Android Support Design TabLayout: Gravity Center and Mode Scrollable

add this line in your actiity when you adding tabs in tablayout

 tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); 

How to scroll the window using JQuery $.scrollTo() function

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

Open button in new window?

<input type="button" onclick="window.open(); return false;" value="click me" />

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

Convert int to string?

None of the answers mentioned that the ToString() method can be applied to integer expressions

Debug.Assert((1000*1000).ToString()=="1000000");

even to integer literals

Debug.Assert(256.ToString("X")=="100");

Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...

HTML5 Email Validation

I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.

Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.

var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=email]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            this.setCustomValidity('');
        }
    });
})

How to loop through an array containing objects and access their properties

This might help somebody. Maybe it's a bug in Node.

var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;

This doesn't work:

while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined

But this works...

while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.

This works too...

while ((arr[c]) && (arr[c].name)) { c++; }

BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.

while ((arr[c].name) && (arr[c])) { c++; }

Error says the array is undefined, but it's not :-/ Node v11.15.0

Subtract 1 day with PHP

A one-liner option is:

echo date_create('2011-04-24')->modify('-1 days')->format('Y-m-d');

Running it on Online PHP Editor.


mktime alternative

If you prefer to avoid using string methods, or going into calculations, or even creating additional variables, mktime supports subtraction and negative values in the following way:

// Today's date
echo date('Y-m-d'); // 2016-03-22

// Yesterday's date
echo date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-1, date("Y"))); // 2016-03-21

// 42 days ago
echo date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-42, date("Y"))); // 2016-02-09

//Using a previous date object
$date_object = new DateTime('2011-04-24');
echo date('Y-m-d',
  mktime(0, 0, 0,
     $date_object->format("m"),
     $date_object->format("d")-1,
     $date_object->format("Y")
    )
); // 2011-04-23

Online PHP Editor

Twitter Bootstrap carousel different height images cause bouncing arrows

Try this (I'm using SASS):

.carousel {
  max-height: 700px;
  overflow: hidden;

  .item img {
    width: 100%;
    height: auto;
  }
}

You can wrap the .carousel into a .container if you wish.

How to add form validation pattern in Angular 2?

My solution with Angular 4.0.1: Just showing the UI for required CVC input - where the CVC must be exactly 3 digits:

    <form #paymentCardForm="ngForm">         
...
        <md-input-container align="start">
            <input #cvc2="ngModel" mdInput type="text" id="cvc2" name="cvc2" minlength="3" maxlength="3" placeholder="CVC" [(ngModel)]="paymentCard.cvc2" [disabled]="isBusy" pattern="\d{3}" required />
            <md-hint *ngIf="cvc2.errors && (cvc2.touched || submitted)" class="validation-result">
                <span [hidden]="!cvc2.errors.required && cvc2.dirty">
                    CVC is required.
                </span>
                <span [hidden]="!cvc2.errors.minlength && !cvc2.errors.maxlength && !cvc2.errors.pattern">
                    CVC must be 3 numbers.
                </span>
            </md-hint>
        </md-input-container>
...
<button type="submit" md-raised-button color="primary" (click)="confirm($event, paymentCardForm.value)" [disabled]="isBusy || !paymentCardForm.valid">Confirm</button>
</form>

Android soft keyboard covers EditText field

add this single line to your relative activity where key board cover edit text.inside onCreat()method of activity.

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

Using $ docker inspect Incase the Image has no /bin/bash in the output, you can use command below: it worked for me perfectly

$ docker exec -it <container id> sh

How to use JUnit to test asynchronous processes

There are many answers here but a simple one is to just create a completed CompletableFuture and use it:

CompletableFuture.completedFuture("donzo")

So in my test:

this.exactly(2).of(mockEventHubClientWrapper).sendASync(with(any(LinkedList.class)));
this.will(returnValue(new CompletableFuture<>().completedFuture("donzo")));

I am just making sure all of this stuff gets called anyway. This technique works if you are using this code:

CompletableFuture.allOf(calls.toArray(new CompletableFuture[0])).join();

It will zip right through it as all the CompletableFutures are finished!

What are the rules for calling the superclass constructor?

The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.

Class2::Class2(string id) : Class1(id) {
....
}

Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.

Regex to remove all special characters from string?

You can use:

string regExp = "\\W";

This is equivalent to Daniel's "[^a-zA-Z0-9]"

\W matches any nonword character. Equivalent to the Unicode categories [^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}].

Regex date format validation on Java

Below added code is working for me if you are using pattern dd-MM-yyyy.

public boolean isValidDate(String date) {
        boolean check;
        String date1 = "^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-([12][0-9]{3})$";
        check = date.matches(date1);

        return check;
    }

Ping with timestamp on Windows CLI

I think my code its what everyone need:

ping -w 5000 -t -l 4000 -4 localhost|cmd /q /v /c "(pause&pause)>nul &for /l %a in () do (for /f "delims=*" %a in ('powershell get-date -format "{ddd dd-MMM-yyyy HH:mm:ss}"') do (set datax=%a) && set /p "data=" && echo([!datax!] - !data!)&ping -n 2 localhost>nul"

to display:

[Fri 09-Feb-2018 11:55:03] - Pinging localhost [127.0.0.1] with 4000 bytes of data:
[Fri 09-Feb-2018 11:55:05] - Reply from 127.0.0.1: bytes=4000 time<1ms TTL=128
[Fri 09-Feb-2018 11:55:08] - Reply from 127.0.0.1: bytes=4000 time<1ms TTL=128
[Fri 09-Feb-2018 11:55:11] - Reply from 127.0.0.1: bytes=4000 time<1ms TTL=128
[Fri 09-Feb-2018 11:55:13] - Reply from 127.0.0.1: bytes=4000 time<1ms TTL=128

note: code to be used inside a command line, and you must have powershell preinstalled on os.

How to calculate growth with a positive and negative number?

Formula should be this one:

=(thisYear+IF(LastYear<0,ABS(LastYear),0))/ABS(LastYear)-100%

The IF value if < 0 is added to your Thisyear value to generate the real difference.

If > 0, the LastYear value is 0

Seems to work in different scenarios checked

How to delete all files from a specific folder?

System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

foreach (FileInfo file in myDirInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
    dir.Delete(true); 
}

Make a Bash alias that takes a parameter?

An alternative solution is to use marker, a tool I've created recently that allows you to "bookmark" command templates and easily place cursor at command place-holders:

commandline marker

I found that most of time, I'm using shell functions so I don't have to write frequently used commands again and again in the command-line. The issue of using functions for this use case, is adding new terms to my command vocabulary and having to remember what functions parameters refer to in the real-command. Marker goal is to eliminate that mental burden.

How to decorate a class?

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

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

Example:

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

class FooMeta(type):

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

class Foo(object):

    __metaclass__ = FooMeta

    def __init__(self, value1):
        pass

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

How to sort List<Integer>?

Use Collections class API to sort.

Collections.sort(list);

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Reading Excel files from C#

Here's some code I wrote in C# using .NET 1.1 a few years ago. Not sure if this would be exactly what you need (and may not be my best code :)).

using System;
using System.Data;
using System.Data.OleDb;

namespace ExportExcelToAccess
{
    /// <summary>
    /// Summary description for ExcelHelper.
    /// </summary>
    public sealed class ExcelHelper
    {
        private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=Yes;\";";

        public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)
        {
            OleDbConnection objConnection = new OleDbConnection();
            objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));
            DataSet dsImport = new DataSet();

            try
            {
                objConnection.Open();

                DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
                {
                    //raise exception if needed
                }

                if( (null != sheetName) && (0 != sheetName.Length))
                {
                    if( !CheckIfSheetNameExists(sheetName, dtSchema) )
                    {
                        //raise exception if needed
                    }
                }
                else
                {
                    //Reading the first sheet name from the Excel file.
                    sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
                }

                new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport);
            }
            catch (Exception)
            {
                //raise exception if needed
            }
            finally
            {
                // Clean up.
                if(objConnection != null)
                {
                    objConnection.Close();
                    objConnection.Dispose();
                }
            }


            return dsImport.Tables[0];
            #region Commented code for importing data from CSV file.
            //              string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
            //
            //              System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);
            //              new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport);
            //              return dsImport.Tables[0];

            #endregion
        }

        /// <summary>
        /// This method checks if the user entered sheetName exists in the Schema Table
        /// </summary>
        /// <param name="sheetName">Sheet name to be verified</param>
        /// <param name="dtSchema">schema table </param>
        private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)
        {
            foreach(DataRow dataRow in dtSchema.Rows)
            {
                if( sheetName == dataRow["TABLE_NAME"].ToString() )
                {
                    return true;
                }   
            }
            return false;
        }
    }
}

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

When using the Docker compose files, publish, publishes to obj/Docker/Publish. When I copied my files there and pointed my Dockerfile to this directory (as generated), it works…

What is recursion and when should I use it?

Recursion is the process where a method call iself to be able to perform a certain task. It reduces redundency of code. Most recurssive functions or methods must have a condifiton to break the recussive call i.e. stop it from calling itself if a condition is met - this prevents the creating of an infinite loop. Not all functions are suited to be used recursively.

Git copy file preserving history

For completeness, I would add that, if you wanted to copy an entire directory full of controlled AND uncontrolled files, you could use the following:

git mv old new
git checkout HEAD old

The uncontrolled files will be copied over, so you should clean them up:

git clean -fdx new

How can I convert string to datetime with format specification in JavaScript?

To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822, if you use yyyy-mm-dd parse may do a mistakes.

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

Where can I find a list of escape characters required for my JSON ajax return type?

Take a look at http://json.org/. It claims a bit different list of escaped characters than Chris proposed.

\"
\\
\/
\b
\f
\n
\r
\t
\u four-hex-digits

font-weight is not working properly?

font-weight can also fail to work if the font you are using does not have those weights in existence – you will often hit this when embedding custom fonts. In those cases the browser will likely round the number to the closest weight that it does have available.

For example, if I embed the following font...

@font-face {
    font-family: 'Nexa';
    src: url(...);
    font-weight: 300;
    font-style: normal;
}

Then I will not be able to use anything other than a weight of 300. All other weights will revert to 300, unless I specify additional @font-face declarations with those additional weights.

Insert data to MySql DB and display if insertion is success or failure

After INSERT query you can use ROW_COUNT() to check for successful insert operation as:

SELECT IF(ROW_COUNT() = 1,  "Insert Success", "Insert Failed") As status;

Where can I find php.ini?

There are several valid ways already mentioned for locating the php.ini file, but if you came across this page because you want to do something with it in a bash script:

path_php_ini="$(php -i | grep 'Configuration File (php.ini) Path' | grep -oP '(?<=\=\>\s).*')" echo ${path_php_ini}

NPM clean modules

You can just delete the node_module directory

rm -rf node_modules/

How do I use the built in password reset/change views with my own templates

If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

The b-list has a good introduction to context processors.

Edit (I seem to have been confused about what the actual question was):

You'll notice that password_reset takes a named parameter called template_name:

def password_reset(request, is_admin_site=False, 
            template_name='registration/password_reset_form.html',
            email_template_name='registration/password_reset_email.html',
            password_reset_form=PasswordResetForm, 
            token_generator=default_token_generator,
            post_reset_redirect=None):

Check password_reset for more information.

... thus, with a urls.py like:

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset

urlpatterns = patterns('',
     (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
     ...
)

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

Calculate the date yesterday in JavaScript

"Date.now() - 86400000" won't work on the Daylight Saving end day (which has 25 hours that day)

Another option is to use Closure:

var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));

How to create a XML object from String in Java?

If you can create a string xml you can easily transform it to the xml document object e.g. -

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try {  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
} catch (Exception e) {  
    e.printStackTrace();  
} 

You can use the document object and xml parsing libraries or xpath to get back the ip address.

Get next / previous element using JavaScript?

There is a attribute on every HTMLElement, "previousElementSibling".

Ex:

<div id="a">A</div>
<div id="b">B</div>
<div id="c">c</div>

<div id="result">Resultado: </div>

var b = document.getElementById("c").previousElementSibling;

document.getElementById("result").innerHTML += b.innerHTML;

Live: http://jsfiddle.net/QukKM/

How to use router.navigateByUrl and router.navigate in Angular

From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .


router.navigateByUrl() is used for absolute path navigation.

ie,

If we need to navigate to entirely different route in that case we can use router.navigateByUrl

For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()


Syntax :

router.navigateByUrl(' ---- String ----');

router.navigate([], {relativeTo: route})

Change icons of checked and unchecked for Checkbox for Android

One alternative would be to use a drawable/textview instead of a checkbox and manipulate it accordingly. I have used this method to have my own checked and unchecked images for a task application.

Python TypeError must be str not int

print("the furnace is now " + str(temperature) + "degrees!")

cast it to str

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Also register your created service in the Manifest and uses-permission as

<application ...>
   <service android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="com.example.MyBroadcastReciver"/>
        </intent-filter>
   </service>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

and then in braod cast Reciever call your service

public class MyBroadcastReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent myIntent = new Intent(context, MyService.class);
        context.startService(myIntent);
    }
}

How to stop the Timer in android?

We can schedule the timer to do the work.After the end of the time we set the message won't send.

This is the code.

Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
            //here you can write the code for send the message
        }
    }, 10, 60000);

In here the method we are calling is,

public void scheduleAtFixedRate (TimerTask task, long delay, long period)

In here,

task : the task to schedule

delay: amount of time in milliseconds before first execution.

period: amount of time in milliseconds between subsequent executions.

For more information you can refer: Android Developer

You can stop the timer by calling,

timer.cancel();

Calculate difference in keys contained in two Python dictionaries

Here is a solution for deep comparing 2 dictionaries keys:

def compareDictKeys(dict1, dict2):
  if type(dict1) != dict or type(dict2) != dict:
      return False

  keys1, keys2 = dict1.keys(), dict2.keys()
  diff = set(keys1) - set(keys2) or set(keys2) - set(keys1)

  if not diff:
      for key in keys1:
          if (type(dict1[key]) == dict or type(dict2[key]) == dict) and not compareDictKeys(dict1[key], dict2[key]):
              diff = True
              break

  return not diff

Generate a random number in a certain range in MATLAB

You can also use:

round(mod(rand.*max,max-1))+min

echo that outputs to stderr

Here is a function for checking the exit status of the last command, showing error and terminate the script.

or_exit() {
    local exit_status=$?
    local message=$*

    if [ "$exit_status" -gt 0 ]
    then
        echo "$(date '+%F %T') [$(basename "$0" .sh)] [ERROR] $message" >&2
        exit "$exit_status"
    fi
}

Usage:

gzip "$data_dir"
    or_exit "Cannot gzip $data_dir"

rm -rf "$junk"
    or_exit Cannot remove $junk folder

The function prints out the script name and the date in order to be useful when the script is called from crontab and logs the errors.

59 23 * * * /my/backup.sh 2>> /my/error.log

Better way to revert to a previous SVN revision of a file?

What you're looking for is called a "reverse merge". You should consult the docs regarding the merge function in the SVN book (as luapyad, or more precisely the first commenter on that post, points out). If you're using Tortoise, you can also just go into the log view and right-click and choose "revert changes from this revision" on the one where you made the mistake.

How to write Unicode characters to the console?

Console.OutputEncoding Property

https://docs.microsoft.com/en-us/dotnet/api/system.console.outputencoding

Note that successfully displaying Unicode characters to the console requires the following:

  • The console must use a TrueType font, such as Lucida Console or Consolas, to display characters.

comparing strings in vb

I think this String.Equals is what you need.

Dim aaa = "12/31"
            Dim a = String.Equals(aaa, "06/30")

a will return false.

adb devices command not working

I just got the same situation, Factory data reset worked well for me.

jQuery UI Slider (setting programmatically)

None of the above answers worked for me, perhaps they were based on an older version of the framework?

All I needed to do was set the value of the underlying control, then call the refresh method, as below:

$("#slider").val(50);
$("#slider").slider("refresh");

Play a Sound with Python

I like pygame, and the command below should work:

pygame.init()
pygame.mixer.Sound('sound.wav').play()

but it doesn't on either of my computers, and there is limited help on the subject out there. edit: I figured out why the pygame sound isn't working for me, it's not loading most sounds correctly, the 'length' attribute is ~0.0002 when I load them. maybe loading them using something other than mygame will get it morking more generally.

with pyglet I'm getting a resource not found error Using the above example, wigh both relative and full paths to the files.

using pyglet.media.load() instead of pyglet.resource.media() lets me load the files.

but sound.play() only plays the first fraction of a second of the file, unless I run pyglet.app.run() which blocks everything else...

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

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

In an attempt to optimize memory and performance dialogs in Android are asynchronous (they are also managed for this reason). Comming from the Windows world, you are used to modal dialogs. Android dialogs are modal but more like non-modal when it comes to execution. Execution does not stop after displaying a dialog.

The best description of Dialogs in Android I have seen is in "Pro Android" http://www.apress.com/book/view/1430215968

This is not a perfect explanation but it should help you to wrap your brain around the differences between Dialogs in Windows and Android. In Windows you want to do A, ask a question with a dialog, and then do B or C. In android design A with all the code you need for B and C in the onClick() of the OnClickListener(s) for the dialog. Then do A and launch the dialog. You’re done with A! When the user clicks a button B or C will get executed.

Windows
-------
A code
launch dialog
user picks B or C
B or C code
done!

Android
-------
OnClick for B code (does not get executed yet)
OnClick for C code (does not get executed yet)
A code
launch dialog
done!
user picks B or C

How do you format an unsigned long long int using printf?

You may want to try using the inttypes.h library that gives you types such as int32_t, int64_t, uint64_t etc. You can then use its macros such as:

uint64_t x;
uint32_t y;

printf("x: %"PRId64", y: %"PRId32"\n", x, y);

This is "guaranteed" to not give you the same trouble as long, unsigned long long etc, since you don't have to guess how many bits are in each data type.

How do I clone a subdirectory only of a Git repository?

It's not possible to clone subdirectory only with Git, but below are few workarounds.

Filter branch

You may want to rewrite the repository to look as if trunk/public_html/ had been its project root, and discard all other history (using filter-branch), try on already checkout branch:

git filter-branch --subdirectory-filter trunk/public_html -- --all

Notes: The -- that separates filter-branch options from revision options, and the --all to rewrite all branches and tags. All information including original commit times or merge information will be preserved. This command honors .git/info/grafts file and refs in the refs/replace/ namespace, so if you have any grafts or replacement refs defined, running this command will make them permanent.

Warning! The rewritten history will have different object names for all the objects and will not converge with the original branch. You will not be able to easily push and distribute the rewritten branch on top of the original branch. Please do not use this command if you do not know the full implications, and avoid using it anyway, if a simple single commit would suffice to fix your problem.


Sparse checkout

Here are simple steps with sparse checkout approach which will populate the working directory sparsely, so you can tell Git which folder(s) or file(s) in the working directory are worth checking out.

  1. Clone repository as usual (--no-checkout is optional):

    git clone --no-checkout git@foo/bar.git
    cd bar
    

    You may skip this step, if you've your repository already cloned.

    Hint: For large repos, consider shallow clone (--depth 1) to checkout only latest revision or/and --single-branch only.

  2. Enable sparseCheckout option:

    git config core.sparseCheckout true
    
  3. Specify folder(s) for sparse checkout (without space at the end):

    echo "trunk/public_html/*"> .git/info/sparse-checkout
    

    or edit .git/info/sparse-checkout.

  4. Checkout the branch (e.g. master):

    git checkout master
    

Now you should have selected folders in your current directory.

You may consider symbolic links if you've too many levels of directories or filtering branch instead.


Right query to get the current number of connections in a PostgreSQL DB

The following query is very helpful

select  * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;

cleanup php session files

Use below cron:

39 20     * * *     root   [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm

Winforms TableLayoutPanel adding rows programmatically

It's a weird design, but the TableLayoutPanel.RowCount property doesn't reflect the count of the RowStyles collection, and similarly for the ColumnCount property and the ColumnStyles collection.

What I've found I needed in my code was to manually update RowCount/ColumnCount after making changes to RowStyles/ColumnStyles.

Here's an example of code I've used:

    /// <summary>
    /// Add a new row to our grid.
    /// </summary>
    /// The row should autosize to match whatever is placed within.
    /// <returns>Index of new row.</returns>
    public int AddAutoSizeRow()
    {
        Panel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
        Panel.RowCount = Panel.RowStyles.Count;
        mCurrentRow = Panel.RowCount - 1;
        return mCurrentRow;
    }

Other thoughts

  • I've never used DockStyle.Fill to make a control fill a cell in the Grid; I've done this by setting the Anchors property of the control.

  • If you're adding a lot of controls, make sure you call SuspendLayout and ResumeLayout around the process, else things will run slow as the entire form is relaid after each control is added.