Programs & Examples On #Disk io

Fast Linux file count for a large number of files

This answer here is faster than almost everything else on this page for very large, very nested directories:

https://serverfault.com/a/691372/84703

locate -r '.' | grep -c "^$PWD"

Synchronizing a local Git repository with a remote one

You can use git hooks for that. Just create a hook that pushes changed to the other repo after an update.

Of course you might get merge conflicts so you have to figure how to deal with them.

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

This happens when you somehow confused java itself. You are trying to run a java 6 VM where it found a JRE 7. It might show this problem even if you type in the command line just java or java -version in a misconfigured environment. The JAR is not the problem, except in the very unlikely case where the code in JAR is looking in the Windows Registry for that (which probably is not your case).

In my case, I had the java.exe, javaw.exe and javaws.exe from Java 6 in the Windows/System32 folder (don't know how it got to be there). The rest of the JDK and JRE where found in the PATH inside C:\Java\jdk_1.7.0\bin. Oops!

How to copy Java Collections list

To understand why Collections.copy() throws an IndexOutOfBoundsException although you've made the backing array of the destination list large enough (via the size() call on the sourceList), see the answer by Abhay Yadav in this related question: How to copy a java.util.List into another java.util.List

Inserting NOW() into Database with CodeIgniter's Active Record

This is the easy way to handle timestamp insertion

$data = array('created_on' => date('Y-m-d H:i:s'));

Best way to convert IList or IEnumerable to Array

Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray() and be done with it.

If you only have a non-generic IEnumerable, do something like this:

IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();

If you don't know the type within that method but the method's callers do know it, make the method generic and try this:

public static void T[] PerformQuery<T>()
{
    IEnumerable query = ...;
    T[] array = query.Cast<T>().ToArray();
    return array;
}

How to update data in one table from corresponding data in another table in SQL Server 2005

If the two databases are on the same server, you should be able to create a SQL statement something like this:

UPDATE Test1.dbo.Employee
SET DeptID = emp2.DeptID
FROM Test2.dbo.Employee as 'emp2'
WHERE
   Test1.dbo.Employee.EmployeeID = emp2.EmployeeID

From your post, I'm not quite clear whether you want to update Test1.dbo.Employee with the values from Test2.dbo.Employee (that's what my query does), or the other way around (since you mention the db on Test1 was the new table......)

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

SQL Server Configuration Manager not found

This path worked for me. on a 32 bit machine.

C:\Windows\System32\mmc.exe /32 C:\Windows\system32\SQLServerManager10.msc

How can I order a List<string>?

ListaServizi.Sort();

Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.

Java : Cannot format given Object as a Date

I have resolved it , this way

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateParser {

    public static void main(String args[]) throws Exception {

        DateParser dateParser = new DateParser();

        String str = dateParser.getparsedDate("2012-11-17T00:00:00.000-05:00");
        System.out.println(str);
    }


    private String getparsedDate(String date) throws Exception {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
        String s1 = date;
        String s2 = null;
        Date d;
        try {
            d = sdf.parse(s1);
            s2 = (new SimpleDateFormat("MM/yyyy")).format(d);

        } catch (ParseException e) {

            e.printStackTrace();
        }

        return s2;

    }

}

How to fill DataTable with SQL Table

The answers above are correct, but I thought I would expand another answer by offering a way to do the same if you require to pass parameters into the query.

The SqlDataAdapter is quick and simple, but only works if you're filling a table with a static request ie: a simple SELECT without parameters.

Here is my way to do the same, but using a parameter to control the data I require in my table. And I use it to populate a DropDownList.

//populate the Programs dropdownlist according to the student's study year / preference
DropDownList ddlPrograms = (DropDownList)DetailsView1.FindControl("ddlPrograms");
if (ddlPrograms != null)
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ATCNTV1ConnectionString"].ConnectionString))
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT ProgramID, ProgramName FROM tblPrograms WHERE ProgramCatID > 0 AND ProgramStatusID = (CASE WHEN @StudyYearID = 'VPR' THEN 10 ELSE 7 END) AND ProgramID NOT IN (23,112,113) ORDER BY ProgramName";
            cmd.Parameters.Add("@StudyYearID", SqlDbType.Char).Value = "11";
            DataTable wsPrograms = new DataTable();
            wsPrograms.Load(cmd.ExecuteReader());

            //populate the Programs ddl list
            ddlPrograms.DataSource = wsPrograms;
            ddlPrograms.DataTextField = "ProgramName";
            ddlPrograms.DataValueField = "ProgramID";
            ddlPrograms.DataBind();
            ddlPrograms.Items.Insert(0, new ListItem("<Select Program>", "0"));
        }
        catch (Exception ex)
        {
            // Handle the error
        }
    }
}

Enjoy

Android - Pulling SQlite database android device

For Ubuntu (not only?):

see Sergeis Answer but instead of openssl use zlib-flate:

cat appbackup.ab | (dd bs=24 count=0 skip=1; cat) | zlib-flate -uncompress > appbackup.tar

Otherwise openssl will probably throw:

openssl:Error: 'zlib' is an invalid command.

because openssl is not compiled with zlib support in Ubuntu

Vue.js unknown custom element

Vue definitely has some bugs around this. I find that although registering a component like so

components: { MyComponent }

will work most of the time, and can be used as MyComponent or my-component automatically, sometimes you have to spell it out as such

components: { 'my-component' : MyComponent }

And use it strictly as my-component

How to get Javascript Select box's selected text

In order to get the value of the selected item you can do the following:

this.options[this.selectedIndex].text

Here the different options of the select are accessed, and the SelectedIndex is used to choose the selected one, then its text is being accessed.

Read more about the select DOM here.

SQL server stored procedure return a table

I do this frequently using Table Types to ensure more consistency and simplify code. You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ... syntax, you can clearly call a PROC and store the results into a table type. In the following example I'm actually passing a table into a PROC along with another param I need to add logic, then I'm effectively "returning a table" and can then work with that as a table variable.

/****** Check if my table type and/or proc exists and drop them ******/
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'returnTableTypeData')
DROP PROCEDURE returnTableTypeData
GO
IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'myTableType')
DROP TYPE myTableType
GO

/****** Create the type that I'll pass into the proc and return from it ******/
CREATE TYPE [dbo].[myTableType] AS TABLE(
    [someInt] [int] NULL,
    [somenVarChar] [nvarchar](100) NULL
)
GO

CREATE PROC returnTableTypeData
    @someInputInt INT,
    @myInputTable myTableType READONLY --Must be readonly because
AS
BEGIN

    --Return the subset of data consistent with the type
    SELECT
        *
    FROM
        @myInputTable
    WHERE
        someInt < @someInputInt

END
GO


DECLARE @myInputTableOrig myTableType
DECLARE @myUpdatedTable myTableType

INSERT INTO @myInputTableOrig ( someInt,somenVarChar )
VALUES ( 0, N'Value 0' ), ( 1, N'Value 1' ), ( 2, N'Value 2' )

INSERT INTO @myUpdatedTable EXEC returnTableTypeData @someInputInt=1, @myInputTable=@myInputTableOrig

SELECT * FROM @myUpdatedTable


DROP PROCEDURE returnTableTypeData
GO
DROP TYPE myTableType
GO

Correct path for img on React.js

Some older answers din't work, others are good but won't explain the theme, in summary:

If image is in 'public' directory

Example: \public\charts\a.png

In html:

<img id="imglogo" src="/charts/logo.svg" />

In JavaScript:

Create image to new img, dynamically:

var img1 = document.createElement("img");  
img1.src = 'charts/a.png';  

Set image to existing img with id as 'img1', dynamically:

document.getElementById('img1').src = 'charts/a.png';

If image is in 'src' directory:

Example: \src\logo.svg

In JavaScript:

import logo from './logo.svg';  
img1.src = logo;  

In jsx:

<img src={logo} /> 

How to install and run Typescript locally in npm?

You need to tell npm that "tsc" exists as a local project package (via the "scripts" property in your package.json) and then run it via npm run tsc. To do that (at least on Mac) I had to add the path for the actual compiler within the package, like this

{
  "name": "foo"
  "scripts": {
    "tsc": "./node_modules/typescript/bin/tsc"
  },
  "dependencies": {
    "typescript": "^2.3.3",
    "typings": "^2.1.1"
  }
}

After that you can run any TypeScript command like npm run tsc -- --init (the arguments come after the first --).

sql server invalid object name - but tables are listed in SSMS tables list

Solved for SSMS 2016.

Had a similar problem, but Intellisense was not in Edit menu.

What seemed to fix it was turning Intellisens on and off, right click on the SQL editor and click 'Intellisense Enabled'. Right click again on 'Intellisense Enabled' to turn it back on again. Ctr Q, I also does this.

This solved the problem, and also I know get the Intellisense on the Edit menu.

How can I simulate a click to an anchor tag?

Quoted from https://developer.mozilla.org/en/DOM/element.click

The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.

Non–Gecko DOMs may behave differently.

Unfortunately it sounds like you have already discovered the best solution to your problem.

