Programs & Examples On #Trackpopupmenu

Parse an HTML string with JS

const parse = Range.prototype.createContextualFragment.bind(document.createRange());

document.body.appendChild( parse('<p><strong>Today is:</strong></p>') ),
document.body.appendChild( parse(`<p style="background: #eee">${new Date()}</p>`) );


Only valid child Nodes within the parent Node (start of the Range) will be parsed. Otherwise, unexpected results may occur:

// <body> is "parent" Node, start of Range
const parseRange = document.createRange();
const parse = Range.prototype.createContextualFragment.bind(parseRange);

// Returns Text "1 2" because td, tr, tbody are not valid children of <body>
parse('<td>1</td> <td>2</td>');
parse('<tr><td>1</td> <td>2</td></tr>');
parse('<tbody><tr><td>1</td> <td>2</td></tr></tbody>');

// Returns <table>, which is a valid child of <body>
parse('<table> <td>1</td> <td>2</td> </table>');
parse('<table> <tr> <td>1</td> <td>2</td> </tr> </table>');
parse('<table> <tbody> <td>1</td> <td>2</td> </tbody> </table>');

// <tr> is parent Node, start of Range
parseRange.setStart(document.createElement('tr'), 0);

// Returns [<td>, <td>] element array
parse('<td>1</td> <td>2</td>');
parse('<tr> <td>1</td> <td>2</td> </tr>');
parse('<tbody> <td>1</td> <td>2</td> </tbody>');
parse('<table> <td>1</td> <td>2</td> </table>');

difference between iframe, embed and object elements

iframe have "sandbox" attribute that may block pop up etc

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

Split an integer into digits to compute an ISBN checksum

(number/10**x)%10

You can use this in a loop, where number is the full number, x is each iteration of the loop (0,1,2,3,...,n) with n being the stop point. x = 0 gives the ones place, x = 1 gives the tens, x = 2 gives the hundreds, and so on. Keep in mind that this will give the value of the digits from right to left, so this might not be the for an ISBN but it will still isolate each digit.

How to find out mySQL server ip address from phpmyadmin

select * from SHOW VARIABLES WHERE Variable_name = 'hostname';

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

Superscript in Python plots

If you want to write unit per meter (m^-1), use $m^{-1}$), which means -1 inbetween {}

Example: plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )

What is a JavaBean exactly?

A JavaBean is just a standard

  1. All properties are private (use getters/setters)
  2. A public no-argument constructor
  3. Implements Serializable.

That's it. It's just a convention. Lots of libraries depend on it though.

With respect to Serializable, from the API documentation:

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

In other words, serializable objects can be written to streams, and hence files, object databases, anything really.

Also, there is no syntactic difference between a JavaBean and another class -- a class is a JavaBean if it follows the standards.

There is a term for it, because the standard allows libraries to programmatically do things with class instances you define in a predefined way. For example, if a library wants to stream any object you pass into it, it knows it can because your object is serializable (assuming the library requires your objects be proper JavaBeans).

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

I want to delete all bin and obj folders to force all projects to rebuild everything

To delete bin and obj before build add to project file:

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

Here is article: How to remove bin and/or obj folder before the build or deploy

How can I count the number of elements of a given value in a matrix?

this would be perfect cause we are doing operation on matrix, and the answer should be a single number

sum(sum(matrix==value))

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

How to get N rows starting from row M from sorted table in T-SQL

SELECT * FROM (
  SELECT
    Row_Number() Over (Order by (Select 1)) as RawKey,
    * 
  FROM [Alzh].[dbo].[DM_THD_TRANS_FY14]
) AS foo
WHERE RawKey between 17210400 and 17210500

Reducing video size with same format and reducing frame size

Instead of chosing fixed bit rates, with the H.264 codec, you can also chose a different preset as described at https://trac.ffmpeg.org/wiki/x264EncodingGuide. I also found Video encoder comparison at KeyJ's blog (archived version) an interesting read, it compares H.264 against Theora and others.

Following is a comparison of various options I tried. The recorded video was originally 673M in size, taken on an iPad using RecordMyScreen. It has a duration of about 20 minutes with a resolution of 1024x768 (with half of the video being blank, so I cropped it to 768x768). In order to reduce size, I lowered the resolution to 480x480. There is no audio.

The results, taking the same 1024x768 as base (and applying cropping, scaling and a filter):

  • With no special options: 95M (encoding time: 1m19s).
  • With only -b 512k added, the size dropped to 77M (encoding time: 1m17s).
  • With only -preset veryslow (and no -b), it became 70M (encoding time: 6m14s)
  • With both -b 512k and -preset veryslow, the size becomes 77M (100K smaller than just -b 512k).
  • With -preset veryslow -crf 28, I get a file of 39M which took 5m47s (with no visual quality difference to me).

N=1, so take the results with a grain of salt and perform your own tests.

Why are there two ways to unstage a file in Git?

Just use:

git reset HEAD <filename>

This unstages the file and keeps the changes you did to it, so you can, in turn, change branches if you wanted and git add those files to another branch instead. All changes are kept.

How can I debug my JavaScript code?

I use old good printf approach (an ancient technique which will work well in any time).

Look to magic %o:

console.log("this is %o, event is %o, host is %s", this, e, location.host);

%o dump clickable and deep-browsable, pretty-printed content of JS object. %s was shown just for a record.

And this:

console.log("%s", new Error().stack);

gives you Java-like stack trace to point of new Error() invocation (including path to file and line number!!).

Both %o and new Error().stack available in Chrome and Firefox.