As a side note, I agree that your solution seems less than ideal, but if you encapsulate the functionality inside a method (much like JQuery would do) it is not so bad.

iOS 7 status bar back to iOS 6 default style in iPhone app?

A small alternative to Archy Holt's answer, a bit more simple:

a. Set UIViewControllerBasedStatusBarAppearance to NO in info.plist

b. In AppDelegate's application:didFinishLaunchingWithOptions:, call:

if ([[UIDevice currentDevice].systemVersion floatValue] < 7)
{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
}
else
{
    // handling statusBar (iOS7)
    application.statusBarStyle = UIStatusBarStyleLightContent;
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    self.window.clipsToBounds = YES;

    // handling screen rotations for statusBar (iOS7)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidChangeStatusBarOrientationNotification:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

And add the method:

- (void)applicationDidChangeStatusBarOrientationNotification:(NSNotification *)notification
{
    // handling statusBar (iOS7)
    self.window.frame = [UIScreen mainScreen].applicationFrame;
}

You can also consider subclassing UIWindow to handle UIApplicationDidChangeStatusBarOrientationNotification itself.

Use formula in custom calculated field in Pivot Table

Some of it is possible, specifically accessing subtotals:

"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)

enter image description here

  • And make sure the field in question is a number field that can be summed, it does not work for text fields for which only count is normally informative.

Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/

Having the output of a console application in Visual Studio instead of the console

A simple solution that works for me, to work with console ability(ReadKey, String with Format and arg etc) and to see and save the output:

I write TextWriter that write to Console and to Trace and replace the Console.Out with it.

if you use Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window" you get it in the Immediate Window and pretty clean.

my code: in start of my code:

Console.SetOut(new TextHelper());

and the class:

public class TextHelper : TextWriter
{
    TextWriter console;

    public TextHelper() {
        console = Console.Out;
    }

    public override Encoding Encoding => this.console.Encoding;

    public override void WriteLine(string format, params object[] arg)
    {
        string s = string.Format(format, arg);
        WriteLine(s);
    }

    public override void Write(object value)
    {
        console.Write(value);
        System.Diagnostics.Trace.Write(value);
    }

    public override void WriteLine(object value)
    {
        Write(value);
        Write("\n");
    }

    public override void WriteLine(string value)
    {
        console.WriteLine(value);
        System.Diagnostics.Trace.WriteLine(value);
    }
}

Note: I override just what I needed so if you write other types you should override more

Change windows hostname from command line

The previously mentioned wmic command is the way to go, as it is installed by default in recent versions of Windows.

Here is my small improvement to generalize it, by retrieving the current name from the environment:

wmic computersystem where name="%COMPUTERNAME%" 
     call rename name="NEW-NAME"

NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.

XAMPP Apache won't start

It's simple if you guys have and use your skype ports turn them ports off from the skype settings->Connections and unmark the port like where it sez ports 80 till 443.

Problem Solved!!!

How to select all records from one table that do not exist in another table?

This is pure set theory which you can achieve with the minus operation.

select id, name from table1
minus
select id, name from table2

Ruby: How to post a file via HTTP as multipart/form-data?

there's also nick sieger's multipart-post to add to the long list of possible solutions.

Grep for beginning and end of line?

Many answers provided for this question. Just wanted to add one more which uses bashism-

#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"

@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).

How to get param from url in angular 4?

In angular, They separate it into 2 kind of url.

  1. URL pattern /heroes/:limit. Example: /heroes/20

    • You can get raw value by using route.snapshot.paramMap.get.
    • Subscribe from route.paramMap to get params
  2. URL pattern /heroes. Example: /heroes?limit=20

    • You can get raw value by using route.snapshot.queryParamMap

Reference: All you need to know about Angular parameters

How to visualize an XML schema?

Here is my approach- download the freemind and CAM XML Template Editor. Then open CAM XML, create new Template from XML, View -> View Template As Mind Map
Pros of this solution:

  • It works locally, so secret files can be processed,
  • totally free of charge,
  • open source.

Cons:

  • Quite unstable with large (more than 20sh MB) files.

Set keyboard caret position in html textbox

Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript

A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.

Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).

An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:

function addLoadEvent(func) {
    if(typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        if(func) {
            var oldLoad = window.onload;

            window.onload = function() {
                if(oldLoad)
                        oldLoad();

                func();
            }
        }
    }
}

// The setCaretPosition function belongs right here!

function setTextAreasOnFocus() {
/***
 * This function will force the keyboard caret to be positioned
 * at the end of all textareas when they receive focus.
 */
    var textAreas = document.getElementsByTagName('textarea');

    for(var i = 0; i < textAreas.length; i++) {
        textAreas[i].onfocus = function() {
            setCaretPosition(this.id, this.value.length);
        }
    }

    textAreas = null;
}

addLoadEvent(setTextAreasOnFocus);

Program "make" not found in PATH

Go to Project> Properties> C/C++ Build> Environment. You will see three fields, choose PATH. See if the folder containing make.exe is appended to the path or not. Sometimes the change to the System PATH variable (made from My Computer> Properties> Advanced System Settings...) is NOT reflected in Eclipse. This solved the problem for me, hope it helps you too!

Best way to add Gradle support to IntelliJ Project

  1. Add build.gradle in your project's root directory.

  2. Then just File -> Invalidate Caches / Restart

Here is a basic build.gradle for Java projects:

plugins {
    id 'java'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '1.2.1'

How can I move all the files from one folder to another using the command line?

You can use the command move

move <source directory> <destination directory>

Reference

Checking images for similarity with OpenCV

If for matching identical images ( same size/orientation )

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Source

Find full path of the Python interpreter?

Just noting a different way of questionable usefulness, using os.environ:

import os
python_executable_path = os.environ['_']

e.g.

$ python -c "import os; print(os.environ['_'])"
/usr/bin/python

How to set JAVA_HOME in Mac permanently?

Declare two export inside your .bashrc or .zshrc:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8) 
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)

Add alias for quick change:

alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'

set default to Java 11

java11

export PATH

export PATH=$JAVA_HOME/bin:$PATH

you could change java11 by java8 inside your .bashrc/zshrc file to change permanently your java version

How to remove duplicate white spaces in string using Java?

You can also try using String Tokeniser, for any space, tab, newline, and all. A simple way is,

String s = "Your Text Here";        
StringTokenizer st = new StringTokenizer( s, " " );
while(st.hasMoreTokens())
{
    System.out.print(st.nextToken());
}

Can you get the column names from a SqlDataReader?

Already mentioned. Just a LINQ answer:

var columns = reader.GetSchemaTable().Rows
                                     .Cast<DataRow>()
                                     .Select(r => (string)r["ColumnName"])
                                     .ToList();

//Or

var columns = Enumerable.Range(0, reader.FieldCount)
                        .Select(reader.GetName)
                        .ToList();

The second one is cleaner and much faster. Even if you cache GetSchemaTable in the first approach, the querying is going to be very slow.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How to make layout with View fill the remaining space?

If you use RelativeLayout, you can do it something like this:

<RelativeLayout
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent">
    <ImageView
        android:id = "@+id/my_image"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_alignParentTop ="true" />
    <RelativeLayout
        android:id="@+id/layout_bottom"
        android:layout_width="fill_parent"
        android:layout_height = "50dp"
        android:layout_alignParentBottom = "true">
        <Button
            android:id = "@+id/but_left"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&lt;"
            android:layout_alignParentLeft = "true"/>
        <TextView
            android:layout_width = "fill_parent"
            android:layout_height = "wrap_content"
            android:layout_toLeftOf = "@+id/but_right"
            android:layout_toRightOf = "@id/but_left" />
        <Button
            android:id = "@id/but_right"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&gt;"
            android:layout_alignParentRight = "true"/>
    </RelativeLayout>
</RelativeLayout>

Sending email with gmail smtp with codeigniter email library

Another option I have working, in a linux server with Postfix:

First, configure CI email to use your server's email system: eg, in email.php, for example

# alias to postfix in a typical Postfix server
$config['protocol'] = 'sendmail'; 
$config['mailpath'] = '/usr/sbin/sendmail'; 

Then configure your postfix to relay the mail to google (perhaps depending on the sender address). You'll probably need to put you user-password settings in /etc/postfix/sasl_passwd (docs)

This is much simpler (and less fragmente) if you have a linux box, already configured to send some/all of its outgoing emails to Google.

I can't install intel HAXM

I probably tried all the solutions mentioned above but all in vain. To summarize, I did:

  • I enable the virtualization going to BIOS setting.

enter image description here

  • Uncheck Hyper-V option by going to Turn Windows features on or off.

enter image description here

Nothing worked for me. What worked for me: I noticed the issue "unable to run mksdcard sdk tool" when I try to download SDK platform.So after some research, I found some SDK tools such as mksdcard.exe require Microsoft Visual C++ runtime 2015-2019. So based on my system type,(for me it was x64) I downloaded the latest Microsoft Visual C++ Redistributable for Visual Studio 2019 from the link https://visualstudio.microsoft.com/downloads/. Detailed answer given here: Android Studio install failed - unable to run mksdcard sdk tool in Windows

enter image description here

enter image description here

After downloading and installing Visual C++ ,the error "unable to run mksdcard sdk tool" was fixed, also when I try to install HAXM after this, it was install successfully. Everything was fine. I was also able to create AVD now(which was also a problem when HAXM was not install).

how to configure lombok in eclipse luna

Step 1: Create a maven project in Eclipse and add the below dependency in the pom.xml

<dependencies>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
</dependency>

Step 2: Run As --> Configuraitons --> Goto Arguments --> give arguments like below maven -clean install

enter image description here

Step 3: Run As --> maven clean

Once you do the maven clean you see Build Success and lombok jar file in the maven Dependencies

enter image description here

Step 4: Goto the jar location as shown in the below screen shot.

enter image description here

Step 5: Give command as shown like below after reaching in the .m2 folder

enter image description here

Step 6: Locate where is your eclipse folder once you this window.Once you see Install Successfull message click on Quit Installer option at the bottom.

enter image description here

Step 7 : We have finished installing the lombok.jar successfully .Now restart your Eclipse IDE and Start below Sample Code to check whether the data is coming or not in the getters and setters.

Step 8: Open Eclipse and create simple Java Maven project and see in the Outline section you can see getters and setters are created you can use either @Data or @Getter @Setter On top of class or you can give on top of variable

@Getter @Setter
privateString riverName;

{OR}

@Getter
@Setter
Class River{
String riverName;
}

[OR]

@Data
class River 
{
Private String riverName;

}

You can see the project structure and Outline Structure how it got created in simple steps.

enter image description here

How do I get an element to scroll into view, using jQuery?

Simplest solution I have seen

var offset = $("#target-element").offset();
$('html, body').animate({
    scrollTop: offset.top,
    scrollLeft: offset.left
}, 1000);

Tutorial Here

printf formatting (%d versus %u)

The difference is simple: they cause different warning messages to be emitted when compiling:

1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %d\n", &a); // prints "memory add=-12"
                               ^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %u\n", &a); // prints "memory add=65456"
                               ^

If you pass your pointer as a void* and use %p as the conversion specifier, then you get no error message:

#include <stdio.h>

int main()
{
    int a = 5;
    // check the memory address
    printf("memory address = %d\n", &a); /* wrong */
    printf("memory address = %u\n", &a); /* wrong */
    printf("memory address = %p\n", (void*)&a); /* right */
}

How to update record using Entity Framework Core?

After going through all the answers I thought i will add two simple options

  1. If you already accessed the record using FirstOrDefault() with tracking enabled (without using .AsNoTracking() function as it will disable tracking) and updated some fields then you can simply call context.SaveChanges()

  2. In other case either you have entity posted to server using HtppPost or you disabled tracking for some reason then you should call context.Update(entityName) before context.SaveChanges()

1st option will only update the fields you changed but 2nd option will update all the fields in the database even though none of the field values were actually updated :)

How do you push just a single Git branch (and no other branches)?

So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.

To push the contents of foo to origin/master, you first need to set its upstream:

git checkout foo
git branch -u origin/master

Then you can push to this branch using:

git push origin HEAD:master

In the last command you can add --force to replace the entire history of origin/master with that of foo.

How to change the default charset of a MySQL table?

If you want to change the table default character set and all character columns to a new character set, use a statement like this:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

So query will be:

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;

Postgres ERROR: could not open file for reading: Permission denied

COPY your table (Name, Latitude, Longitude) FROM 'C:\Temp\your file.csv' DELIMITERS ',' CSV HEADER;

Use c:\Temp\"Your File"\.

Docker container will automatically stop after "docker run -d"

Background

A Docker container runs a process (the "command" or "entrypoint") that keeps it alive. The container will continue to run as long as the command continues to run.

In your case, the command (/bin/bash, by default, on centos:latest) is exiting immediately (as bash does when it's not connected to a terminal and has nothing to run).

Normally, when you run a container in daemon mode (with -d), the container is running some sort of daemon process (like httpd). In this case, as long as the httpd daemon is running, the container will remain alive.

What you appear to be trying to do is to keep the container alive without a daemon process running inside the container. This is somewhat strange (because the container isn't doing anything useful until you interact with it, perhaps with docker exec), but there are certain cases where it might make sense to do something like this.

(Did you mean to get to a bash prompt inside the container? That's easy! docker run -it centos:latest)

Solution

A simple way to keep a container alive in daemon mode indefinitely is to run sleep infinity as the container's command. This does not rely doing strange things like allocating a TTY in daemon mode. Although it does rely on doing strange things like using sleep as your primary command.

$ docker run -d centos:latest sleep infinity
$ docker ps
CONTAINER ID  IMAGE         COMMAND          CREATED       STATUS       PORTS NAMES
d651c7a9e0ad  centos:latest "sleep infinity" 2 seconds ago Up 2 seconds       nervous_visvesvaraya

Alternative Solution

As indicated by cjsimon, the -t option allocates a "pseudo-tty". This tricks bash into continuing to run indefinitely because it thinks it is connected to an interactive TTY (even though you have no way to interact with that particular TTY if you don't pass -i). Anyway, this should do the trick too:

$ docker run -t -d centos:latest

Not 100% sure whether -t will produce other weird interactions; maybe leave a comment below if it does.

How to store(bitmap image) and retrieve image from sqlite database in android?

Setting Up the database

public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "database_name";

    // Table Names
    private static final String DB_TABLE = "table_image";

    // column names
    private static final String KEY_NAME = "image_name";
    private static final String KEY_IMAGE = "image_data";

    // Table create statement
    private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+ 
                       KEY_NAME + " TEXT," + 
                       KEY_IMAGE + " BLOB);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating table
        db.execSQL(CREATE_TABLE_IMAGE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);

        // create new table
        onCreate(db);
    }
}

Insert in the Database:

public void addEntry( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_NAME,    name);
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Retrieving data:

 byte[] image = cursor.getBlob(1);

Note:

  1. Before inserting into database, you need to convert your Bitmap image into byte array first then apply it using database query.
  2. When retrieving from database, you certainly have a byte array of image, what you need to do is to convert byte array back to original image. So, you have to make use of BitmapFactory to decode.

Below is an Utility class which I hope could help you:

public class DbBitmapUtility {

    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}


Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Is a URL allowed to contain a space?

URL can have an Space Character in them and they will be displayed as %20 in most of the browsers, but browser encoding rules change quite often and we cannot depend on how a browser will display the URL.

So Instead you can replace the Space Character in the URL with any character that you think shall make the URL More readable and ' Pretty ' ;) ..... O so general characters that are preferred are "-","_","+" .... but these aren't the compulsions so u can use any of the character that is not supposed to be in the URL Already.

Please avoid the %,&,},{,],[,/,>,< as the URL Space Character Replacement as they can pull up an error on certain browsers and Platforms.

As you can see the Stak overflow itself uses the '-' character as Space(%20) replacement.

Have an Happy questioning.

Most efficient conversion of ResultSet to JSON?

the other way , here I have used ArrayList and Map, so its not call json object row by row but after iteration of resultset finished :

 List<Map<String, String>> list = new ArrayList<Map<String, String>>();

  ResultSetMetaData rsMetaData = rs.getMetaData();  


      while(rs.next()){

              Map map = new HashMap();
              for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {
                 String key = rsMetaData.getColumnName(i);

                  String value = null;

               if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                           value = rs.getString(key);
               } else if(rsmd.getColumnType(i)==java.sql.Types.BIGINT)                         
                             value = rs.getLong(key);
               }                  


                    map.put(key, value);
              }
              list.add(map);


    }


     json.put(list);    

How to set the holo dark theme in a Android app?

According the android.com, you only need to set it in the AndroidManifest.xml file:

http://developer.android.com/guide/topics/ui/themes.html#ApplyATheme

Adding the theme attribute to your application element worked for me:

--AndroidManifest.xml--

...

<application ...

  android:theme="@android:style/Theme.Holo"/>
  ...

</application>

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Difference between "\n" and Environment.NewLine

Environment.NewLine will return the newline character for the corresponding platform in which your code is running

you will find this very useful when you deploy your code in linux on the Mono framework

Transmitting newline character "\n"

Try to replace the \n with %0A just like you have spaces replaced with %20.

How can I convert a DOM element to a jQuery element?

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.

How can I convert an integer to a hexadecimal string in C?

The following code takes an integer and makes a string out of it in hex format:

int  num = 32424;
char hex[5];

sprintf(hex, "%x", num);
puts(hex);

gives

7ea8

How do I give text or an image a transparent background using CSS?

Here's how I do this (it might not be optimal, but it works):

Create the div that you want to be semi-transparent. Give it a class/id. Leave it empty, and close it. Give it a set height and width (say, 300 pixels by 300 pixels). Give it an opacity of 0.5 or whatever you like, and a background color.

Then, directly below that div, create another div with a different class/id. Create a paragraph inside it, where you'll place your text. Give the div position: relative, and top: -295px (that's negative 295 pixels). Give it a z-index of 2 for good measure, and make sure its opacity is 1. Style your paragraph as you like, but make sure the dimensions are less than that of the first div so it doesn't overflow.