With such powerful tools you make assumption whats going wrong in your JS, put debug output (don't forget wrap in if statement to reduce amount of data) and verify your assumption. Fix issue or make new assumption or put more debug output to bit problem.

Also for stack traces use:

console.trace();

as say Console

Happy hacking!

Java error: Only a type can be imported. XYZ resolves to a package

Without further details, it sounds like an error in the import declaration of a class. Check, if all import declarations either import all classes from a package or a single class:

import all.classes.from.package.*;
import only.one.type.named.MyClass;

Edit

OK, after the edit, looks like it's a jsp problem.

Edit 2

Here is another forum entry, the problem seems to have similarities and the victim solved it by reinstalling eclipse. I'd try that one first - installing a second instance of eclipse with only the most necessary plugins, a new workspace, the project imported into that clean workspace, and hope for the best...

How to reload current page in ReactJS?

use this might help

window.location.reload();

Why SpringMVC Request method 'GET' not supported?

Apparently some POST requests looks like a "GET" to the server (like Heroku...)

So I use this strategy and it works for me:

@RequestMapping(value = "/salvar", method = { RequestMethod.GET, RequestMethod.POST })

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

Scanner method to get a char

Console cons = System.console();

The above code line creates cons as a null reference. The code and output are given below:

Console cons = System.console();
if (cons != null) {
    System.out.println("Enter single character: ");
    char c = (char) cons.reader().read();
    System.out.println(c);
}else{
    System.out.println(cons);
}

Output :

null

The code was tested on macbook pro with java version "1.6.0_37"

How do I pass multiple ints into a vector at once?

You can also use Boost.Assignment:

const list<int> primes = list_of(2)(3)(5)(7)(11);

vector<int> v; 
v += 1,2,3,4,5,6,7,8,9;

if, elif, else statement issues in Bash

Missing space between elif and [ rest your program is correct. you need to correct it an check it out. here is fixed program:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

useful link related to this bash if else statement

Query to list number of records in each table in a database

A snippet I found at http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=21021 that helped me:

select t.name TableName, i.rows Records
from sysobjects t, sysindexes i
where t.xtype = 'U' and i.id = t.id and i.indid in (0,1)
order by TableName;

Restart node upon changing a file

forever module has a concept of multiple node.js servers, and can start, restart, stop and list currently running servers. It can also watch for changing files and restart node as needed.

Install it if you don't have it already:

npm install forever -g

After installing it, call the forever command: use the -w flag to watch file for changes:

forever -w ./my-script.js

In addition, you can watch directory and ignore patterns:

forever --watch --watchDirectory ./path/to/dir --watchIgnore *.log ./start/file

What is the difference between :focus and :active?

Focus can only be given by keyboard input, but an Element can be activated by both, a mouse or a keyboard.

If one would use :focus on a link, the style rule would only apply with pressing a botton on the keyboard.

Types in MySQL: BigInt(20) vs Int(20)

Quote:

The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.

How to use the DropDownList's SelectedIndexChanged event

The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..

    <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
        AutoPostBack="True" AppendDataBoundItems="true">
    <asp:DropDownList ID="DropDownList2" runat="server"
        onselectedindexchanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList> 


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList2

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList3
}

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

By default Vagrant uses a generated private key to login, you can try this:

ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1

List only stopped Docker containers

The typical command is:

docker container ls -f 'status=exited'

However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:

  • created
  • restarting
  • running
  • removing
  • paused
  • exited
  • dead

You can filter on multiple statuses by passing multiple filters on the status:

docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'

If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q, and you can also limit to just the containers that exited successfully with an exit code filter:

docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')

For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

It's quite easy for a fix.

For me, we had more than one inputs in the form. We need to isolate the input / line causing error and simply add the name attribute. That fixed the issue for me:

Before:

<form class="example-form">

    <mat-form-field appearance="outline">

      <mat-select placeholder="Select your option" [(ngModel)]="sample.stat"> <!--HERE -->

          <mat-option *ngFor="let option of actions" [value]="option">{{option}</mat-option>
      </mat-select>
    </mat-form-field>

    <mat-form-field appearance="outline">
      <mat-label>Enter number</mat-label>

      <input id="myInput" type="text" placeholder="Enter number" aria-label="Number"
        matInput [formControl]="myFormControl" required [(ngModel)]="number">  <!--HERE -->

    </mat-form-field>

    <mat-checkbox [(ngModel)]="isRight">Check!</mat-checkbox> <!--HERE -->

  </form>

After: i just added the name attribute for select and checkbox and that fixed the issue. As follows:

<mat-select placeholder="Select your option" name="mySelect" 
  [(ngModel)]="sample.stat"> <!--HERE: Observe the "name" attribute -->

<input id="myInput" type="text" placeholder="Enter number" aria-label="Number"
        matInput [formControl]="myFormControl" required [(ngModel)]="number">  <!--HERE -->

<mat-checkbox name="myCheck" [(ngModel)]="isRight">Check!</mat-checkbox> <!--HERE: Observe the "name" attribute -->

As you see added the name attribute. It is not necessary to be given same as your ngModel name. Just providing the name attribute will fix the issue.

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

Hive insert query like SQL

Yes you can insert but not as similar to SQL.

In SQL we can insert the row level data, but here you can insert by fields (columns).

During this you have to make sure target table and the query should have same datatype and same number of columns.

eg:

CREATE TABLE test(stu_name STRING,stu_id INT,stu_marks INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE;

INSERT OVERWRITE TABLE test SELECT lang_name, lang_id, lang_legacy_id FROM export_table;

Installing Apache Maven Plugin for Eclipse

Installed Maven in Juno IDE for Java EE (eclipse-jee-juno-SR2-linux-gtk-x86_64)

Eclipse -> Available Software Sites -> Maven URL -> http://download.eclipse.org/technology/m2e/releases

Following Maven URL did not work and was giving "No software found" error: http://eclipse.org/m2e/download/

'tuple' object does not support item assignment

You have misspelt the second pixels as pixel. The following works:

pixels = [1,2,3]
pixels[0] = 5

It appears that due to the typo you were trying to accidentally modify some tuple called pixel, and in Python tuples are immutable. Hence the confusing error message.

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

How to detect when a UIScrollView has finished scrolling

I've tried Ashley Smart's answer and it worked like a charm. Here's another idea, with using only scrollViewDidScroll

-(void)scrollViewDidScroll:(UIScrollView *)sender 
{   
    if(self.scrollView_Result.contentOffset.x == self.scrollView_Result.frame.size.width)       {
    // You have reached page 1
    }
}

I just had two pages so it worked for me. However, if you have more than one page, it could be problematic (you could check whether the current offset is a multiple of the width but then you wouldn't know if the user stopped at 2nd page or is on his way to 3rd or more)

Recommended add-ons/plugins for Microsoft Visual Studio

It's not a Visual Studio add in, but it is a tool that I couldn't use Visual Studio without it...

ClipX - it's works with the normal clipboard, but saves the entries to a searchable list, you can use copy and paste as ususal, but you can hit CTRL+SHIFT+V and the list pops up. It works with images, text, etc. It even persists after you reboot your computer.

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

public Configuration()
{
    AutomaticMigrationsEnabled = false;

    // register mysql code generator

    SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}

I find out that connector 6.6.4 will not work with Entity Framework 5 but with Entity Framework 4.3. So to downgrade issue the following commands in the package manager console:

Uninstall-Package EntityFramework

Install-Package EntityFramework -Version 4.3.1

Finally I do Update-Database -Verbose again and voila! The schema and tables are created. Wait for the next version of connector to use it with Entity Framework 5.

How can I backup a Docker-container with its data-volumes?

if I want to revert the container I can try to commit an image, and then later delete the container, and create a new container from the committed image. But if I do that the volume gets deleted and all my data is gone

As the docker user guide explains, data volumes are meant to persist data outside of a container filesystem. This also ease the sharing of data between multiple containers.

While Docker will never delete data in volumes (unless you delete the associated container with docker rm -v), volumes that are not referenced by any docker container are called dangling volumes. Those dangling volumes are difficult to get rid of and difficult to access.

This means that as soon as the last container using a volume is deleted, the data volume becomes dangling and its content difficult to acess.

In order to prevent those dangling volumes, the trick is to create an additional docker container using the data volume you want to remain ; so that there will always be at least that docker container referencing the volume. This way you can delete the docker container running the wordpress app without losing the ease of access to that data volume content.

Such containers are called data volume containers.

There must be some simple way to back up my container plus volume data but I can't find it anywhere.

backup docker images

To backup docker images, use the docker save command that will produce a tar archive that can be used later on to create a new docker image with the docker load command.

backup docker containers

You can backup a docker container by different means

  • by committing a new docker image based on the docker container current state using the docker commit command
  • by exporting the docker container file system as a tar archive using the docker export command. You can later on create a new docker image from that tar archive with the docker import command.

Be aware that those commands will only backup the docker container layered file system. This excludes the data volumes.

backup docker data volumes

To backup a data volume you can run a new container using the volume you want to backup and executing the tar command to produce an archive of the volume content as described in the docker user guide.

In your particular case, the data volume is used to store the data for a MySQL server. So if you want to export a tar archive for this volume, you will need to stop the MySQL server first. To do so you will have to stop the wordpress container.

backup the MySQL data

An other way is to remotely connect to the MySQL server to produce a database dump with the mysqldump command. However in order for this to work, your MySQL server must be configured to accept remote connections and also have a user who is allowed to connect remotely. This might not be the case with the wordpress docker image you are using.


Edit

Docker recently introduced Docker volume plugins which allow to delegate the handling of volumes to plugins implemented by vendors.

The docker run command has a new behavior for the -v option. It is now possible to pass it a volume name. Volumes created in that way are named and easy to reference later on, easing the issues with dangling volumes.

Edit 2

Docker introduced the docker volume prune command to delete all dangling volumes easily.

CSS grid wrapping

You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Enter image description here

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Enter image description here

How to listen to route changes in react router v4?

You should to use history v4 lib.

Example from there

history.listen((location, action) => {
  console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

How can I make a multipart/form-data POST request using Java?

Here's a solution that does not require any libraries.

This routine transmits every file in the directory d:/data/mpf10 to urlToConnect


String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
    writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
    File dir = new File("d:/data/mpf10");
    for (File file : dir.listFiles()) {
        if (file.isDirectory()) {
            continue;
        }
        writer.println("--" + boundary);
        writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
        writer.println("Content-Type: text/plain; charset=UTF-8");
        writer.println();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            for (String line; (line = reader.readLine()) != null;) {
                writer.println(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
    writer.println("--" + boundary + "--");
} finally {
    if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
// Handle response

javac option to compile all java files under a given directory recursively

javac -cp "jar_path/*" $(find . -name '*.java')

(I prefer not to use xargs because it can split them up and run javac multiple times, each with a subset of java files, some of which may import other ones not specified on the same javac command line)

If you have an App.java entrypoint, freaker's way with -sourcepath is best. It compiles every other java file it needs, following the import-dependencies. eg:

javac -cp "jar_path/*" -sourcepath src/ src/com/companyname/modulename/App.java

You can also specify a target class-file dir: -d target/.

How to provide a mysql database connection in single file in nodejs

I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.

As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).

Connection Pool Docs

How do I create a slug in Django?

You can look at the docs for the SlugField to get to know more about it in more descriptive way.

How to automatically generate unique id in SQL like UID12345678?

CREATE TABLE dbo.tblUsers
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
    [Name] VARCHAR(50) NOT NULL,
)

marc_s's Answer Snap

marc_s's Answer Snap

Error 0x80005000 and DirectoryServices

The same error occurs if in DirectoryEntry.Patch is nothing after the symbols "LDAP//:". It is necessary to check the directoryEntry.Path before directorySearcher.FindOne(). Unless explicitly specified domain, and do not need to "LDAP://".

private void GetUser(string userName, string domainName)
{
     DirectoryEntry dirEntry = new DirectoryEntry();

     if (domainName.Length > 0)
     {
          dirEntry.Path = "LDAP://" + domainName;
     }

     DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
     dirSearcher.SearchScope = SearchScope.Subtree;
     dirSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(sn={0}*)(givenName={0})(sAMAccountName={0}*)))", userName);
     var searchResults = dirSearcher.FindAll();
     //var searchResults = dirSearcher.FindOne();

     if (searchResults.Count == 0)
     {
          MessageBox.Show("User not found");
     }
     else
     {
          foreach (SearchResult sr in searchResults)
          {
              var de = sr.GetDirectoryEntry();
              string user = de.Properties["SAMAccountName"][0].ToString();
              MessageBox.Show(user); 
          }        
     }
}

Python - round up to the nearest ten

You can use math.ceil() to round up, and then multiply by 10

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

To use just do

>>roundup(45)
50

Number of occurrences of a character in a string

The most straight forward, and most efficient, would be to simply loop through the characters in the string:

int cnt = 0;
foreach (char c in test) {
  if (c == '&') cnt++;
}

You can use Linq extensions to make a simpler, and almost as efficient version. There is a bit more overhead, but it's still surprisingly close to the loop in performance:

int cnt = test.Count(c => c == '&');

Then there is the old Replace trick, however that is better suited for languages where looping is awkward (SQL) or slow (VBScript):

int cnt = test.Length - test.Replace("&", "").Length;

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

First check if there is any connectivity problem and you can reach the SMTP server:

In terminal type:

telnet servername portnumber 

If you receive the 220 response you can reach the SMTP server and there is no connectivity problem but if the connection to the server failed see what's wrong in your network.

If the server needs auth try to authenticate on the server by username and password and see if something goes wrong.

At last see if the server requires encryption and if yes openssl and other stuff are configured correctly.

How do I read a specified line in a text file?

Read five lines each time, just put your statement in if statement , thats it

        String str1 = @"C:\Users\TEMP\Desktop\StaN.txt";   

        System.IO.StreamReader file = new System.IO.StreamReader(str1);

        line = file.ReadLine();

        Int32 ctn=0;

        try
        {

            while ((line = file.ReadLine()) != null)
            {

                    if (Counter == ctn)
                    {
                        MessageBox.Show("I am here");
                        ctn=ctn+5;
                        continue;
                    }
                    else
                    {
                        Counter++;
                        //MessageBox.Show(Counter.ToString());
                        MessageBox.Show(line.ToString());
                    } 
                }

            file.Close();
        }
        catch (Exception er)
        {

        }

Set up an HTTP proxy to insert a header

If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found here.

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old.
  • The speed tests quoted below are comparing an older version of Json.Nt (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


Update since .Net Core 3.0

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .


I would recommend Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file


Why? Here's a feature comparison between common serialisers as well as benchmark tests .

Below is a graph of performance taken from the linked article:

enter image description here

This separate post, states that:

Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer


Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned

These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.

How to diff one file to an arbitrary version in Git?

If you are looking for the diff on a specific commit and you want to use the github UI instead of the command line (say you want to link it to other folks), you can do:

https://github.com/<org>/<repo>/commit/<commit-sha>/<path-to-file>

For example:

https://github.com/grails/grails-core/commit/02942c5b4d832b856fbc04c186f1d02416895a7e/grails-test-suite-uber/build.gradle

Note the Previous and Next links at the top right that allow you to navigate through all the files in the commit.

This only works for a specific commit though, not for comparing between any two arbitrary versions.

how to enable sqlite3 for php?

The Debian/Ubuntu way for php-7.2, php-7.3 & php-7.4 (e.g. the [234] part)

sudo apt install php7.[234]-sqlite
sudo phpenmod sqlite3

Be sure to note that on Windows Subsystem for Linux version 1 (WSL1) the (file-)locking system for SQlite is broken.

Xamarin.Forms ListView: Set the highlight color of a tapped item

The easiest way to accomplish this on android is by adding the following code to your custom style :

@android:color/transparent

How to frame two for loops in list comprehension python

In comprehension, the nested lists iteration should follow the same order than the equivalent imbricated for loops.

To understand, we will take a simple example from NLP. You want to create a list of all words from a list of sentences where each sentence is a list of words.

>>> list_of_sentences = [['The','cat','chases', 'the', 'mouse','.'],['The','dog','barks','.']]
>>> all_words = [word for sentence in list_of_sentences for word in sentence]
>>> all_words
['The', 'cat', 'chases', 'the', 'mouse', '.', 'The', 'dog', 'barks', '.']

To remove the repeated words, you can use a set {} instead of a list []

>>> all_unique_words = list({word for sentence in list_of_sentences for word in sentence}]
>>> all_unique_words
['.', 'dog', 'the', 'chase', 'barks', 'mouse', 'The', 'cat']

or apply list(set(all_words))

>>> all_unique_words = list(set(all_words))
['.', 'dog', 'the', 'chases', 'barks', 'mouse', 'The', 'cat']

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How do I do a simple 'Find and Replace" in MsSQL?

If you are working with SQL Server 2005 or later there is also a CLR library available at http://www.sqlsharp.com/ that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.

Hiding user input on terminal in Linux script

Here is a variation of @SiegeX's answer which works with traditional Bourne shell (which has no support for += assignments).

password=''
while IFS= read -r -s -n1 pass; do
  if [ -z "$pass" ]; then
     echo
     break
  else
     printf '*'
     password="$password$pass"
  fi
done

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

As Ryan says, the tsc compiler has a switch --declaration which generates a .d.ts file from a .ts file. Also note that (barring bugs) TypeScript is supposed to be able to compile Javascript, so you can pass existing javascript code to the tsc compiler.

Android - Activity vs FragmentActivity?

ianhanniballake is right. You can get all the functionality of Activity from FragmentActivity. In fact, FragmentActivity has more functionality.

Using FragmentActivity you can easily build tab and swap format. For each tab you can use different Fragment (Fragments are reusable). So for any FragmentActivity you can reuse the same Fragment.

Still you can use Activity for single pages like list down something and edit element of the list in next page.

Also remember to use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach a android.support.v4.app.Fragment to an android.app.Activity, as this will cause an exception to be thrown.

Export to CSV using MVC, C# and jQuery

Simple excel file create in mvc 4

public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }

Merging multiple PDFs using iTextSharp in c#.net

I found the answer:

Instead of the 2nd Method, add more files to the first array of input files.

public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
    // step 1: creation of a document-object
    Document document = new Document();
    //create newFileStream object which will be disposed at the end
    using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
    {
       // step 2: we create a writer that listens to the document
       PdfCopy writer = new PdfCopy(document, newFileStream );
       if (writer == null)
       {
           return;
       }

       // step 3: we open the document
       document.Open();

       foreach (string fileName in fileNames)
       {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(fileName);
           reader.ConsolidateNamedDestinations();

           // step 4: we add content
           for (int i = 1; i <= reader.NumberOfPages; i++)
           {                
               PdfImportedPage page = writer.GetImportedPage(reader, i);
               writer.AddPage(page);
           }

           PRAcroForm form = reader.AcroForm;
           if (form != null)
           {
               writer.CopyAcroForm(reader);
           }

           reader.Close();
       }

       // step 5: we close the document and writer
       writer.Close();
       document.Close();
   }//disposes the newFileStream object
}

adb shell su works but adb root does not

I use for enter su mode in abd shell

adb shell "su"

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

Segments of p

Assume p contains all possible finite number combinations. See math.stackexchange question

  1. Determine the number of digits needed from the size of the array.
  2. Use segments of p places as indexes to determine how to re-order the array. If a segment exceeds the size boundaries for this array, adjust the p decimal offset and start over.
  3. Check if the re-ordered array is sorted. If it is woot, else adjust the offset and start over.

C# - Simplest way to remove first occurrence of a substring from another string

int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
    ? sourceString
    : sourceString.Remove(index, removeString.Length);

Random strings in Python

random_name = lambda length: ''.join(random.sample(string.letters, length))

length must be <= len(string.letters) = 53. result example

   >>> [random_name(x) for x in range(1,20)]
['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', 'EBrPcYKUvZ', 'GmxPKCnbfih', 'nSiNmCRktdWZ', 'VWKSsGwlBeXUr', 'i
stIFGTUlZqnav', 'bqfwgBhyTJMUEzF', 'VLXlPiQnhptZyoHq', 'BXWATvwLCUcVesFfk', 'jLngHmTBtoOSsQlezV', 'JOUhklIwDBMFzrTCPub']
>>> 

Enjoy. ;)

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

Per this github comment, one can disable urllib3 request warnings via requests in a 1-liner:

requests.packages.urllib3.disable_warnings()

This will suppress all warnings though, not just InsecureRequest (ie it will also suppress InsecurePlatform etc). In cases where we just want stuff to work, I find the conciseness handy.

How to return PDF to browser in MVC?

HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");

if the filename is generating dynamically then how to define filename here, it is generating through guid here.

Deleting Objects in JavaScript

Just found a jsperf you may consider interesting in light of this matter. (it could be handy to keep it around to complete the picture)

It compares delete, setting null and setting undefined.

But keep in mind that it tests the case when you delete/set property many times.

How can an html element fill out 100% of the remaining screen height, using css only?

Please let me add my 5 cents here and offer a classical solution:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idHeader {position:absolute; left:0; right:0; border:solid 3px red;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idHeader" style="height:30px; top:0;">Header section</div>_x000D_
  <div id="idContent" style="top:36px; bottom:0;">Content section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will work in all browsers, no script, no flex. Open snippet in full page mode and resize browser: desired proportions are preserved even in fullscreen mode.

Note:

  • Elements with different background color can actually cover each other. Here I used solid border to ensure that elements are placed correctly.
  • idHeader.height and idContent.top are adjusted to include border, and should have the same value if border is not used. Otherwise elements will pull out of the viewport, since calculated width does not include border, margin and/or padding.
  • left:0; right:0; can be replaced by width:100% for the same reason, if no border used.
  • Testing in separate page (not as a snippet) does not require any html/body adjustment.
  • In IE6 and earlier versions we must add padding-top and/or padding-bottom attributes to #idOuter element.

To complete my answer, here is the footer layout:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}_x000D_
#idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idContent" style="bottom:36px; top:0;">Content section</div>_x000D_
  <div id="idFooter" style="height:30px; bottom:0;">Footer section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And here is the layout with both header and footer:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idHeader {position:absolute; left:0; right:0; border:solid 3px red;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}_x000D_
#idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idHeader" style="height:30px; top:0;">Header section</div>_x000D_
  <div id="idContent" style="top:36px; bottom:36px;">Content section</div>_x000D_
  <div id="idFooter" style="height:30px; bottom:0;">Footer section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I ignore ampersands in a SQL script running from SQL Plus?

set define off <- This is the best solution I found

I also tried...

set define }

I was able to insert several records containing ampersand characters '&' but I cannot use the '}' character into the text So I decided to use "set define off" and everything works as it should.

Serializing an object as UTF-8 XML in .NET

Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).

To get the actual UTF-8 octets you could use:

var serializer = new XmlSerializer(typeof(SomeSerializableObject));

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);

serializer.Serialize(streamWriter, entry);

byte[] utf8EncodedXml = memoryStream.ToArray();

I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):