That's it. Here's the code:

_x000D_
_x000D_
.trans {_x000D_
  opacity: 0.5;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  background-color: orange;_x000D_
}_x000D_
.trans2 {_x000D_
  opacity: 1;_x000D_
  position: relative;_x000D_
  top: -295px;_x000D_
}_x000D_
.trans2 p {_x000D_
  width: 295px;_x000D_
  color: black;_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<body>_x000D_
  <div class="trans">_x000D_
  </div>_x000D_
  <div class="trans2">_x000D_
    <p>_x000D_
      text text text_x000D_
    </p>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

This works in Safari 2.x, but I don't know about Internet Explorer.

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).

How to avoid "Permission denied" when using pip with virtualenv

While creating virtualenv if you use sudo the directory is created with root privileges.So when you try to install a package with non-sudo user you won't have permission to install into it. So always create virtualenv without sudo and install without sudo.

You can also copy packages installed on global python to virtualenv.

cp -r /lib/python/site-packages/* virtualenv/lib/python/site-packages/

How can one use multi threading in PHP applications

Multi-threading is possible in php

Yes you can do multi-threading in PHP with pthreads

From the PHP documentation:

pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.

Warning: The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.

Simple Test

#!/usr/bin/php
<?php
class AsyncOperation extends Thread {

    public function __construct($arg) {
        $this->arg = $arg;
    }

    public function run() {
        if ($this->arg) {
            $sleep = mt_rand(1, 10);
            printf('%s: %s  -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep);
            sleep($sleep);
            printf('%s: %s  -finish' . "\n", date("g:i:sa"), $this->arg);
        }
    }
}

// Create a array
$stack = array();

//Initiate Multiple Thread
foreach ( range("A", "D") as $i ) {
    $stack[] = new AsyncOperation($i);
}

// Start The Threads
foreach ( $stack as $t ) {
    $t->start();
}

?>

First Run

12:00:06pm:     A  -start -sleeps 5
12:00:06pm:     B  -start -sleeps 3
12:00:06pm:     C  -start -sleeps 10
12:00:06pm:     D  -start -sleeps 2
12:00:08pm:     D  -finish
12:00:09pm:     B  -finish
12:00:11pm:     A  -finish
12:00:16pm:     C  -finish

Second Run

12:01:36pm:     A  -start -sleeps 6
12:01:36pm:     B  -start -sleeps 1
12:01:36pm:     C  -start -sleeps 2
12:01:36pm:     D  -start -sleeps 1
12:01:37pm:     B  -finish
12:01:37pm:     D  -finish
12:01:38pm:     C  -finish
12:01:42pm:     A  -finish

Real World Example

error_reporting(E_ALL);
class AsyncWebRequest extends Thread {
    public $url;
    public $data;

    public function __construct($url) {
        $this->url = $url;
    }

    public function run() {
        if (($url = $this->url)) {
            /*
             * If a large amount of data is being requested, you might want to
             * fsockopen and read using usleep in between reads
             */
            $this->data = file_get_contents($url);
        } else
            printf("Thread #%lu was not provided a URL\n", $this->getThreadId());
    }
}

$t = microtime(true);
$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));
/* starting synchronization */
if ($g->start()) {
    printf("Request took %f seconds to start ", microtime(true) - $t);
    while ( $g->isRunning() ) {
        echo ".";
        usleep(100);
    }
    if ($g->join()) {
        printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data));
    } else
        printf(" and %f seconds to finish, request failed\n", microtime(true) - $t);
}

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

There's a lot of manual solutions to this, but I wanted to reiterate and update Julie's answer above. Use google collections Joiner class.

Joiner.on(", ").join(34, 26, ..., 2)

It handles var args, iterables and arrays and properly handles separators of more than one char (unlike gimmel's answer). It will also handle null values in your list if you need it to.

Message 'src refspec master does not match any' when pushing commits in Git

I had a similar error. But Git tells me:

*** Please tell me who you are.

Run

git config --global user.email "[email protected]"
git config --global user.name "Your Name"

Or to set your account's default identity.

Omit --global to set the identity only in this repository.

Then the error goes away.

How to get label of select option with jQuery?

Try this:

$('select option:selected').text();

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

Numpy: Creating a complex array from 2 real ones?

This is what your are looking for:

from numpy import array

a=array([1,2,3])
b=array([4,5,6])

a + 1j*b

->array([ 1.+4.j,  2.+5.j,  3.+6.j])

PowerShell: Create Local User Account

Import-Csv C:\test.csv |
Foreach-Object {
  NET USER    $ _.username   $ _.password /ADD
  NET LOCALGROUP "group" $_.username  /ADD
}

edit csv as username,password and change "group" for your groupname

:) worked on 2012 R2

How can I add a .npmrc file?

This issue is because of you having some local or private packages. For accessing those packages you have to create .npmrc file for this issue. Just refer the following link for your solution. https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment

Install NuGet via PowerShell script

With PowerShell but without the need to create a script:

Invoke-WebRequest https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile Nuget.exe

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

Check if a number has a decimal place/is a whole number

Perhaps this works for you?

It uses regex to check if there is a comma in the number, and if there is not, then it will add the comma and stripe.

var myNumber = '50';
function addCommaStripe(text){
    if(/,/.test(text) == false){
        return text += ',-';
    } else {
        return text;
    }
}
myNumber = addCommaStripe(myNumber);

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

How to parse a date?

The problem is that you have a date formatted like this:

Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormat that is:

yyyy-MM-dd

The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

Vim: How to insert in visual block mode?

if you want to add new text before or after the selected colum:

  • press ctrl+v
  • select columns
  • press shift+i
  • write your text
  • press esc
  • press "jj"

What is a plain English explanation of "Big O" notation?

It shows how an algorithm scales based on input size.

O(n2): known as Quadratic complexity

  • 1 item: 1 operations
  • 10 items: 100 operations
  • 100 items: 10,000 operations

Notice that the number of items increases by a factor of 10, but the time increases by a factor of 102. Basically, n=10 and so O(n2) gives us the scaling factor n2 which is 102.

O(n): known as Linear complexity

  • 1 item: 1 second
  • 10 items: 10 seconds
  • 100 items: 100 seconds

This time the number of items increases by a factor of 10, and so does the time. n=10 and so O(n)'s scaling factor is 10.

O(1): known as Constant complexity

  • 1 item: 1 operations
  • 10 items: 1 operations
  • 100 items: 1 operations

The number of items is still increasing by a factor of 10, but the scaling factor of O(1) is always 1.

O(log n): known as Logarithmic complexity

  • 1 item: 1 operations
  • 10 items: 2 operations
  • 100 items: 3 operations
  • 1000 items: 4 operations
  • 10,000 items: 5 operations

The number of computations is only increased by a log of the input value. So in this case, assuming each computation takes 1 second, the log of the input n is the time required, hence log n.

That's the gist of it. They reduce the maths down so it might not be exactly n2 or whatever they say it is, but that'll be the dominating factor in the scaling.

How to destroy a JavaScript object?

While the existing answers have given solutions to solve the issue and the second half of the question, they do not provide an answer to the self discovery aspect of the first half of the question that is in bold:

"How can I see which variable causes memory overhead...?"

It may not have been as robust 3 years ago, but the Chrome Developer Tools "Profiles" section is now quite powerful and feature rich. The Chrome team has an insightful article on using it and thus also how garbage collection (GC) works in javascript, which is at the core of this question.

Since delete is basically the root of the currently accepted answer by Yochai Akoka, it's important to remember what delete does. It's irrelevant if not combined with the concepts of how GC works in the next two answers: if there's an existing reference to an object it's not cleaned up. The answers are more correct, but probably not as appreciated because they require more thought than just writing 'delete'. Yes, one possible solution may be to use delete, but it won't matter if there's another reference to the memory leak.

Another answer appropriately mentions circular references and the Chrome team documentation can provide much more clarity as well as the tools to verify the cause.

Since delete was mentioned here, it also may be useful to provide the resource Understanding Delete. Although it does not get into any of the actual solution which is really related to javascript's garbage collector.

The controller for path was not found or does not implement IController

In my case of legacy application, the issue occurred when I added below entry in web.config file under the node <system.webServer>

       <modules runAllManagedModulesForAllRequests="true"></modules>

When I removed it, the issue resolved.

Get string character by index - Java

You're pretty stuck with substring(), given your requirements. The standard way would be charAt(), but you said you won't accept a char data type.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

How to determine previous page URL in Angular?

You can use Location as mentioned here.

Here's my code if the link opened on new tab

navBack() {
    let cur_path = this.location.path();
    this.location.back();
    if (cur_path === this.location.path())
     this.router.navigate(['/default-route']);    
  }

Required imports

import { Router } from '@angular/router';
import { Location } from '@angular/common';

Force update of an Android app when a new version is available

Google introduced In-app updates lib, (https://developer.android.com/guide/app-bundle/in-app-updates) it works on Lollipop+ and gives you the ability to ask the user for an update with a nice dialog (FLEXIBLE) or with mandatory full-screen message (IMMEDIATE).

You need to implement the latter. Here is how it will look like: enter image description here

I covered all the code in this answer: https://stackoverflow.com/a/56808529/5502121

git replace local version with remote version

This is the safest solution:

git stash

Now you can do whatever you want without fear of conflicts.

For instance:

git checkout origin/master

If you want to include the remote changes in the master branch you can do:

git reset --hard origin/master

This will make you branch "master" to point to "origin/master".

PowerShell script to return members of multiple security groups

This is cleaner and will put in a csv.

Import-Module ActiveDirectory

$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)


$Table = @()

$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}



Foreach ($Group in $Groups)
{

$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname

foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}

}

$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

Java: Check the date format of current string is according to required format or not

For your case, you may use regex:

boolean checkFormat;

if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
    checkFormat=true;
else
   checkFormat=false;

For a larger scope or if you want a flexible solution, refer to MadProgrammer's answer.

Edit

Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable

Select rows of a matrix that meet a condition

If the dataset is called data, then all the rows meeting a condition where value of column 'pm2.5' > 300 can be received by -

data[data['pm2.5'] >300,]

UIView Hide/Show with animation

You can try this.

 func showView(objView:UIView){

    objView.alpha = 0.0
    UIView.animate(withDuration: 0.5, animations: {
        objView.alpha = 0.0
    }, completion: { (completeFadein: Bool) -> Void in
        objView.alpha = 1.0
        let transition = CATransition()
        transition.duration = 0.5
        transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        transition.type = kCATransitionFade
        objView.layer.add(transition, forKey: nil)
    })
}

func HideView(objView:UIView){

    UIView.animate(withDuration: 0.5, animations: {
        objView.alpha = 1.0
    }, completion: { (completeFadein: Bool) -> Void in
        objView.alpha = 0.0
        let transition = CATransition()
        transition.duration = 0.5
        transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        transition.type = kCATransitionFade
        objView.layer.add(transition, forKey: nil)
    })
}

And pass your view name

        showView(objView: self.viewSaveCard)
        HideView(objView: self.viewSaveCard)

MySQL "incorrect string value" error when save unicode string in Django

If you have this problem here's a python script to change all the columns of your mysql database automatically.

#! /usr/bin/env python
import MySQLdb

host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()

cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)

results = cursor.fetchall()
for row in results:
  sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
  cursor.execute(sql)
db.close()

How to create dictionary and add key–value pairs dynamically?

In modern javascript (ES6/ES2015), one should use Map data structure for dictionary. The Map data structure in ES6 lets you use arbitrary values as keys.

const map = new Map();
map.set("true", 1);
map.set("false", 0);

In you are still using ES5, the correct way to create dictionary is to create object without a prototype in the following way.

var map = Object.create(null);
map["true"]= 1;
map["false"]= 0;

There are many advantages of creating a dictionary without a prototype object. Below blogs are worth reading on this topic.

dict-pattern

objects-as-maps

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

Setting environment variables in Linux using Bash

The reason people often suggest writing

VAR=value
export VAR

instead of the shorter

export VAR=value

is that the longer form works in more different shells than the short form. If you know you're dealing with bash, either works fine, of course.

Adding an assets folder in Android Studio

An image of how to in Android Studio 1.5.1.

Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...

enter image description here

Adding timestamp to a filename with mv in BASH

A single line method within bash works like this.

[some out put] >$(date "+%Y.%m.%d-%H.%M.%S").ver

will create a file with a timestamp name with ver extension. A working file listing snap shot to a date stamp file name as follows can show it working.

find . -type f -exec ls -la {} \; | cut -d ' ' -f 6- >$(date "+%Y.%m.%d-%H.%M.%S").ver

Of course

cat somefile.log > $(date "+%Y.%m.%d-%H.%M.%S").ver

or even simpler

ls > $(date "+%Y.%m.%d-%H.%M.%S").ver

ImportError: No module named apiclient.discovery

For app engine project you gotta install the lib locally by typing

pip install -t lib google-api-python-client

read more here

Render basic HTML view?

app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});

CSS width of a <span> tag

Use the attribute 'display' as in the example:

<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>

How can I remove text within parentheses with a regex?

s/\([^)]*\)//

So in Python, you'd do:

re.sub(r'\([^)]*\)', '', filename)

Replace multiple whitespaces with single whitespace in JavaScript string

If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:

$j('#fragment_key').bind({
    keypress: function(e){
        var key = e.keyCode;
    var character = String.fromCharCode(key); 
    if(character.match( /[' ']/)) {
        alert("Blank space is not allowed in the Name");
        return false;
        }
    }
});
  • create a JQuery function .
  • this is key press event.
  • Initialize a variable.
  • Give condition to match the character
  • show a alert message for your matched condition.

Docker official registry (Docker Hub) URL

The registry path for official images (without a slash in the name) is library/<image>. Try this instead:

docker pull registry.hub.docker.com/library/busybox

Get Character value from KeyCode in JavaScript... then trim

You can also use the read-only property key. It also respects special keys like shift etc. and is supported by IE9.

When a non-printable or special character is pressed, the value will be on of the defined key values like 'Shift' or 'Multiply'.

  • Keyboard     event.key
  • X             -> 'x'
  • Shift+X -> 'X'
  • F5            -> 'F5'

Conditionally formatting cells if their value equals any value of another column

No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:

NOTE: remove any duplicates from the individual columns first!

  1. Select the columns to compare
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red

    • Bonus tip, you can filter each row by colour to either leave the unique values in the column, or leave just the duplicates.

enter image description here enter image description here

WPF chart controls

Sparrow Chart Toolkit a best opensource chart control for multiple platforms
-WPF
-Silverlight
-WinRT
-Windows phone
-Windows Forms
-Mono

https://sparrowtoolkit.codeplex.com/

How can I color Python logging output?

The bit I had trouble with was setting up the formatter properly:

class ColouredFormatter(logging.Formatter):    
    def __init__(self, msg):
        logging.Formatter.__init__(self, msg)
        self._init_colour = _get_colour()

    def close(self):
        # restore the colour information to what it was
        _set_colour(self._init_colour)

    def format(self, record):        
        # Add your own colourer based on the other examples
        _set_colour( LOG_LEVEL_COLOUR[record.levelno] )
        return logging.Formatter.format(self, record)         

def init():
    # Set up the formatter. Needs to be first thing done.
    rootLogger = logging.getLogger()
    hdlr = logging.StreamHandler()
    fmt = ColouredFormatter('%(message)s')
    hdlr.setFormatter(fmt)
    rootLogger.addHandler(hdlr)

And then to use:

import coloured_log
import logging

coloured_log.init()
logging.info("info")    
logging.debug("debug")    

coloured_log.close()    # restore colours

Populate a datagridview with sql query results

if you are using mysql this code you can use.

string con = "SERVER=localhost; user id=root; password=; database=databasename";
    private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

What is the right way to debug in iPython notebook?

I just discovered PixieDebugger. Even thought I have not yet had the time to test it, it really seems the most similar way to debug the way we're used in ipython with ipdb

enter image description here

It also has an "evaluate" tab

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

Why do this() and super() have to be the first statement in a constructor?

It makes sense that constructors complete their execution in order of derivation. Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must complete its execution first.

A simple demonstration:

class A {
    A() {
        System.out.println("Inside A's constructor.");
    }
}

class B extends A {
    B() {
        System.out.println("Inside B's constructor.");
    }
}

class C extends B {
    C() {
        System.out.println("Inside C's constructor.");
    }
}

class CallingCons {
    public static void main(String args[]) {
        C c = new C();
    }
}

The output from this program is:

Inside A's constructor
Inside B's constructor
Inside C's constructor

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

New lines (\r\n) are not working in email body

You need to use a <br> because your Content-Type is text/html.

It works without the Content-Type header because then your e-mail will be interpreted as plain text. If you really want to use \n you should use Content-Type: text/plain but then you'll lose any markup.

Also check out similar question here.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

if while In visual studio with IIS express working and when published failed try this:enter image description here

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

How to find all positions of the maximum value in a list?

Also a solution, which gives only the first appearance, can be achieved by using numpy:

>>> import numpy as np
>>> a_np = np.array(a)
>>> np.argmax(a_np)
9

how do I check in bash whether a file was created more than x time ago?

Creation time isn't stored.

What are stored are three timestamps (generally, they can be turned off on certain filesystems or by certain filesystem options):

  • Last access time
  • Last modification time
  • Last change time

a "Change" to the file is counted as permission changes, rename etc. While the modification is contents only.

Regex allow digits and a single dot

Try this

boxValue = boxValue.replace(/[^0-9\.]/g,"");

This Regular Expression will allow only digits and dots in the value of text box.

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

Evenly distributing n points on a sphere

Healpix solves a closely related problem (pixelating the sphere with equal area pixels):

http://healpix.sourceforge.net/

It's probably overkill, but maybe after looking at it you'll realize some of it's other nice properties are interesting to you. It's way more than just a function that outputs a point cloud.

I landed here trying to find it again; the name "healpix" doesn't exactly evoke spheres...