var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var  xw = XmlWriter.Create(memStm))
{
  serializer.Serialize(xw, entry);
  var utf8 = memStm.ToArray();
}

Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

I had a similar issue which i solved by making two changes

  1. added below entry in application.yaml file

    spring: jackson: serialization.write_dates_as_timestamps: false

  2. add below two annotations in pojo

    1. @JsonDeserialize(using = LocalDateDeserializer.class)
    2. @JsonSerialize(using = LocalDateSerializer.class)

    sample example

    import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public class Customer { //your fields ... @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) protected LocalDate birthdate; }

then the following json requests worked for me

  1. sample request format as string

{ "birthdate": "2019-11-28" }

  1. sample request format as array

{ "birthdate":[2019,11,18] }

Hope it helps!!

MySQL LEFT JOIN 3 tables

Try this definitely work.

SELECT p.PersonID AS person_id,
   p.Name, p.SS, 
   f.FearID AS fear_id,
   f.Fear 
   FROM person_fear AS pf 
      LEFT JOIN persons AS p ON pf.PersonID = p.PersonID 
      LEFT JOIN fears AS f ON pf.PersonID = f.FearID 
   WHERE f.FearID = pf.FearID AND p.PersonID = pf.PersonID

Is there a constraint that restricts my generic method to numeric types?

Considering the popularity of this question and the interest behind such a function I am surprised to see that there is no answer involving T4 yet.

In this sample code I will demonstrate a very simple example of how you can use the powerful templating engine to do what the compiler pretty much does behind the scenes with generics.

Instead of going through hoops and sacrificing compile-time certainty you can simply generate the function you want for every type you like and use that accordingly (at compile time!).

In order to do this:

  • Create a new Text Template file called GenericNumberMethodTemplate.tt.
  • Remove the auto-generated code (you'll keep most of it, but some isn't needed).
  • Add the following snippet:
<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>

<# Type[] types = new[] {
    typeof(Int16), typeof(Int32), typeof(Int64),
    typeof(UInt16), typeof(UInt32), typeof(UInt64)
    };