unexpected T_VARIABLE, expecting T_FUNCTION

put public, protected or private before the $connection.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

cursor.execute(sql,array)

Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)

Sorting options elements alphabetically using jQuery

Yes you can sort the options by its text and append it back to the select box.

 function NASort(a, b) {    
      if (a.innerHTML == 'NA') {
          return 1;   
      }
      else if (b.innerHTML == 'NA') {
          return -1;   
      }       
      return (a.innerHTML > b.innerHTML) ? 1 : -1;
  };

Fiddle: https://jsfiddle.net/vaishali_ravisankar/5zfohf6v/

How can I do a case insensitive string comparison?

You should use static String.Compare function like following

x => String.Compare (x.Username, (string)drUser["Username"],
                     StringComparison.OrdinalIgnoreCase) == 0

Shuffling a list of objects

random.shuffle should work. Here's an example, where the objects are lists:

from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)

# print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary

Note that shuffle works in place, and returns None.

How to split a string into a list?

If you want all the chars of a word/sentence in a list, do this:

print(list("word"))
#  ['w', 'o', 'r', 'd']


print(list("some sentence"))
#  ['s', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e']

Is there Selected Tab Changed Event in the standard WPF Tab Control

If you're using the MVVM pattern then it is inconvenient (and breaks the pattern) to use the event handler. Instead, you can bind each individual TabItem's Selector.IsSelected property to a dependency property in your viewmodel and then handle the PropertyChanged event handler. That way you know exactly which tab was selected/deselected based on the PropertyName and you have a special handler for each tab.

Example: MainView.xaml

<TabControl>
 <TabItem Header="My tab 1" Selector.IsSelected="{Binding IsMyTab1Selected}"> ... </TabItem>
 <TabItem Header="My tab 2" Selector.IsSelected="{Binding IsMyTab2Selected}"> ... </TabItem>
</TabControl>

Example: MainViewModel.cs

public bool IsMyTab1Selected {
 get { return (bool)GetValue(IsMyTab1SelectedProperty); }
 set { SetValue(IsMyTab1SelectedProperty, value); }
}
public static readonly DependencyProperty IsMyTab1SelectedProperty =
DependencyProperty.Register("IsMyTab1Selected", typeof(bool), typeof(MainViewModel), new PropertyMetadata(true, new PropertyChangedCallback(MyPropertyChanged)));

public bool IsMyTab2Selected {
 get { return (bool)GetValue(IsMyTab2SelectedProperty); }
 set { SetValue(IsMyTab2SelectedProperty, value); }
}
public static readonly DependencyProperty IsMyTab2SelectedProperty =
DependencyProperty.Register("IsMyTab2Selected", typeof(bool), typeof(MainViewModel), new PropertyMetadata(false, new PropertyChangedCallback(MyPropertyChanged)));

private void MyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
 if (e.Property.Name == "IsMyTab1Selected") {
  // stuff to do
 } else if (e.Property.Name == "IsMyTab2Selected") {
  // stuff to do
 }
}

If your MainViewModel is INotifyPropertyChanged rather than DependencyObject, then use this instead:

Example: MainViewModel.cs

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) {
 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public MainViewModel() {
 PropertyChanged += handlePropertyChanged;
}

public bool IsMyTab1Selected {
 get { return _IsMyTab1Selected ; }
 set {
  if (value != _IsMyTab1Selected ) {
   _IsMyTab1Selected = value;
   OnPropertyChanged("IsMyTab1Selected ");
  }
 }
}
private bool _IsMyTab1Selected = false;

public bool IsMyTab2Selected {
 get { return _IsMyTab2Selected ; }
 set {
  if (value != _IsMyTab2Selected ) {
   _IsMyTab2Selected = value;
   OnPropertyChanged("IsMyTab2Selected ");
  }
 }
}
private bool _IsMyTab2Selected = false;

private void handlePropertyChanged(object sender, PropertyChangedEventArgs e) {
 if (e.PropertyName == "IsMyTab1Selected") {
  // stuff to do
 } else if (e.PropertyName == "IsMyTab2Selected") {
  // stuff to do
 }
}

Delimiter must not be alphanumeric or backslash and preg_match

Please try with this

 $pattern = "/My name is '\(.*\)' and im fine/"; 

How do I set the selected item in a comboBox to match my string using C#?

Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.

How to get text from each cell of an HTML table?

$content = '';
    for($rowth=0; $rowth<=100; $rowth++){
        $content .= $selenium->getTable("tblReports.{$rowth}.0") . "\n";
        //$content .= $selenium->getTable("tblReports.{$rowth}.1") . "\n";
        $content .= $selenium->getTable("tblReports.{$rowth}.2") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.3") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.4") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.5") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.6") . "\n";

    }

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

SQL to generate a list of numbers from 1 to 100

Using Oracle's sub query factory clause: "WITH", you can select numbers from 1 to 100:

WITH t(n) AS (
  SELECT 1 from dual
  UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT * FROM t;

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

Visual Studio 2015 Update 3 Offline Installer (ISO)

The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:

  1. Download Web Installer from Microsoft Web Site
  2. Execute the Installer. NOTE: the installer is still a simple downloader for the real web-installer.
  3. After running the real web installer, Run Windows Task manager and find the real web installer path that is stored in your temp folder
  4. copy the real installer somewhere else. like C:\VS Community\
  5. Open Command Prompt and execute the installer that you copied to C:\VS Community\ with this argument: /Layout .
  6. Now installer will download the FULL offline installer to your selected folder!

Good Luck

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

What's the difference between Perl's backticks, system, and exec?

Let me quote the manuals first:

perldoc exec():

The exec function executes a system command and never returns-- use system instead of exec if you want it to return

perldoc system():

Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.

In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.

perldoc `String`:

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.


Alternatives:

In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.

Example:

use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

Finally, IPC::Run from the CPAN is also worth looking at…

ORA-01008: not all variables bound. They are bound

You have two references to the :lot_priprc binding variable -- while it should require you to only set the variable's value once and bind it in both places, I've had problems where this didn't work and had to treat each copy as a different variable. A pain, but it worked.

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

How can I align YouTube embedded video in the center in bootstrap

Using Bootstrap's built in .center-block class, which sets margin left and right to auto:

<iframe class="center-block" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>

Or using the built in .text-center class, which sets text-align: center:

<div class="text-center">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div>

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

I did it by passing the cookie through the HttpContext:

HttpContext localContext = new BasicHttpContext();

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

response = client.execute(httppost, localContext);

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

Download a file by jQuery.Ajax

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

_x000D_
_x000D_
fetch('https://jsonplaceholder.typicode.com/todos/1')_x000D_
  .then(resp => resp.blob())_x000D_
  .then(blob => {_x000D_
    const url = window.URL.createObjectURL(blob);_x000D_
    const a = document.createElement('a');_x000D_
    a.style.display = 'none';_x000D_
    a.href = url;_x000D_
    // the filename you want_x000D_
    a.download = 'todo-1.json';_x000D_
    document.body.appendChild(a);_x000D_
    a.click();_x000D_
    window.URL.revokeObjectURL(url);_x000D_
    alert('your file has downloaded!'); // or you know, something with better UX..._x000D_
  })_x000D_
  .catch(() => alert('oh no!'));
_x000D_
_x000D_
_x000D_

2012 Original jQuery/iframe/Cookie based approach

Bluish is completely right about this, you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs.

I created jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience. Take a look at my blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action. Here is the source

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

Depending on what browsers you need to support you may be able to use https://github.com/eligrey/FileSaver.js/ which allows more explicit control than the IFRAME method jQuery File Download uses.

Jquery button click() function is not working

You need to use the event delegation syntax of .on() here. Change:

$("#add").click(function() {

to

$("#buildyourform").on('click', '#add', function () {

jsFiddle example

If else on WHERE clause

IF is used to select the field, then the LIKE clause is placed after it:

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE IF(`email` != '', `email`, `email2`) LIKE  '%@domain.nl%'

Python read-only property

Just my two cents, Silas Ray is on the right track, however I felt like adding an example. ;-)

Python is a type-unsafe language and thus you'll always have to trust the users of your code to use the code like a reasonable (sensible) person.

Per PEP 8:

Use one leading underscore only for non-public methods and instance variables.

To have a 'read-only' property in a class you can make use of the @property decoration, you'll need to inherit from object when you do so to make use of the new-style classes.

Example:

>>> class A(object):
...     def __init__(self, a):
...         self._a = a
...
...     @property
...     def a(self):
...         return self._a
... 
>>> a = A('test')
>>> a.a
'test'
>>> a.a = 'pleh'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

Difference between decimal, float and double in .NET?

No one has mentioned that

In default settings, Floats (System.Single) and doubles (System.Double) will never use overflow checking while Decimal (System.Decimal) will always use overflow checking.

I mean

decimal myNumber = decimal.MaxValue;
myNumber += 1;

throws OverflowException.

But these do not:

float myNumber = float.MaxValue;
myNumber += 1;

&

double myNumber = double.MaxValue;
myNumber += 1;

How to redirect stdout to both file and console with scripting?

Here is a simple context manager that prints to the console and writes the same output to an file. It also writes any exceptions to the file.

import traceback
import sys

# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
    def __init__(self, filename):
        self.file = open(filename, 'w')
        self.stdout = sys.stdout

    def __enter__(self):
        sys.stdout = self

    def __exit__(self, exc_type, exc_value, tb):
        sys.stdout = self.stdout
        if exc_type is not None:
            self.file.write(traceback.format_exc())
        self.file.close()

    def write(self, data):
        self.file.write(data)
        self.stdout.write(data)

    def flush(self):
        self.file.flush()
        self.stdout.flush()

To use the context manager:

print("Print")
with Tee('test.txt'):
    print("Print+Write")
    raise Exception("Test")
print("Print")

Delete all files of specific type (extension) recursively down a directory using a batch file

I wrote a batch script a while ago that allows you to pick a file extension to delete. The script will look in the folder it is in and all subfolders for any file with that extension and delete it.

@ECHO OFF
CLS

SET found=0
ECHO Enter the file extension you want to delete...
SET /p ext="> "

IF EXIST *.%ext% (           rem Check if there are any in the current folder :)
  DEL *.%ext%
  SET found=1
)
FOR /D /R %%G IN ("*") DO (  rem Iterate through all subfolders
  IF EXIST %%G CD %%G
  IF EXIST *.%ext% (
    DEL *.%ext%
    SET found=1
  )
)

IF %found%==1 (
  ECHO.
  ECHO Deleted all .%ext% files.
  ECHO.
) ELSE (
  ECHO.
  ECHO There were no .%ext% files.
  ECHO Nothing has been deleted.
  ECHO.
)

PAUSE
EXIT

Hope this comes in useful to anyone who wants it :)

How to align text below an image in CSS?

You can use the HTML5 Caption feature.

Merging dictionaries in C#

The trivial solution would be:

using System.Collections.Generic;
...
public static Dictionary<TKey, TValue>
    Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)
{
    var result = new Dictionary<TKey, TValue>();
    foreach (var dict in dictionaries)
        foreach (var x in dict)
            result[x.Key] = x.Value;
    return result;
}

How do I change the number of open files limit in Linux?

You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit

Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.

set rlim_fd_max = 166384
set rlim_fd_cur = 8192

On OS X, this same data must be set in /etc/sysctl.conf.

kern.maxfilesperproc=166384
kern.maxfiles=8192

Under Linux, these settings are often in /etc/security/limits.conf.

There are two kinds of limits:

  • soft limits are simply the currently enforced limits
  • hard limits mark the maximum value which cannot be exceeded by setting a soft limit

Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.

There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.

Modifying local variable from inside lambda

You can wrap it up to workaround the compiler but please remember that side effects in lambdas are discouraged.

To quote the javadoc

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement A small number of stream operations, such as forEach() and peek(), can operate only via side-effects; these should be used with care

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

For tracking changes to a folder where the folder was moved, I started using:

git rev-list --all --pretty=oneline -- "*/foo/subfoo/*"

This isn't perfect as it will grab other folders with the same name, but if it is unique, then it seems to work.

How to detect the device orientation using CSS media queries?

@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}

@media all and (orientation:landscape) {
  /* Style adjustments for landscape mode goes here */
}

but it still looks like you have to experiment

Using true and false in C

Just include <stdbool.h> if your system provides it. That defines a number of macros, including bool, false, and true (defined to _Bool, 0, and 1 respectively). See section 7.16 of C99 for more details.

Html/PHP - Form - Input as array

HTML: Use names as

<input name="levels[level][]">
<input name="levels[build_time][]">

PHP:

$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
    foreach ($array[$fieldKey] as $key=>$value) {
        $newArray[$key][$fieldKey] = $value;
    }
}  

$newArray will hold data as you want

Array ( 
  [0] => Array ( [level] => 1 [build_time] => 123 ) 
  [1] => Array ( [level] => 2 [build_time] => 456 )
)

How to modify existing, unpushed commit messages?

Amending the most recent commit message

git commit --amend

will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with:

git commit --amend -m "New commit message"

…however, this can make multi-line commit messages or small corrections more cumbersome to enter.

Make sure you don't have any working copy changes staged before doing this or they will get committed too. (Unstaged changes will not get committed.)

Changing the message of a commit that you've already pushed to your remote branch

If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also need to force push the commit with:

git push <remote> <branch> --force
# Or
git push <remote> <branch> -f

Warning: force-pushing will overwrite the remote branch with the state of your local one. If there are commits on the remote branch that you don't have in your local branch, you will lose those commits.

Warning: be cautious about amending commits that you have already shared with other people. Amending commits essentially rewrites them to have different SHA IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether.


Perform an interactive rebase

Another option is to use interactive rebase. This allows you to edit any message you want to update even if it's not the latest message.

In order to do a Git squash, follow these steps:

// n is the number of commits up to the last commit you want to be able to edit
git rebase -i HEAD~n

Once you squash your commits - choose the e/r for editing the message:

Enter image description here

Important note about interactive rebase

When you use git rebase -i HEAD~n there can be more than n commits. Git will "collect" all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + .

Good tip:

If you have to do it for more than a single branch and you might face conflicts when amending the content, set up git rerere and let Git resolve those conflicts automatically for you.


Documentation

Convert list to dictionary using linq and not worrying about duplicates

In case we want all the Person (instead of only one Person) in the returning dictionary, we could:

var _people = personList
.GroupBy(p => p.FirstandLastName)
.ToDictionary(g => g.Key, g => g.Select(x=>x));

Android, How to read QR code in my application?

if user doesn't have any qr reader, what will happen to the application? if it crashes, may i ask user to download for example QrDroid and after that use it?

Interestingly, Google now introduced Mobile Vision APIs, they are integrated in play services itself.

In your Gradle file just add:

compile 'com.google.android.gms:play-services-vision:11.4.0'

Taken from this QR code tutorial.

UPDATE 2020:

Now QR code scanning is also a part of ML Kit, so you can bundle the model inside the app and use it by integrating the following gradle dependency:

dependencies {
  // ...
  // Use this dependency to bundle the model with your app
  implementation 'com.google.mlkit:barcode-scanning:16.0.3'
}

Or you can use the following gradle dependency to dynamically download the models from Google Play Services:

dependencies {
  // ...
  // Use this dependency to use the dynamically downloaded model in Google Play Services
  implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:16.1.2'
}

Taken from this link.

Removing element from array in component state

Here is a way to remove the element from the array in the state using ES6 spread syntax.

onRemovePerson: (index) => {
  const data = this.state.data;
  this.setState({ 
    data: [...data.slice(0,index), ...data.slice(index+1)]
  });
}

What is an HttpHandler in ASP.NET

Any Class that implements System.Web.IHttpHandler Interface becomes HttpHandler. And this class run as processes in response to a request made to the ASP.NET Site.

The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler(The Class that implements System.Web.IHttpHandler Interface).

You can create your own custom HTTP handlers that render custom output to the browser.

Some ASP.NET default handlers are:

  1. Page Handler (.aspx) – Handles Web pages
  2. User Control Handler (.ascx) – Handles Web user control pages
  3. Web Service Handler (.asmx) – Handles Web service pages
  4. Trace Handler (trace.axd) – Handles trace functionality

Permission denied when launch python script via bash

#strace ./scripts/replace-md5sums.py

$apply already in progress error

I know it's old question but if you really need use $scope.$applyAsync();

Are (non-void) self-closing tags valid in HTML5?

Self-closing tags are valid in HTML5, but not required.

<br> and <br /> are both fine.

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

How to parse date string to Date?

String target = "27-09-1991 20:29:30";
DateFormat df = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
Date result =  df.parse(target);
System.out.println(result); 

This works fine?

Is there any sed like utility for cmd.exe?

As far as I know nothing like sed is bundled with windows. However, sed is available for Windows in several different forms, including as part of Cygwin, if you want a full POSIX subsystem, or as a Win32 native executable if you want to run just sed on the command line.

Sed for Windows (GnuWin32 Project)

If it needs to be native to Windows then the only other thing I can suggest would be to use a scripting language supported by Windows without add-ons, such as VBScript.

Centering floating divs within another div

The following solution does not use inline blocks. However, it requires two helper divs:

  1. The content is floated
  2. The inner helper is floated (it stretches as much as the content)
  3. The inner helper is pushed right 50% (its left aligns with center of outer helper)
  4. The content is pulled left 50% (its center aligns with left of inner helper)
  5. The outer helper is set to hide the overflow