#>

using System;
public static class MaxMath {
    <# foreach (var type in types) { 
    #>
        public static <#= type.Name #> Max (<#= type.Name #> val1, <#= type.Name #> val2) {
            return val1 > val2 ? val1 : val2;
        }
    <#
    } #>
}

That's it. You're done now.

Saving this file will automatically compile it to this source file:

using System;
public static class MaxMath {
    public static Int16 Max (Int16 val1, Int16 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static Int32 Max (Int32 val1, Int32 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static Int64 Max (Int64 val1, Int64 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt16 Max (UInt16 val1, UInt16 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt32 Max (UInt32 val1, UInt32 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt64 Max (UInt64 val1, UInt64 val2) {
        return val1 > val2 ? val1 : val2;
    }
}

In your main method you can verify that you have compile-time certainty:

namespace TTTTTest
{
    class Program
    {
        static void Main(string[] args)
        {
            long val1 = 5L;
            long val2 = 10L;
            Console.WriteLine(MaxMath.Max(val1, val2));
            Console.Read();
        }
    }
}

enter image description here

I'll get ahead of one remark: no, this is not a violation of the DRY principle. The DRY principle is there to prevent people from duplicating code in multiple places that would cause the application to become hard to maintain.

This is not at all the case here: if you want a change then you can just change the template (a single source for all your generation!) and it's done.

In order to use it with your own custom definitions, add a namespace declaration (make sure it's the same one as the one where you'll define your own implementation) to your generated code and mark the class as partial. Afterwards, add these lines to your template file so it will be included in the eventual compilation:

<#@ import namespace="TheNameSpaceYouWillUse" #>
<#@ assembly name="$(TargetPath)" #>

Let's be honest: This is pretty cool.

Disclaimer: this sample has been heavily influenced by Metaprogramming in .NET by Kevin Hazzard and Jason Bock, Manning Publications.

How can I post an array of string to ASP.NET MVC Controller without a form?

I modified my response to include the code for a test app I did.

Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).

First the javascript:

function test()
{
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };

    $.ajax({
        type: "POST",
        url: "/Home/SaveList",
        data: postData,
        success: function(data){
            alert(data.Result);
        },
        dataType: "json",
        traditional: true
    });
}

And here's the code in my controller class:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!

How to check if a number is a power of 2

for any power of 2, the following also holds.

n&(-n)==n

NOTE: fails for n=0 , so need to check for it
Reason why this works is:
-n is the 2s complement of n. -n will have every bit to the left of rightmost set bit of n flipped compared to n. For powers of 2 there is only one set bit.

Constants in Kotlin -- what's a recommended way to create them?

class Myclass {

 companion object {
        const val MYCONSTANT = 479
}

you have two choices you can use const keyword or use the @JvmField which makes it a java's static final constant.

class Myclass {

     companion object {
           @JvmField val MYCONSTANT = 479
    }

If you use the @JvmField annotation then after it compiles the constant gets put in for you the way you would call it in java.
Just like you would call it in java the compiler will replace that for you when you call the companion constant in code.

However, if you use the const keyword then the value of the constant gets inlined. By inline i mean the actual value is used after it compiles.

so to summarize here is what the compiler will do for you :

//so for @JvmField:

Foo var1 = Constants.FOO;

//and for const:

Foo var1 = 479

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

How do I allow HTTPS for Apache on localhost?

I've just attempted this - I needed to test some development code on my localhost Apache on Windows. This was WAAAY more difficult than it should be. But here are the steps that managed to work after much hairpulling...

I found that my Apache install comes with openssl.exe which is helpful. If you don't have a copy, you'll need to download it. My copy was in Apache2\bin folder which is how I reference it below.

Steps:

  1. Ensure you have write permissions to your Apache conf folder
  2. Open a command prompt in Apache2\conf folder
  3. Type
    ..\bin\openssl req -config openssl.cnf -new -out blarg.csr -keyout blarg.pem
  4. You can leave all questions blank except:

    • PEM Passphrase: a temporary password such as "password"
    • Common Name: the hostname of your server

  5. When that completes, type
    ..\bin\openssl rsa -in blarg.pem -out blarg.key

  6. Generate your self-signed certificate by typing:
    ..\bin\openssl x509 -in blarg.csr -out blarg.cert -req -signkey blarg.key -days 365

  7. Open Apache's conf\httpd.conf file and ensure SSL module is enabled - there should be no hash at the start of this line:
    LoadModule ssl_module modules/mod_ssl.so

  8. Some Apache installations place the SSL config in a separate file. If so, ensure that the SSL conf file is being included. In my case I had to uncomment this line:
    Include conf/extra/httpd-ssl.conf

  9. In the SSL config httpd-ssl.conf I had to update the following lines:

    • Update
      SSLSessionCache "shmcb:C:\Program Files (x86)\Zend\Apache2/logs/ssl_scache(512000)"
      to
      SSLSessionCache "shmcb:C:/Progra\~2/Zend/Apache2/logs/ssl_scache(512000)"
      (The brackets in the path confuse the module, so we need to escape them)
    • DocumentRoot - set this to the folder for your web files
    • ServerName - the server's hostname
    • SSLCertificateFile "conf/blarg.cert"
    • SSLCertificateKeyFile "conf/blarg.key"

  10. Restart Apache.

  11. Try loading https://localhost/ in your browser.

Hopefully you made it this far. Feel free to update this post with any other helpful info.

(Screenshots courtesy of Neil Obremski and his helpful article - although now quite out-of-date.)

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

How do I add an existing directory tree to a project in Visual Studio?

I found no answer to my satisfaction, so I figured out myself.

Here is the answer to you if you want to add external source codes to your project and don't want to copy over the entire codes. I have many dependencies on other gits and they are updated hourly if not minutely. I can't do copy every hour to sync up. Here is what you need to do.

Assume this is structure:

/root/projA/src

/root/projA/includes

/root/projB/src

/root/projB/includes

/root/yourProj/src

/root/yourProj/includes

  1. Start your VS solution.
  2. Right-click the project name right below the Solution.
  3. Then click the "Add", "New Filter", put the name "projA" for projA.
  4. Right-click on the "projA", click "Add", "New Filter", enter name "src"
  5. Right-click on the "projA", click "Add", "New Filter", enter name "includes"
  6. Right-click "projA"/"src", click "Add", "Existing Item", then browse to the /root/projA/src to add all source codes or one by one for the ones you want.
  7. Do same for "projA"/"includes"
  8. Do same for projB. Now the external/existing projects outside yours are present in your solution/project. The VS will compile them together. Here is an trick. Since the projA and projB are virtual folders under your project, the compiler may not find the projA/includes.

  9. If it doesn't find the projA/includes, then right click the project, select the "Properties".

  10. Navigate to "C/C++". Edit "Additional Include Directories", add your projA/include as such "../projA/includes", relative path.

One caveat, if there are duplicated include/header files, the "exclude from project" on the "Header file" doesn't really work. It's a bug in VS.

Best C++ IDE or Editor for Windows

I personally like Visual Studio combined with a third party add-in such as Visual Assist (http://www.wholetomato.com/). I've tried a few of the others and always ended up back with Visual Studio. Plus, Visual Studio is a widely used product in development industries, so having experience using it can only be a plus.

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

How do you clear a stringstream variable?

my 2 cents:

this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.

//clear the stringstream variable

sstm.str("");
sstm.clear();

//fill up the streamstream variable
sstm << "crap" << "morecrap";

Sending mail from Python using SMTP

Or

import smtplib
 
from email.message import EmailMessage
from getpass import getpass


password = getpass()

message = EmailMessage()
message.set_content('Message content here')
message['Subject'] = 'Your subject here'
message['From'] = "USERNAME@DOMAIN"
message['To'] = "[email protected]"

try:
    smtp_server = None
    smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587)
    smtp_server.ehlo()
    smtp_server.starttls()
    smtp_server.ehlo()
    smtp_server.login("USERNAME@DOMAIN", password)
    smtp_server.send_message(message)
except Exception as e:
    print("Error: ", str(e))
finally:
    if smtp_server is not None:
        smtp_server.quit()

If you want to use Port 465 you have to create an SMTP_SSL object.

ApiNotActivatedMapError for simple html page using google-places-api

as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)

you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key

also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.

JSON to pandas DataFrame

Here is small utility class that converts JSON to DataFrame and back: Hope you find this helpful.

# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize

class DFConverter:

    #Converts the input JSON to a DataFrame
    def convertToDF(self,dfJSON):
        return(json_normalize(dfJSON))

    #Converts the input DataFrame to JSON 
    def convertToJSON(self, df):
        resultJSON = df.to_json(orient='records')
        return(resultJSON)

How do I use itertools.groupby()?

Another example:

for key, igroup in itertools.groupby(xrange(12), lambda x: x // 5):
    print key, list(igroup)

results in

0 [0, 1, 2, 3, 4]
1 [5, 6, 7, 8, 9]
2 [10, 11]

Note that igroup is an iterator (a sub-iterator as the documentation calls it).

This is useful for chunking a generator:

def chunker(items, chunk_size):
    '''Group items in chunks of chunk_size'''
    for _key, group in itertools.groupby(enumerate(items), lambda x: x[0] // chunk_size):
        yield (g[1] for g in group)

with open('file.txt') as fobj:
    for chunk in chunker(fobj):
        process(chunk)

Another example of groupby - when the keys are not sorted. In the following example, items in xx are grouped by values in yy. In this case, one set of zeros is output first, followed by a set of ones, followed again by a set of zeros.

xx = range(10)
yy = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]
for group in itertools.groupby(iter(xx), lambda x: yy[x]):
    print group[0], list(group[1])

Produces:

0 [0, 1, 2]
1 [3, 4, 5]
0 [6, 7, 8, 9]

Passing an array as parameter in JavaScript

Just remove the .value, like this:

function(arrayP){    
   for(var i = 0; i < arrayP.length; i++){
      alert(arrayP[i]);    //no .value here
   }
}

Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.

How do I write a "tab" in Python?

You can use \t in a string literal:

"hello\talex"

How to prevent Google Colab from disconnecting?

Well I am not a python guy nor I know what is the actual use of this 'Colab', I use it as a build system lol. And I used to setup ssh forwarding in it then put this code and just leave it running and yeah it works.

import getpass
authtoken = getpass.getpass()

Get current URL with jQuery?

If you want to get the path of the root site, use this:

$(location).attr('href').replace($(location).attr('pathname'),'');

EF Migrations: Rollback last applied migration?

In EF Core you can enter the command Remove-Migration in the package manager console after you've added your erroneous migration.

The console suggests you do so if your migration could involve a loss of data:

An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy. To undo this action, use Remove-Migration.

round up to 2 decimal places in java?

     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));

How can I center <ul> <li> into div

Just add text-align: center; to your <ul>. Problem solved.

Query to list all users of a certain group

memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:

(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))

If you don't yet have the distinguished name, you can search for it with:

(&(objectCategory=group)(cn=myCustomGroup))

and return the attribute distinguishedName. Case may matter.

Open Facebook page from Android app?

In Facebook version 11.0.0.11.23 (3002850) fb://profile/ and fb://page/ no longer work. I decompiled the Facebook app and found that you can use fb://facewebmodal/f?href=[YOUR_FACEBOOK_PAGE]. Here is the method I have been using in production:

/**
 * <p>Intent to open the official Facebook app. If the Facebook app is not installed then the
 * default web browser will be used.</p>
 *
 * <p>Example usage:</p>
 *
 * {@code newFacebookIntent(ctx.getPackageManager(), "https://www.facebook.com/JRummyApps");}
 *
 * @param pm
 *     The {@link PackageManager}. You can find this class through {@link
 *     Context#getPackageManager()}.
 * @param url
 *     The full URL to the Facebook page or profile.
 * @return An intent that will open the Facebook page/profile.
 */
public static Intent newFacebookIntent(PackageManager pm, String url) {
  Uri uri = Uri.parse(url);
  try {
    ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
    if (applicationInfo.enabled) {
      // http://stackoverflow.com/a/24547437/1048340
      uri = Uri.parse("fb://facewebmodal/f?href=" + url);
    }
  } catch (PackageManager.NameNotFoundException ignored) {
  }
  return new Intent(Intent.ACTION_VIEW, uri);
}

How to create and add users to a group in Jenkins for authentication?

I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.

I didn't have high hopes, as that plugin was last updated in 2011

Laravel Carbon subtract days from current date

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

How to gzip all files in all sub-directories into one compressed file in bash

there are lots of compression methods that work recursively command line and its good to know who the end audience is.

i.e. if it is to be sent to someone running windows then zip would probably be best:

zip -r file.zip folder_to_zip

unzip filenname.zip

for other linux users or your self tar is great

tar -cvzf filename.tar.gz folder

tar -cvjf filename.tar.bz2 folder  # even more compression

#change the -c to -x to above to extract

One must be careful with tar and how things are tarred up/extracted, for example if I run

cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd


pwd

/home/myusername

tar -xvzf passwd.tar.gz

this will create /home/myusername/etc/passwd

unsure if all versions of tar do this:

 Removing leading `/' from member names

In Unix, how do you remove everything in the current directory and below it?

Use

rm -rf *

Update: The . stands for current directory, but we cannot use this. The command seems to have explicit checks for . and ... Use the wildcard globbing instead. But this can be risky.

A safer version IMO is to use:

rm -ri * 

(this prompts you for confirmation before deleting every file/directory.)

How to flush route table in windows?

You can open a command prompt and do a

route print

and see your current routing table.

You can modify it by

route add    d.d.d.d mask m.m.m.m g.g.g.g 
route delete d.d.d.d mask m.m.m.m g.g.g.g 
route change d.d.d.d mask m.m.m.m g.g.g.g

these seem to work

I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)

Check if a class `active` exist on element with jquery

If Condition to check, currently class active or not

$('#next').click(function(){
    if($('p:last').hasClass('active'){
       $('.active').removeClass();
    }else{
       $('.active').addClass();
    }
});

Argument Exception "Item with Same Key has already been added"

That Exception is thrown if there is already a key in the dictionary when you try to add the new one.

There must be more than one line in rct3Lines with the same first word. You can't have 2 entries in the same dictionary with the same key.

You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply

rct3Features[items[0]]=items[1]

but, if not you may want to test if the key already exists with:

if(rect3Features.ContainsKey(items[0]))
{
    //Do something
} 
else 
{
    //Do something else
}

Parsing JSON in Java without knowing JSON format

To get JSON quickly into Java objects (Maps) that you can then 'drill' and work with, you can use json-io (https://github.com/jdereg/json-io). This library will let you read in a JSON String, and get back a 'Map of Maps' representation.

If you have the corresponding Java classes in your JVM, you can read the JSON in and it will parse it directly into instances of the Java classes.

JsonReader.jsonToMaps(String json)

where json is the String containing the JSON to be read. The return value is a Map where the keys will contain the JSON fields, and the values will contain the associated values.

JsonReader.jsonToJava(String json) 

will read the same JSON string in, and the return value will be the Java instance that was serialized into the JSON. Use this API if you have the classes in your JVM that were written by

JsonWriter.objectToJson(MyClass foo).

Passing an array as an argument to a function in C

In C, except for a few special cases, an array reference always "decays" to a pointer to the first element of the array. Therefore, it isn't possible to pass an array "by value". An array in a function call will be passed to the function as a pointer, which is analogous to passing the array by reference.

EDIT: There are three such special cases where an array does not decay to a pointer to it's first element:

  1. sizeof a is not the same as sizeof (&a[0]).
  2. &a is not the same as &(&a[0]) (and not quite the same as &a[0]).
  3. char b[] = "foo" is not the same as char b[] = &("foo").

What is the fastest factorial function in JavaScript?

Iterative:

Math.factorial=n=>{for(var o=n;n>1;)o*=--n;return o};

Recursive:

Math.factorial=n=>n>1?n--*Math.fac(n):1;

Precalculated:

(_=>{let f=[],i=0;for(;i<171;i++)f[i]=(n=>{for(var o=n;n>1;)o*=--n;return o})(i);Math.factorial=n=>{n=Math.round(n);return n<171?f[n]:Infinity}})();

https://code.sololearn.com/Wj4rlA27C9fD. Here I might post more solutions.

Client to send SOAP request and receive response

The best practice is to reference the WSDL and use it like a web service reference. It's easier and works better, but if you don't have the WSDL, the XSD definitions are a good piece of code.

Is there a RegExp.escape function in JavaScript?

Mozilla Developer Network's Guide to Regular Expressions provides this escaping function:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Change span text?

document.getElementById("serverTime").innerHTML = ...;

Pod install is staying on "Setting up CocoaPods Master repo"

When CocoaPods is doing that it is downloading the entire specs repo to ~/.cocoapods. This could take a while depending on your connection. I would try doing it explicitly first with pod setup

Open terminal here in Mac OS finder

There is a bug in the AppleScript on OSX 10.6. (2 terminal windows open). I fixed this by adding the close command after activate. This close the first Terminal window.

on run
    tell application "Finder"
        try
            activate
            set frontWin to folder of front window as string
            set frontWinPath to (get POSIX path of frontWin)
            tell application "Terminal"
                activate
                close
                do script with command "cd \"" & frontWinPath & "\""
            end tell
        on error error_message
            beep
            display dialog error_message buttons ¬
                {"OK"} default button 1
        end try
    end tell
end run

Getting Keyboard Input

You can use Scanner class

To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util package.

Scanner package used for obtaining the input of the primitive types like int, double etc. and strings. It is the easiest way to read input in a Java program, though not very efficient.

  1. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream (Keyboard).

For example, this code allows a user to read a number from System.in:

Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

Some Public methods in Scanner class.

  • hasNext() Returns true if this scanner has another token in its input.
  • nextInt() Scans the next token of the input as an int.
  • nextFloat() Scans the next token of the input as a float.
  • nextLine() Advances this scanner past the current line and returns the input that was skipped.
  • nextDouble() Scans the next token of the input as a double.
  • close() Closes this scanner.

For more details of Public methods in Scanner class.

Example:-

import java.util.Scanner;                      //importing class

class ScannerTest {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);       // Scanner object

    System.out.println("Enter your rollno");
    int rollno = sc.nextInt();
    System.out.println("Enter your name");
    String name = sc.next();
    System.out.println("Enter your fee");
    double fee = sc.nextDouble();
    System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
    sc.close();                              // closing object
  }
}

String.equals versus ==

== tests for reference equality.

.equals() tests for value equality.

Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).

== is for testing whether two strings are the same Object.

// These two have the same value
new String("test").equals("test") ==> true 

// ... but they are not the same object
new String("test") == "test" ==> false 

// ... neither are these
new String("test") == new String("test") ==> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" ==> true 

// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st"  ==> true

// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false

It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.

Submit form on pressing Enter with AngularJS

Will be slightly neater using a CSS class instead of repeating inline styles.

CSS

input[type=submit] {
    position: absolute;
    left: -9999px;
}

HTML

<form ng-submit="myFunc()">
    <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
    <input type="submit" />
</form>

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

How to sum a variable by group

While I have recently become a convert to dplyr for most of these types of operations, the sqldf package is still really nice (and IMHO more readable) for some things.

Here is an example of how this question can be answered with sqldf

x <- data.frame(Category=factor(c("First", "First", "First", "Second",
                                  "Third", "Third", "Second")), 
                Frequency=c(10,15,5,2,14,20,3))

sqldf("select 
          Category
          ,sum(Frequency) as Frequency 
       from x 
       group by 
          Category")

##   Category Frequency
## 1    First        30
## 2   Second         5
## 3    Third        34

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

How to initialize a two-dimensional array in Python?

from random import randint
l = []

for i in range(10):
    k=[]
    for j in range(10):
        a= randint(1,100)
        k.append(a)

    l.append(k)




print(l)
print(max(l[2]))

b = []
for i in range(10):
    a = l[i][5]
    b.append(a)

print(min(b))

how to align all my li on one line?

I'm would recommend it:

<style>
    .clearfix {
       *zoom: 1;
    }
    .clearfix:before,
    .clearfix:after {
        content: " ";
        display: table;
    }
    .clearfix:after {
        clear: both;
    }
    ul.list {
       list-style: none;
    }
    ul.list li {
       display: inline-block;
    }
</style>

<ul class="list clearfix">
    <li>li-one</li>
    <li>li-two</li>
    <li>li-three</li>
    <li>li-four</li>
</ul>

C# event with custom arguments

You need to declare a custom eventhandler.

public class MyEventArgs: EventArgs
{
  ...
}

public delegate void MyEventHandler(object sender, MyEventArgs e);

public class MyControl: UserControl
{
  public event MyEventHandler MyEvent;
   ...
}

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

jQuery: selecting each td in a tr

Fully example to demonstrate how jQuery query all data in HTML table.

Assume there is a table like the following in your HTML code.

<table id="someTable">
  <thead>
    <tr>
      <td>title 0</td>
      <td>title 1</td>
      <td>title 2</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>row 0 td 0</td>
      <td>row 0 td 1</td>
      <td>row 0 td 2</td>
    </tr>
    <tr>
      <td>row 1 td 0</td>
      <td>row 1 td 1</td>
      <td>row 1 td 2</td>
    </tr>
    <tr>
      <td>row 2 td 0</td>
      <td>row 2 td 1</td>
      <td>row 2 td 2</td>
    </tr>
    <tr> ... </tr>
    <tr> ... </tr>
    ...
    <tr> ... </tr>
    <tr>
      <td>row n td 0</td>
      <td>row n td 1</td>
      <td>row n td 2</td>
    </tr>
  </tbody>
</table>

Then, The Answer, the code to print all row all column, should like this

$('#someTable tbody tr').each( (tr_idx,tr) => {
    $(tr).children('td').each( (td_idx, td) => {
        console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
    });                 
});

After running the code, the result will show

[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
...
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2

Summary.
In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.

From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.

How do I include image files in Django templates?

Try this,

settings.py

# typically, os.path.join(os.path.dirname(__file__), 'media')
MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'

urls.py

urlpatterns = patterns('',
               (r'^media/(?P<path>.*)$', 'django.views.static.serve',
                 {'document_root': settings.MEDIA_ROOT}),
              )

.html

<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />

Caveat

Beware! using Context() will yield you an empty value for {{MEDIA_URL}}. You must use RequestContext(), instead.

I hope, this will help.

How to exclude a directory from ant fileset, based on directories contents

Answer provided by user mgaert works for me. I think it should be marked as the right answer.

It works also with complex selectors like in this example:

<!-- 
    selects only direct subdirectories of ${targetdir} if they have a
    sub-subdirectory named either sub1 or sub2
-->
<dirset dir="${targetdir}" >
    <and>
        <depth max="0"/>
        <or>
            <present targetdir="${targetdir}">
                <globmapper from="*" to="*/sub1" />
            </present>
            <present targetdir="${targetdir}">
                <globmapper from="*" to="*/sub2" />
            </present>
        </or>
    </and>
</dirset>

Thus, having a directory structure like this:

targetdir
+-- bar
¦   +-- sub3
+-- baz
¦   +-- sub1
+-- foo
¦   +-- sub2
+-- phoo
¦   +-- sub1
¦   +-- sub2
+-- qux
    +-- xyzzy
        +-- sub1

the above dirset would contain only

baz foo phoo
(bar doesn't match because of sub3 while xyzzy doesn't match because it's not a direct subdirectory of targetdir)

List vs tuple, when to use each?

I believe (and I am hardly well-versed in Python) that the main difference is that a tuple is immutable (it can't be changed in place after assignment) and a list is mutable (you can append, change, subtract, etc).

So, I tend to make my tuples things that shouldn't change after assignment and my lists things that can.

How do I get the object if it exists, or None if it does not exist?

To make things easier, here is a snippet of the code I wrote, based on inputs from the wonderful replies here:

class MyManager(models.Manager):

    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except ObjectDoesNotExist:
            return None

And then in your model:

class MyModel(models.Model):
    objects = MyManager()

That's it. Now you have MyModel.objects.get() as well as MyModel.objetcs.get_or_none()

How to solve '...is a 'type', which is not valid in the given context'? (C#)

Change

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS = new CERas.CERAS(); 
    } 

to

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS c = new CERas.CERAS(); 
    } 

Or if you wish to use it later again

change it to

using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WinApp_WMI2 
{ 
    public partial class Form1 : Form 
    { 
        CERas.CERAS m_CERAS;

        public Form1() 
        { 
            InitializeComponent(); 
        } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
        m_CERAS = new CERas.CERAS(); 
    } 
} 


}

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

PYODBC--Data source name not found and no default driver specified

I faced this issue and was looking for the solution. Finally I was trying all the options from the https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows , and for my MSSQL 12 only "{ODBC Driver 11 for SQL Server}" works. Just try it one by one. And the second important thing you have to get correct server name, because I thought preciously that I need to set \SQLEXPRESS in all of the cases, but found out that you have to set EXACTLY what you see in the server properties. Example on the screenshot: enter image description here

How do I loop through or enumerate a JavaScript object?

It's interesting people in these answers have touched on both Object.keys() and for...of but never combined them:

var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
    console.log(key + ':' + map[key]);

You can't just for...of an Object because it's not an iterator, and for...index or .forEach()ing the Object.keys() is ugly/inefficient.
I'm glad most people are refraining from for...in (with or without checking .hasOwnProperty()) as that's also a bit messy, so other than my answer above, I'm here to say...


You can make ordinary object associations iterate! Behaving just like Maps with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)

var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
    //key:value
    console.log(pair[0] + ':' + pair[1]);

//or
for (let [key, value] of ordinaryObject)
    console.log(key + ':' + value);

So long as you include my shim below:

//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
    var keys = Object.keys(this)[Symbol.iterator]();
    var obj = this;
    var output;
    return {next:function() {
        if (!(output = keys.next()).done)
            output.value = [output.value, obj[output.value]];
        return output;
    }};
};

Without having to create a real Map object that doesn't have the nice syntactic sugar.

var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
    console.log(pair[0] + ':' + pair[1]);

In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!

//shown in demo
var realMap = new Map({well:'hello', there:'!'});

For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;

//no prototype manipulation
function getObjIterator(obj) {
    //create a dummy object instead of adding functionality to all objects
    var iterator = new Object();

    //give it what the shim does but as its own local property
    iterator[Symbol.iterator] = function() {
        var keys = Object.keys(obj)[Symbol.iterator]();
        var output;

        return {next:function() {
            if (!(output = keys.next()).done)
                output.value = [output.value, obj[output.value]];
            return output;
        }};
    };

    return iterator;
}

Now you can just call it as an ordinary function, nothing else is affected

var realMap = new Map(getObjIterator({well:'hello', there:'!'}))

or

for (let pair of getObjIterator(ordinaryObject))

There's no reason why that wouldn't work.

Welcome to the future.

image processing to improve tesseract OCR accuracy

As a rule of thumb, I usually apply the following image pre-processing techniques using OpenCV library:

  1. Rescaling the image (it's recommended if you’re working with images that have a DPI of less than 300 dpi):

    img = cv2.resize(img, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_CUBIC)
    
  2. Converting image to grayscale:

    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
  3. Applying dilation and erosion to remove the noise (you may play with the kernel size depending on your data set):

    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)
    
  4. Applying blur, which can be done by using one of the following lines (each of which has its pros and cons, however, median blur and bilateral filter usually perform better than gaussian blur.):

    cv2.threshold(cv2.GaussianBlur(img, (5, 5), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.threshold(cv2.bilateralFilter(img, 5, 75, 75), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.threshold(cv2.medianBlur(img, 3), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.adaptiveThreshold(cv2.GaussianBlur(img, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    
    cv2.adaptiveThreshold(cv2.bilateralFilter(img, 9, 75, 75), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    
    cv2.adaptiveThreshold(cv2.medianBlur(img, 3), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    

I've recently written a pretty simple guide to Tesseract but it should enable you to write your first OCR script and clear up some hurdles that I experienced when things were less clear than I would have liked in the documentation.

In case you'd like to check them out, here I'm sharing the links with you:

iFrame onload JavaScript event

_x000D_
_x000D_
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
    this.style.backgroundColor = "red";_x000D_
    alert(this.nodeName);_x000D_
_x000D_
    console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
_x000D_
_x000D_

sql query to get earliest date

If you just want the date:

SELECT MIN(date) as EarliestDate
FROM YourTable
WHERE id = 2

If you want all of the information:

SELECT TOP 1 id, name, score, date
FROM YourTable
WHERE id = 2
ORDER BY Date

Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.

Android SQLite: Update Statement

You can try:

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

Or

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

db.update("YOUR_TABLE", newValues, "id=6", null);

Or

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

String[] args = new String[]{"user1", "user2"};
db.update("YOUR_TABLE", newValues, "name=? OR name=?", args);

HTML <input type='file'> File Selection Event

jQuery way:

$('input[name=myInputName]').change(function(ev) {

    // your code
});

Extract first and last row of a dataframe in pandas

I think the most simple way is .iloc[[0, -1]].

df = pd.DataFrame({'a':range(1,5), 'b':['a','b','c','d']})
df2 = df.iloc[[0, -1]]

print df2

   a  b
0  1  a
3  4  d

Create list of single item repeated N times

Create List of Single Item Repeated n Times in Python

Depending on your use-case, you want to use different techniques with different semantics.

Multiply a list for Immutable items

For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:

[e] * 4

Note that this is usually only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.

schema = ['string'] * len(columns)

Multiply the list where we want the same item repeated

Multiplying a list gives us the same elements over and over. The need for this is rare:

[iter(iterable)] * 4

This is sometimes used to map an iterable into a list of lists:

>>> iterable = range(12)
>>> a_list = [iter(iterable)] * 4
>>> [[next(l) for l in a_list] for i in range(3)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

We can see that a_list contains the same range iterator four times:

>>> a_list
[<range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>]

Mutable items

I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.

Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:

list_of_lists = [[] for _ in columns]

The underscore is simply a throwaway variable name in this context.

If you only have the number, that would be:

list_of_lists = [[] for _ in range(4)]

The _ is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.


Caveats for using the immutable method with mutable items:

Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:

foo = [[]] * 4
foo[0].append('x')

foo now returns:

[['x'], ['x'], ['x'], ['x']]

But with immutable objects, you can make it work because you change the reference, not the object:

>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]

>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]

But again, mutable objects are no good for this, because in-place operations change the object, not the reference:

l = [set()] * 4
>>> l[0] |= set('abc')    
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]

Find intersection of two nested lists?

You should flatten using this code ( taken from http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks ), the code is untested, but I'm pretty sure it works:


def flatten(x):
    """flatten(sequence) -> list

    Returns a single, flat list which contains all elements retrieved
    from the sequence and all recursively contained sub-sequences
    (iterables).

    Examples:
    >>> [1, 2, [3,4], (5,6)]
    [1, 2, [3, 4], (5, 6)]
    >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
    [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""

    result = []
    for el in x:
        #if isinstance(el, (list, tuple)):
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

After you had flattened the list, you perform the intersection in the usual way:


c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

def intersect(a, b):
     return list(set(a) & set(b))

print intersect(flatten(c1), flatten(c2))

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

How do I remove all non-ASCII characters with regex and Notepad++?

This expression will search for non-ASCII values:

[^\x00-\x7F]+

Tick off 'Search Mode = Regular expression', and click Find Next.

Source: Regex any ASCII character

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

Escaping single quotes in JavaScript string for JavaScript evaluation

var str ="fsdsd'4565sd"; str.replace(/'/g,"'")

This worked for me. Kindly try this

enter image description here

Parsing date string in Go

This is rather late to the party, and not really saying anything that hasn't been already said in one form or another, mostly through links above, but I wanted to give a TL;DR recap to those with less attention span:

The date and time of the go format string is very important. It's how Go knows which field is which. They are generally 1-9 left to right as follows:

  • January / Jan / january / jan / 01 / _1 (etc) are for month
  • 02 / _2 are for day of month
  • 15 / 03 / _3 / PM / P / pm /p are for hour & meridian (3pm)
  • 04 / _4 are for minutes
  • 05 / _5 are for seconds
  • 2006 / 06 are for year
  • -0700 / 07:00 / MST are for timezone
  • .999999999 / .000000000 etc are for partial seconds (I think the distinction is if trailing zeros are removed)
  • Mon / Monday are day of the week (which 01-02-2006 actually was),

So, Don't write "01-05-15" as your date format, unless you want "Month-Second-Hour"

(... again, this was basically a summary of above.)

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

// find the first select and bind a click handler
$('#column_select').bind('click', function(){
    // retrieve the selected value
    var value = $(this).val(),
        // build a regular expression that does a head-match
        expression = new RegExp('^' + value),
        // find the second select
        $select = $('#layout_select);

    // hide all children (<option>s) of the second select,
    // check each element's value agains the regular expression built from the first select's value
    // show elements that match the expression
    $select.children().hide().filter(function(){
      return !!$(this).val().match(expression);
    }).show();
});

(this is far from perfect, but should get you there…)

How do I install g++ on MacOS X?

Type g++(or make) on terminal.

This will prompt for you to install the developer tools, if they are missing.

Also the size will be very less when compared to xcode

Direct casting vs 'as' operator?

string s = (string)o; // 1

Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.

string s = o as string; // 2

Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.

string s = o.ToString(); // 3

Causes a NullReferenceException if o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.


Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).

3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.

What is username and password when starting Spring Boot with Tomcat?

For a start simply add the following to your application.properties file

spring.security.user.name=user
spring.security.user.password=pass

NB: with no double quote

Run your application and enter the credentials (user, pass)

How do I comment on the Windows command line?

: this is one way to comment

As a result:

:: this will also work
:; so will this
:! and this

Above styles work outside codeblocks, otherwise:

REM is another way to comment.

How to cut first n and last n columns?

To use AWK to cut off the first and last fields:

awk '{$1 = ""; $NF = ""; print}' inputfile

Unfortunately, that leaves the field separators, so

aaa bbb ccc

becomes

[space]bbb[space]

To do this using kurumi's answer which won't leave extra spaces, but in a way that's specific to your requirements:

awk '{delim = ""; for (i=2;i<=NF-1;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile

This also fixes a couple of problems in that answer.

To generalize that:

awk -v skipstart=1 -v skipend=1 '{delim = ""; for (i=skipstart+1;i<=NF-skipend;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile

Then you can change the number of fields to skip at the beginning or end by changing the variable assignments at the beginning of the command.

Best way to structure a tkinter application?

Organizing your application using class make it easy to you and others who work with you to debug problems and improve the app easily.

You can easily organize your application like this:

class hello(Tk):
    def __init__(self):
        super(hello, self).__init__()
        self.btn = Button(text = "Click me", command=close)
        self.btn.pack()
    def close():
        self.destroy()

app = hello()
app.mainloop()

jquery to validate phone number

function validatePhone(txtPhone) {
    var a = document.getElementById(txtPhone).value;
    var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
    if (filter.test(a)) {
        return true;
    }
    else {
        return false;
    }
}

Demo http://jsfiddle.net/dishantd/JLJMW/496/

Cannot deserialize the current JSON array (e.g. [1,2,3])

This could be You

Before trying to consume your json object with another object just check that the api is returning raw json via the browser api/rootobject, for my case i found out that the underlying data provider mssqlserver was not running and throw an unhanded exception !

as simple as that :)

What's the function like sum() but for multiplication? product()?

I prefer the answers a and b above using functools.reduce() and the answer using numpy.prod(), but here is yet another solution using itertools.accumulate():

import itertools
import operator
prod = list(itertools.accumulate((3, 4, 5), operator.mul))[-1]

LINUX: Link all files from one to another directory

The posted solutions will not link any hidden files. To include them, try this:

cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib not /mnt/usr/lib), you could do this:

cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

Uncaught SyntaxError: Unexpected token :

Uncaught SyntaxError: Unexpected token }

Chrome gaved me the error for this sample code:

<div class="file-square" onclick="window.location = " ?dir=zzz">
    <div class="square-icon"></div>
    <div class="square-text">zzz</div>
</div>

and solved it fixing the onclick to be like

... onclick="window.location = '?dir=zzz'" ...

But the error has nothing to do with the problem..

How to install and run phpize

This might help someone on ubuntu. No promises.

sudo apt-get install libcurl3 php5-dev libcurl4-gnutls-dev libmagic-dev
sudo apt-get install php-http make
sudo pecl install pecl_http

And adding "extension=http.so" to php.ini (Normally located at /etc/php5/apache2/php.ini)

Then restart Apache (sudo service apache2 restart).

If in doubt, check your apache logs:

sudo su --
cd /var/log/apache2
tail -25 error.log

Is http.so starting or failing?

How do I check what version of Python is running my script?

Here's a short commandline version which exits straight away (handy for scripts and automated execution):

python -c "print(__import__('sys').version)"

Or just the major, minor and micro:

python -c "print(__import__('sys').version_info[:1])" # (2,)
python -c "print(__import__('sys').version_info[:2])" # (2, 7)
python -c "print(__import__('sys').version_info[:3])" # (2, 7, 6)

How to change node.js's console font color?

I really liked @Daniel's answer, but the console.log{color} functions didn't work the same way as regular console.log. I have made a few changes, and now all parameters to the new functions will be passed to console.log (as well as the color codes).

const _colors = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

const enableColorLogging = function(){
    Object.keys(_colors).forEach(key => {
        console['log' + key] = function(){
            return console.log(_colors[key], ...arguments, _colors.Reset);
        }
    });
}

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

It sounds to me that you really want to limit the rows being returned in your query and page through the results. If so, you can do something like:

select * from (select rownum myrow, a.* from TEST1 a )
where myrow between 5 and 10 ;

You just have to determine your boundaries.

What is the behavior of integer division?

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

How to make several plots on a single page using matplotlib?

To answer your main question, you want to use the subplot command. I think changing plt.figure(i) to plt.subplot(4,4,i+1) should work.

How to display Base64 images in HTML?

The + character occurring in a data URI should be encoded as %2B. This is like encoding any other string in a URI. For example, argument separators (? and &) must be encoded when a URI with an argument is sent as part of another URI.

How to check for empty value in Javascript?

First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).

Also, for your if-condition, this should suffice:

if (!timetemp[0].value) {
    // The value is empty.
}
else {
    // The value is not empty.
}

The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.

Is it bad practice to use break to exit a loop in Java?

It isn't bad practice, but it can make code less readable. One useful refactoring to work around this is to move the loop to a separate method, and then use a return statement instead of a break, for example this (example lifted from @Chris's answer):

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
        //you've found the item. Let's stop.
        item = array[x];
        break; 
    }
}

can be refactored (using extract method) to this:

public String searchForItem(String itemIamLookingFor)
{
    for(int x = 0; x < 10; x++)
    {
        if(array[x].equals(itemIamLookingFor))
        {
            return array[x];
        }
    }
}

Which when called from the surrounding code can prove to be more readable.

Uncaught ReferenceError: $ is not defined error in jQuery

The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.

BOTTOM PART OF _Layout.cshtml:

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

</body>
</html>

I moved them above the @RenderBody() and all was fine.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

JQuery wait for page to finish loading before starting the slideshow?

you can try

$(function()
{

$(window).bind('load', function()
{

// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...

});
});

i had the same problem and this code worked for me. how it works for you too!

Inserting HTML into a div

Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:

$('#yourDivName').html('yourtHTML');

You may also consider using:

$('#yourDivName').append('yourtHTML');

This will add your gallery as the last item in the selected div. Or:

$('#yourDivName').prepend('yourtHTML');

This will add it as the first item in the selected div.

See the JQuery docs for these functions:

How to keep one variable constant with other one changing with row in excel

You put it as =(B0+4)/($A$0)

You can also go across WorkSheets with Sheet1!$a$0

Copy tables from one database to another in SQL Server

If there is existing table and we wants to copy only data, we can try this query.

insert into Destination_Existing_Tbl select col1,col2 FROM Source_Tbl

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

How to determine whether a Pandas Column contains a particular value

I did a few simple tests:

In [10]: x = pd.Series(range(1000000))

In [13]: timeit 999999 in x.values
567 µs ± 25.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [15]: timeit x.isin([999999]).any()
9.54 ms ± 291 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [16]: timeit (x == 999999).any()
6.86 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [17]: timeit 999999 in set(x)
79.8 ms ± 1.98 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [21]: timeit x.eq(999999).any()
7.03 ms ± 33.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [22]: timeit x.eq(9).any()
7.04 ms ± 60 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [24]: timeit 9 in x.values
666 µs ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Interestingly it doesn't matter if you look up 9 or 999999, it seems like it takes about the same amount of time using the in syntax (must be using binary search)

In [24]: timeit 9 in x.values
666 µs ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [25]: timeit 9999 in x.values
647 µs ± 5.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [26]: timeit 999999 in x.values
642 µs ± 2.11 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [27]: timeit 99199 in x.values
644 µs ± 5.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [28]: timeit 1 in x.values
667 µs ± 20.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Seems like using x.values is the fastest, but maybe there is a more elegant way in pandas?

How to resolve this System.IO.FileNotFoundException

I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.

If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...

Before going down the dll version path... Check closer to home and verify your thread code is not throwing.

Is it possible to make input fields read-only through CSS?

Not really what you need, but it can help and answser the question here depending of what you want to achieve.

You can prevent all pointer events to be sent to the input by using the CSS property : pointer-events:none It will kind of add a layer on top of the element that will prevent you to click in it ... You can also add a cursor:text to the parent element to give back the text cursor style to the input ...

Usefull, for example, when you can't modify the JS/HTML of a module.. and you can just customize it by css.

JSFIDDLE

How to use JavaScript source maps (.map files)?

Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.

  1. Grunt: using plugin grunt-contrib-uglify
  2. Gulp: using plugin gulp-uglify
  3. Google closure: using parameter --create_source_map

How do I get sed to read from standard input?

  1. Open the file using vi myfile.csv
  2. Press Escape
  3. Type :%s/replaceme/withthis/
  4. Type :wq and press Enter

Now you will have the new pattern in your file.

Disabling the button after once click

protected void Page_Load(object sender, EventArgs e)
    {
        // prevent user from making operation twice
        btnSave.Attributes.Add("onclick", 
                               "this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");

        // ... etc. 
    }

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

Printing prime numbers from 1 through 100

Just try this. It's easy without any extra builtin functions.

#include <iostream>

int prime(int n,int r){

  for(int i=2;n<=r;i++){
    if(i==2 || i==3 || i==5 || i==7){
      std::cout<<i<<" ";
      n++;
    } else if(i%2==0 || i%3==0 || i%5==0 || i%7==0)
      continue;
    else {
      std::cout<<i<<" ";
      n++;
    }
  }

}

main(){

  prime(1,25);
}

Testing by 2,3,5,7 is good enough for up to 120, so 100 is OK.

There are 25 primes below 100, an 30 below 121 = 11*11.

Laravel password validation rule

I have had a similar scenario in Laravel and solved it in the following way.

The password contains characters from at least three of the following five categories:

  • English uppercase characters (A – Z)
  • English lowercase characters (a – z)
  • Base 10 digits (0 – 9)
  • Non-alphanumeric (For example: !, $, #, or %)
  • Unicode characters

First, we need to create a regular expression and validate it.

Your regular expression would look like this:

^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$

I have tested and validated it on this site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipluated the way you want.

So your final Laravel code should be like this:

'password' => 'required|
               min:6|
               regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/|
               confirmed',

Update As @NikK in the comment mentions, in Laravel 5.5 and newer the the password value should encapsulated in array Square brackets like

'password' => ['required', 
               'min:6', 
               'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/', 
               'confirmed']

I have not testing it on Laravel 5.5 so I am trusting @NikK hence I have moved to working with c#/.net these days and have no much time for Laravel.

Note:

  1. I have tested and validated it on both the regular expression site and a Laravel 5 test environment and it works.
  2. I have used min:6, this is optional but it is always a good practice to have a security policy that reflects different aspects, one of which is minimum password length.
  3. I suggest you to use password confirmed to ensure user typing correct password.
  4. Within the 6 characters our regex should contain at least 3 of a-z or A-Z and number and special character.
  5. Always test your code in a test environment before moving to production.
  6. Update: What I have done in this answer is just example of regex password

Some online references

Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:

How to use http.client in Node.js if there is basic authorization

for what it's worth I'm using node.js 0.6.7 on OSX and I couldn't get 'Authorization':auth to work with our proxy, it needed to be set to 'Proxy-Authorization':auth my test code is:

var http = require("http");
var auth = 'Basic ' + new Buffer("username:password").toString('base64');
var options = {
    host: 'proxyserver',
    port: 80,
    method:"GET",
    path: 'http://www.google.com',
    headers:{
        "Proxy-Authorization": auth,
        Host: "www.google.com"
    } 
};
http.get(options, function(res) {
    console.log(res);
    res.pipe(process.stdout);
});

callback to handle completion of pipe

Based nodejs document, http://nodejs.org/api/stream.html#stream_event_finish, it should handle writableStream's finish event.

var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

How to delete empty folders using windows command prompt?

A simpler way is to do xcopy to make a copy of the entire directory structure using /s switch. help for /s says Copies directories and subdirectories except empty ones.

xcopy dirA dirB /S

where dirA is source with Empty folders. DirB will be the copy without empty folders

How do I put double quotes in a string in vba?

All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard", In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?