_x000D_
_x000D_
.ca-outer {_x000D_
  overflow: hidden;_x000D_
  background: #FFC;_x000D_
}_x000D_
.ca-inner {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: 50%;_x000D_
  background: #FDD;_x000D_
}_x000D_
.content {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: -50%;_x000D_
  background: #080;_x000D_
}_x000D_
/* examples */_x000D_
div.content > div {_x000D_
  float: left;_x000D_
  margin: 10px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #FFF;_x000D_
}_x000D_
ul.content {_x000D_
  padding: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
ul.content > li {_x000D_
  margin: 10px;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <div class="content">_x000D_
      <div>Box 1</div>_x000D_
      <div>Box 2</div>_x000D_
      <div>Box 3</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <ul class="content">_x000D_
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>_x000D_
      <li>Nullam efficitur nulla in libero consectetur dictum ac a sem.</li>_x000D_
      <li>Suspendisse iaculis risus ut dapibus cursus.</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Returning a value from thread?

My favorite class, runs any method on another thread with just 2 lines of code.

class ThreadedExecuter<T> where T : class
{
    public delegate void CallBackDelegate(T returnValue);
    public delegate T MethodDelegate();
    private CallBackDelegate callback;
    private MethodDelegate method;

    private Thread t;

    public ThreadedExecuter(MethodDelegate method, CallBackDelegate callback)
    {
        this.method = method;
        this.callback = callback;
        t = new Thread(this.Process);
    }
    public void Start()
    {
        t.Start();
    }
    public void Abort()
    {
        t.Abort();
        callback(null); //can be left out depending on your needs
    }
    private void Process()
    {
        T stuffReturned = method();
        callback(stuffReturned);
    }
}

usage

    void startthework()
    {
        ThreadedExecuter<string> executer = new ThreadedExecuter<string>(someLongFunction, longFunctionComplete);
        executer.Start();
    }
    string someLongFunction()
    {
        while(!workComplete)
            WorkWork();
        return resultOfWork;
    }
    void longFunctionComplete(string s)
    {
        PrintWorkComplete(s);
    }

Beware that longFunctionComplete will NOT execute on the same thread as starthework.

For methods that take parameters you can always use closures, or expand the class.

How to get a substring of text?

Use String#slice, also aliased as [].

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[6..-1]               #=> "there"
a[6..]                 #=> "there" (requires Ruby 2.6+)
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil

How to convert std::string to lower case?

An alternative to Boost is POCO (pocoproject.org).

POCO provides two variants:

  1. The first variant makes a copy without altering the original string.
  2. The second variant changes the original string in place.
    "In Place" versions always have "InPlace" in the name.

Both versions are demonstrated below:

#include "Poco/String.h"
using namespace Poco;

std::string hello("Stack Overflow!");

// Copies "STACK OVERFLOW!" into 'newString' without altering 'hello.'
std::string newString(toUpper(hello));

// Changes newString in-place to read "stack overflow!"
toLowerInPlace(newString);

How to edit nginx.conf to increase file size upload

Add client_max_body_size

Now that you are editing the file you need to add the line into the server block, like so;

server {
    client_max_body_size 8M;

    //other lines...
}

If you are hosting multiple sites add it to the http context like so;

http {
    client_max_body_size 8M;

    //other lines...
}

And also update the upload_max_filesize in your php.ini file so that you can upload files of the same size.

Saving in Vi

Once you are done you need to save, this can be done in vi with pressing esc key and typing :wq and returning.

Restarting Nginx and PHP

Now you need to restart nginx and php to reload the configs. This can be done using the following commands;

sudo service nginx restart
sudo service php5-fpm restart

Or whatever your php service is called.

Posting form to different MVC post action depending on the clicked submit button

BEST ANSWER 1:

ActionNameSelectorAttribute mentioned in

  1. How do you handle multiple submit buttons in ASP.NET MVC Framework?

  2. ASP.Net MVC 4 Form with 2 submit buttons/actions

http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx

ANSWER 2

Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor

Second Approach

Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.

Third Approach: Client Script

<button name="ClientCancel" type="button" 
    onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" 
style="display:none;"></a>

How to print matched regex pattern using awk?

Off topic, this can be done using the grep also, just posting it here in case if anyone is looking for grep solution

echo 'xxx yyy zzze ' | grep -oE 'yyy'

Getting full URL of action in ASP.NET MVC

This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.

UPDATE: The way to get url formed outside of the page itself is well described in answers above.

Or you could do a oneliner like following:

new UrlHelper(actionExecutingContext.RequestContext).Action(
    "SessionTimeout", "Home", 
    new {area = string.Empty}, 
    actionExecutingContext.Request.Url!= null? 
    actionExecutingContext.Request.Url.Scheme : "http"
);

from filter or:

new UrlHelper(this.Request.RequestContext).Action(
    "Details", 
    "Journey", 
    new { area = productType }, 
    this.Request.Url!= null? this.Request.Url.Scheme : "http"
);

However quite often one needs to get the url of current page, for those cases using Html.Action and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.

One way is to use JavaScript to get URL is window.location.href another - document.URL

Permissions error when connecting to EC2 via SSH on Mac OSx

If you have a PPK file working on a PC, then export it as OpenSSH file using puttygen.exe for PC and use that on Mac (any Unix machine).

I was getting the same error --

debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: Next authentication method: publickey
debug1: Trying private key: ec2-keypair
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-with-mic)

As I was using a PPK file on Windows, I followed the steps as described above and Bingo!

$ ssh -i ec2-openssh-key root@ec2-instance-ip

how to check if a form is valid programmatically using jQuery Validation Plugin

iContribute: It's never too late for a right answer.

var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
  form.submit();
}else{
  console.log("Required field missing.");
}

This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

How can I create an Asynchronous function in Javascript?

Edit: I totally misunderstood the question. In the browser, I would use setTimeout. If it was important that it ran in another thread, I would use Web Workers.

Best way to do nested case statement logic in SQL Server

I personally do it this way, keeping the embedded CASE expressions confined. I'd also put comments in to explain what is going on. If it is too complex, break it out into function.

SELECT
    col1,
    col2,
    col3,
    CASE WHEN condition THEN
      CASE WHEN condition1 THEN
        CASE WHEN condition2 THEN calculation1
        ELSE calculation2 END
      ELSE
        CASE WHEN condition2 THEN calculation3
        ELSE calculation4 END
      END
    ELSE CASE WHEN condition1 THEN 
      CASE WHEN condition2 THEN calculation5
      ELSE calculation6 END
    ELSE CASE WHEN condition2 THEN calculation7
         ELSE calculation8 END
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table

How to directly initialize a HashMap (in a literal way)?

If you need to place only one key-value pair, you can use Collections.singletonMap(key, value);

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

sorting and paging with gridview asp.net

Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.

The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.

There are other methods, too, such as persisting user profiles.

I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx

To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

typeof !== "undefined" vs. != null

_x000D_
_x000D_
var bar = null;_x000D_
console.log(typeof bar === "object"); //true yes _x000D_
//because null a datatype of object_x000D_
_x000D_
var barf = "dff";_x000D_
console.log(typeof barf.constructor);//function_x000D_
_x000D_
_x000D_
console.log(Array.isArray(bar));//falsss_x000D_
_x000D_
_x000D_
console.log((bar !== null) && (bar.constructor === Object)); //false_x000D_
_x000D_
console.log((bar !== null) && (typeof bar === "object"));  // logs false_x000D_
//because bar!==null, bar is a object_x000D_
_x000D_
_x000D_
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function"))); //false_x000D_
_x000D_
console.log(typeof bar === typeof object); //false_x000D_
console.log(typeof bar2 === typeof undefined); //true_x000D_
console.log(typeof bar3 === typeof undefinedff); //true_x000D_
console.log(typeof bar2 == typeof undefined); //true_x000D_
_x000D_
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]")); //false
_x000D_
_x000D_
_x000D_

Adding an external directory to Tomcat classpath

Just specify it in shared.loader or common.loader property of /conf/catalina.properties.

subtract time from date - moment js

Moment.subtract does not support an argument of type Moment - documentation:

moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);

The simplest solution is to specify the time delta as an object:

// Assumes string is hh:mm:ss
var myString = "03:15:00",
    myStringParts = myString.split(':'),
    hourDelta: +myStringParts[0],
    minuteDelta: +myStringParts[1];


date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"

Create a hidden field in JavaScript

var input = document.createElement("input");

input.setAttribute("type", "hidden");

input.setAttribute("name", "name_you_want");

input.setAttribute("value", "value_you_want");

//append to form element that you want .
document.getElementById("chells").appendChild(input);

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

How to start MySQL with --skip-grant-tables?

On the Linux system you can do following (Should be similar for other OS)

Check if mysql process is running:

sudo service mysql status

If runnning then stop the process: (Make sure you close all mysql tool)

sudo service mysql stop

If you have issue stopping then do following

Search for process: ps aux | grep mysqld Kill the process: kill -9 process_id

Now start mysql in safe mode with skip grant

sudo mysqld_safe --skip-grant-tables &

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

PHP Error: Cannot use object of type stdClass as array (array and object issues)

$blog is an object not an array

try using $blog->id instead of $blog['id']

Comparing two vectors in an if statement

Are they identical?

> identical(A,C)
[1] FALSE

Which elements disagree:

> which(A != C)
[1] 2 4

How do I change a single value in a data.frame?

In RStudio you can write directly in a cell. Suppose your data.frame is called myDataFrame and the row and column are called columnName and rowName. Then the code would look like:

myDataFrame["rowName", "columnName"] <- value

Hope that helps!