Programs & Examples On #Format specifiers

format-specifiers refer to the syntax of the format string parameter of the *printf functions in C/C++, allowing special formatting of arguments.

Format specifier %02x

You are actually getting the correct value out.

The way your x86 (compatible) processor stores data like this, is in Little Endian order, meaning that, the MSB is last in your output.

So, given your output:

10101010

the last two hex values 10 are the Most Significant Byte (2 hex digits = 1 byte = 8 bits (for (possibly unnecessary) clarification).

So, by reversing the memory storage order of the bytes, your value is actually: 01010101.

Hope that clears it up!

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

These are identical for printf but different for scanf. For printf, both %d and %i designate a signed decimal integer. For scanf, %d and %i also means a signed integer but %i inteprets the input as a hexadecimal number if preceded by 0x and octal if preceded by 0 and otherwise interprets the input as decimal.

Correct format specifier for double in printf

Given the C99 standard (namely, the N1256 draft), the rules depend on the function kind: fprintf (printf, sprintf, ...) or scanf.

Here are relevant parts extracted:

Foreword

This second edition cancels and replaces the first edition, ISO/IEC 9899:1990, as amended and corrected by ISO/IEC 9899/COR1:1994, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996. Major changes from the previous edition include:

  • %lf conversion specifier allowed in printf

7.19.6.1 The fprintf function

7 The length modifiers and their meanings are:

l (ell) Specifies that (...) has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.

The same rules specified for fprintf apply for printf, sprintf and similar functions.

7.19.6.2 The fscanf function

11 The length modifiers and their meanings are:

l (ell) Specifies that (...) that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double;

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.

12 The conversion specifiers and their meanings are: a,e,f,g Matches an optionally signed floating-point number, (...)

14 The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

The long story short, for fprintf the following specifiers and corresponding types are specified:

  • %f -> double
  • %Lf -> long double.

and for fscanf it is:

  • %f -> float
  • %lf -> double
  • %Lf -> long double.

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

Hex:

printf("64bit: %llp", 0xffffffffffffffff);

Output:

64bit: FFFFFFFFFFFFFFFF

How to printf "unsigned long" in C?

The format is %lu.

Please check about the various other datatypes and their usage in printf here

How should I print types like off_t and size_t?

You can use z for size_t and t for ptrdiff_t like in

printf("%zu %td", size, ptrdiff);

But my manpage says some older library used a different character than z and discourages use of it. Nevertheless, it's standardized (by the C99 standard). For those intmax_t and int8_t of stdint.h and so on, there are macros you can use, like another answer said:

printf("value: %" PRId32, some_int32_t);
printf("value: %" PRIu16, some_uint16_t);

They are listed in the manpage of inttypes.h.

Personally, I would just cast the values to unsigned long or long like another answer recommends. If you use C99, then you can (and should, of course) cast to unsigned long long or long long and use the %llu or %lld formats respectively.

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

I know this is an older post but one thing to watch out for when you cannot change the security is to make sure that your username and password are set.

I had a service with authenticationMode as UserNameOverTransport, when the username and password were not set for the service client I would get this error.

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

How do you list all triggers in a MySQL database?

I hope following code will give you more information.

select * from information_schema.triggers where 
information_schema.triggers.trigger_schema like '%your_db_name%'

This will give you total 22 Columns in MySQL version: 5.5.27 and Above

TRIGGER_CATALOG 
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA 
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED 
SQL_MODE
DEFINER 
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION

Angular 2 'component' is not a known element

This question may seem old and odd, but when I was trying to load a module(lazy loading) and getting the same error, I realized I was missing an exports clause for the component that shipped as a part of a larger module.

This Angular.io Link explains why: Components/Services inside a module, remains private(or protected) by default. To make them public, you have to export them.

Expanding on @Robin Djikof's answer with @live-love code sample, this is what was technically missing in my case(Angular 8):

@NgModule({
  declarations: [
    SomeOtherComponent,
    ProductListComponent
  ],
  imports: [
    DependantModule
  ],
  exports: [ProductListComponent] 
  //<- This line makes ProductListComponent available outside the module, 
  //while keeping SomeOtherComponent private to the module
})
export class SomeLargeModule { }

How to fast get Hardware-ID in C#?

I got here looking for the same thing and I found another solution. If you guys are interested I share this class:

using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
    /// <summary>
    /// Generates a 16 byte Unique Identification code of a computer
    /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
    /// </summary>
    public class FingerPrint  
    {
        private static string fingerPrint = string.Empty;
        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " + 
            biosId() + "\nBASE >> " + baseId() +
                            //"\nDISK >> "+ diskId() + "\nVIDEO >> " + 
            videoId() +"\nMAC >> "+ macId()
                                     );
            }
            return fingerPrint;
        }
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier
        (string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
        private static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
        //BIOS Identifier
        private static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
        //Main physical hard drive ID
        private static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
        //Motherboard ID
        private static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
        //Primary video controller ID
        private static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
        //First enabled network card ID
        private static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration", 
                "MACAddress", "IPEnabled");
        }
        #endregion
    }
}

I won't take any credit for this because I found it here It worked faster than I expected for me. Without the graphic card, mac and drive id's I got the unique ID in about 2-3 seconds. With those above included I got it in about 4-5 seconds.

Note: Add reference to System.Management.

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

Variable used in lambda expression should be final or effectively final

Java 8 has a new concept called “Effectively final” variable. It means that a non-final local variable whose value never changes after initialization is called “Effectively Final”.

This concept was introduced because prior to Java 8, we could not use a non-final local variable in an anonymous class. If you wanna have access to a local variable in anonymous class, you have to make it final.

When lambda was introduced, this restriction was eased. Hence to the need to make local variable final if it’s not changed once it is initialized as lambda in itself is nothing but an anonymous class.

Java 8 realized the pain of declaring local variable final every time a developer used lambda, introduced this concept, and made it unnecessary to make local variables final. So if you see the rule for anonymous classes has not changed, it’s just you don’t have to write the final keyword every time when using lambdas.

I found a good explanation here

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

Add line break within tooltips

Use

&#013

There shouldn't be any ; character.

Convert array to JSON string in swift

As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.

As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.

Instead just do the array->data->string parts:

Swift 3/4

let array = [ "one", "two" ]

func json(from object:Any) -> String? {
    guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
        return nil
    }
    return String(data: data, encoding: String.Encoding.utf8)
}

print("\(json(from:array as Any))")

Original Answer

let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

although you should probably not use forced unwrapping, it gives you the right starting point.

Remove final character from string

Simple:

st =  "abcdefghij"
st = st[:-1]

There is also another way that shows how it is done with steps:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

This is also a way with user input:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

To make it take away the last word in a list:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

Extract text from a string

Just to add a non-regex solution:

'(' + $myString.Split('()')[1] + ')'

This splits the string at the parentheses and takes the string from the array with the program name in it.

If you don't need the parentheses, just use:

$myString.Split('()')[1]

Reading specific XML elements from XML file

This is how I would do it (the code below has been tested, full source provided below), begin by creating a class with common properties

    class Word
    {
        public string Base { get; set; }
        public string Category { get; set; }
        public string Id { get; set; }
    }

load using XDocument with INPUT_DATA for demonstration purposes and find element name with lexicon . . .

    XDocument doc = XDocument.Parse(INPUT_DATA);
    XElement lex = doc.Element("lexicon");

make sure there is a value and use linq to extract the word elements from it . . .

    Word[] catWords = null;
    if (lex != null)
    {
        IEnumerable<XElement> words = lex.Elements("word");
        catWords = (from itm in words
                    where itm.Element("category") != null
                        && itm.Element("category").Value == "verb"
                        && itm.Element("id") != null
                        && itm.Element("base") != null
                    select new Word() 
                    {
                        Base = itm.Element("base").Value,
                        Category = itm.Element("category").Value,
                        Id = itm.Element("id").Value,
                    }).ToArray<Word>();
    }

The where statement checks if the category element exists and that the category value is not null and then check it again that it is a verb. Then check that the other nodes also exists . . .

The linq query will return an IEnumerable< Typename > object, so we can call ToArray< Typename >() to cast the entire collection into the type we want.

Then print it to get . . .

[Found]
 Id: E0006429
 Base: abandon
 Category: verb

[Found]
 Id: E0006524
 Base: abolish
 Category: verb

Full Source:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace test
{
    class Program
    {

        class Word
        {
            public string Base { get; set; }
            public string Category { get; set; }
            public string Id { get; set; }
        }

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse(INPUT_DATA);
            XElement lex = doc.Element("lexicon");
            Word[] catWords = null;
            if (lex != null)
            {
                IEnumerable<XElement> words = lex.Elements("word");
                catWords = (from itm in words
                            where itm.Element("category") != null
                                && itm.Element("category").Value == "verb"
                                && itm.Element("id") != null
                                && itm.Element("base") != null
                            select new Word() 
                            {
                                Base = itm.Element("base").Value,
                                Category = itm.Element("category").Value,
                                Id = itm.Element("id").Value,
                            }).ToArray<Word>();
            }

            //print it
            if (catWords != null)
            {
                Console.WriteLine("Words with <category> and value verb:\n");
                foreach (Word itm in catWords)
                    Console.WriteLine("[Found]\n Id: {0}\n Base: {1}\n Category: {2}\n", 
                        itm.Id, itm.Base, itm.Category);
            }
        }

        const string INPUT_DATA =
        @"<?xml version=""1.0""?>
        <lexicon>
        <word>
          <base>a</base>
          <category>determiner</category>
          <id>E0006419</id>
        </word>
        <word>
          <base>abandon</base>
          <category>verb</category>
          <id>E0006429</id>
          <ditransitive/>
          <transitive/>
        </word>
        <word>
          <base>abbey</base>
          <category>noun</category>
          <id>E0203496</id>
        </word>
        <word>
          <base>ability</base>
          <category>noun</category>
          <id>E0006490</id>
        </word>
        <word>
          <base>able</base>
          <category>adjective</category>
          <id>E0006510</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abnormal</base>
          <category>adjective</category>
          <id>E0006517</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abolish</base>
          <category>verb</category>
          <id>E0006524</id>
          <transitive/>
        </word>
        </lexicon>";

    }
}

Capture Image from Camera and Display in Activity

In Activity:

@Override
    protected void onCreate(Bundle savedInstanceState) {
                 image = (ImageView) findViewById(R.id.imageButton);
        image.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                SimpleDateFormat sdfPic = new SimpleDateFormat(DATE_FORMAT);
                currentDateandTime = sdfPic.format(new Date()).replace(" ", "");
                File imagesFolder = new File(IMAGE_PATH, currentDateandTime);
                imagesFolder.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = IMAGE_NAME + n + IMAGE_FORMAT;
                File file = new File(imagesFolder, fname);
                outputFileUri = Uri.fromFile(file);
                cameraIntent= new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                                startActivityForResult(cameraIntent, CAMERA_DATA);
                }catch(Exception e) {
                    e.printStackTrace();
                }

            }
        });
           @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
        case CAMERA_DATA :
                final int IMAGE_MAX_SIZE = 300;
                try {
                    // Bitmap bitmap;
                    File file = null;
                    FileInputStream fis;
                    BitmapFactory.Options opts;
                    int resizeScale;
                    Bitmap bmp;
                    file = new File(outputFileUri.getPath());
                    // This bit determines only the width/height of the
                    // bitmap
                    // without loading the contents
                    opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    fis = new FileInputStream(file);
                    BitmapFactory.decodeStream(fis, null, opts);
                    fis.close();

                    // Find the correct scale value. It should be a power of
                    // 2
                    resizeScale = 1;

                    if (opts.outHeight > IMAGE_MAX_SIZE
                            || opts.outWidth > IMAGE_MAX_SIZE) {
                        resizeScale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE/ (double) Math.max(opts.outHeight, opts.outWidth)) / Math.log(0.5)));
                    }

                    // Load pre-scaled bitmap
                    opts = new BitmapFactory.Options();
                    opts.inSampleSize = resizeScale;
                    fis = new FileInputStream(file);
                    bmp = BitmapFactory.decodeStream(fis, null, opts);
                    Bitmap getBitmapSize = BitmapFactory.decodeResource(
                            getResources(), R.drawable.male);
                    image.setLayoutParams(new RelativeLayout.LayoutParams(
                            200,200));//(width,height);
                    image.setImageBitmap(bmp);
                    image.setRotation(90);
                    fis.close();

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
                    imageByte = baos.toByteArray();
                    break;
                } catch (FileNotFoundException e) {

                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

in layout.xml:

enter code here
<RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">


        <ImageView
            android:id="@+id/imageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

                            android:src="@drawable/XXXXXXX"
            android:textAppearance="?android:attr/textAppearanceSmall" />

in manifest.xml:

    <uses-permission android:name="android.permission.CAMERA" />   <uses-feature android:name="android.hardware.camera" />

Add params to given URL in Python

I liked Lukasz version, but since urllib and urllparse functions are somewhat awkward to use in this case, I think it's more straightforward to do something like this:

params = urllib.urlencode(params)

if urlparse.urlparse(url)[4]:
    print url + '&' + params
else:
    print url + '?' + params

psql: FATAL: Peer authentication failed for user "dev"

When you specify:

psql -U user

it connects via UNIX Socket, which by default uses peer authentication, unless specified in pg_hba.conf otherwise.

You can specify:

host    database             user             127.0.0.1/32       md5
host    database             user             ::1/128            md5

to get TCP/IP connection on loopback interface (both IPv4 and IPv6) for specified database and user.

After changes you have to restart postgres or reload it's configuration. Restart that should work in modern RHEL/Debian based distros:

service postgresql restart

Reload should work in following way:

pg_ctl reload

but the command may differ depending of PATH configuration - you may have to specify absolute path, which may be different, depending on way the postgres was installed.

Then you can use:

psql -h localhost -U user -d database

to login with that user to specified database over TCP/IP. md5 stands for encrypted password, while you can also specify password for plain text passwords during authorisation. These 2 options shouldn't be of a great matter as long as database server is only locally accessible, with no network access.

Important note: Definition order in pg_hba.conf matters - rules are read from top to bottom, like iptables, so you probably want to add proposed rules above the rule:

host    all             all             127.0.0.1/32            ident

For a boolean field, what is the naming convention for its getter/setter?

It should just be get{varname} like every other getter. Changing it to "is" doesn't stop bad variable names, it just makes another unnecessary rule.

Consider program generated code, or reflection derivations.

It's a non-useful convention that should be dropped at the first available opportunity.

Adding elements to an xml file in C#

You're close, but you want name to be an XAttribute rather than XElement:

 XDocument doc = XDocument.Load(spath); 
 XElement root = new XElement("Snippet"); 
 root.Add(new XAttribute("name", "name goes here")); 
 root.Add(new XElement("SnippetCode", "SnippetCode")); 
 doc.Element("Snippets").Add(root); 
 doc.Save(spath); 

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

You can clone https://github.com/brock/node-reinstall and run the simple command as given in the repository.After that just restart your system.
This is the simplest method and also worked for me.

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

How to create a DataTable in C# and how to add rows?

You can write one liner using DataRow.Add(params object[] values) instead of four lines.

dt.Rows.Add("Ravi", "500");

As you create new DataTable object, there seems no need to Clear DataTable in very next statement. You can also use DataTable.Columns.AddRange to add columns with on statement. Complete code would be.

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });     
dt.Rows.Add("Ravi", "500");

Does an HTTP Status code of 0 have any meaning?

Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.

Separating class code into a header and cpp file

In general your .h contains the class defition, which is all your data and all your method declarations. Like this in your case:

A2DD.h:

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y);    
  int getSum();
};

And then your .cpp contains the implementations of the methods like this:

A2DD.cpp:

A2DD::A2DD(int x,int y)
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}

Is Fortran easier to optimize than C for heavy calculations?

I compare speed of Fortran, C, and C++ with the classic Levine-Callahan-Dongarra benchmark from netlib. The multiple language version, with OpenMP, is http://sites.google.com/site/tprincesite/levine-callahan-dongarra-vectors The C is uglier, as it began with automatic translation, plus insertion of restrict and pragmas for certain compilers. C++ is just C with STL templates where applicable. To my view, the STL is a mixed bag as to whether it improves maintainability.

There is only minimal exercise of automatic function in-lining to see to what extent it improves optimization, since the examples are based on traditional Fortran practice where little reliance is place on in-lining.

The C/C++ compiler which has by far the most widespread usage lacks auto-vectorization, on which these benchmarks rely heavily.

Re the post which came just before this: there are a couple of examples where parentheses are used in Fortran to dictate the faster or more accurate order of evaluation. Known C compilers don't have options to observe the parentheses without disabling more important optimizations.

CKEditor, Image Upload (filebrowserUploadUrl)

New CKeditor doesn't have file manager included (CKFinder is payable). You can integrate free filemanager that is good looking and easy to implement in CKeditor.

http://labs.corefive.com/2009/10/30/an-open-file-manager-for-ckeditor-3-0/

You dowload it, copy it to your project. All instructions are there but you basically just put path to added filemanager index.html page in your code.

CKEDITOR.replace( 'meeting_notes',
{
startupFocus : true,
toolbar :
[
['ajaxsave'],
['Bold', 'Italic', 'Underline', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
['Cut','Copy','Paste','PasteText'],
['Undo','Redo','-','RemoveFormat'],
['TextColor','BGColor'],
['Maximize', 'Image']
],
filebrowserUploadUrl : '/filemanager/index.html' // you must write path to filemanager where you have copied it.
});    

Most languages are supported (php, asp, MVC && aspx - ashx,...)).

Increase permgen space

You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.

External resource not being loaded by AngularJs

If anybody is looking for a TypeScript solution:

.ts file (change variables where applicable):

module App.Filters {

    export class trustedResource {

        static $inject:string[] = ['$sce'];

        static filter($sce:ng.ISCEService) {
            return (value) => {
                return $sce.trustAsResourceUrl(value)
            };
        }
    }
}
filters.filter('trustedResource', App.Filters.trusted.filter);

Html:

<video controls ng-if="HeaderVideoUrl != null">
  <source ng-src="{{HeaderVideoUrl | trustedResource}}" type="video/mp4"/>
</video>

LDAP Authentication using Java

Following Code authenticates from LDAP using pure Java JNDI. The Principle is:-

  1. First Lookup the user using a admin or DN user.
  2. The user object needs to be passed to LDAP again with the user credential
  3. No Exception means - Authenticated Successfully. Else Authentication Failed.

Code Snippet

public static boolean authenticateJndi(String username, String password) throws Exception{
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
    props.put(Context.SECURITY_PRINCIPAL, "uid=adminuser,ou=special users,o=xx.com");//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, "adminpassword");//dn user password


    InitialDirContext context = new InitialDirContext(props);

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
    javax.naming.directory.SearchResult result = answers.nextElement();

    String user = result.getNameInNamespace();

    try {
        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

   context = new InitialDirContext(props);
    } catch (Exception e) {
        return false;
    }
    return true;
}

Getting the WordPress Post ID of current post

Try:

$post = $wp_query->post;

Then pass the function:

$post->ID

Count the number of items in my array list

The number of itemIds in your list will be the same as the number of elements in your list:

int itemCount = list.size();

However, if you're looking to count the number of unique itemIds (per @pst) then you should use a set to keep track of them.

Set<String> itemIds = new HashSet<String>();

//...
itemId = p.getItemId();
itemIds.add(itemId);

//... later ...
int uniqueItemIdCount = itemIds.size();

Python Set Comprehension

You can generate pairs like this:

{(x, x + 2) for x in r if x + 2 in r}

Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.

A different way of doing it: (Although slower for large sets of primes)

{(x, y) for x in r for y in r if x + 2 == y}

Setting the JVM via the command line on Windows

yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.

My go to solution on Windows for a bit of 'packaging' is something like this:

@echo off
setlocal
@rem  _________________________
@rem
@set  JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@rem
@set  JAVA_EXE=%JAVA_HOME%\bin\java
@set  VER=test
@set  WRK=%~d0%~p0%VER%
@rem
@pushd %WRK%
cd 
@echo.
@echo  %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar
       %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar 
@rem
@rem  _________________________
popd
endlocal
@exit /b

I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.

Atom menu is missing. How do I re-enable

CONTROL + SHIFT + P and execute command "Tree View: Show"

Create a folder if it doesn't already exist

We should always modularise our code and I've written the same check it below... We first check the directory, if the directory is absent we create the directory.

$boolDirPresents = $this->CheckDir($DirectoryName);

if (!$boolDirPresents) {
        $boolCreateDirectory = $this->CreateDirectory($DirectoryName);
        if ($boolCreateDirectory) {
        echo "Created successfully";
      }
  }

function CheckDir($DirName) {
    if (file_exists($DirName)) {
        echo "Dir Exists<br>";
        return true;
    } else {
        echo "Dir Not Absent<br>";
        return false;
    }
}

function CreateDirectory($DirName) {
    if (mkdir($DirName, 0777)) {
        return true;
    } else {
        return false;
    }
}

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

How to call stopservice() method of Service class from the calling activity class

In fact to stopping the service we must use the method stopService() and you are doing in right way:

Start service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  startService(myService);

Stop service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  stopService(myService);

if you call stopService(), then the method onDestroy() in the service is called (NOT the stopService() method):

  @Override
    public void onDestroy() {
      timer.cancel();
      task.cancel();    
        Log.i(TAG, "onCreate() , service stopped...");
    }

you must implement the onDestroy() method!.

Here is a complete example including how to start/stop the service.

instantiate a class from a variable in PHP?

class Test {
    public function yo() {
        return 'yoes';
    }
}

$var = 'Test';

$obj = new $var();
echo $obj->yo(); //yoes

Set Page Title using PHP

create a new page php and add this code:

_x000D_
_x000D_
<?php_x000D_
function ch_title($title){_x000D_
    $output = ob_get_contents();_x000D_
    if ( ob_get_length() > 0) { ob_end_clean(); }_x000D_
    $patterns = array("/<title>(.*?)<\/title>/");_x000D_
    $replacements = array("<title>$title</title>");_x000D_
    $output = preg_replace($patterns, $replacements,$output);_x000D_
    echo $output;_x000D_
}_x000D_
?>
_x000D_
_x000D_
_x000D_

in <head> add code: <?php require 'page.php' ?> and on each page you call the function ch_title('my title');

Java Map equivalent in C#

class Test
{
    Dictionary<int, string> entities;

    public string GetEntity(int code)
    {
        // java's get method returns null when the key has no mapping
        // so we'll do the same

        string val;
        if (entities.TryGetValue(code, out val))
            return val;
        else
            return null;
    }
}

Bootstrap with jQuery Validation Plugin

for bootstrap 4 this work with me good

    $.validator.setDefaults({
    highlight: function(element) {
        $(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
        $(element).closest('.form-group').find(".form-control:first").addClass('is-valid');

    },
    errorElement: 'span',
    errorClass: 'invalid-feedback',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

hope it will help !

How to convert a huge list-of-vector to a matrix more efficiently?

It would help to have sample information about your output. Recursively using rbind on bigger and bigger things is not recommended. My first guess at something that would help you:

z <- list(1:3,4:6,7:9)
do.call(rbind,z)

See a related question for more efficiency, if needed.

How to read XML using XPath in Java

You can try this.

XML Document

Save as employees.xml.

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
    <Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
    </Employee>
    <Employee id="2">
        <age>35</age>
        <name>Lisa</name>
        <gender>Female</gender>
        <role>CEO</role>
    </Employee>
    <Employee id="3">
        <age>40</age>
        <name>Tom</name>
        <gender>Male</gender>
        <role>Manager</role>
    </Employee>
    <Employee id="4">
        <age>25</age>
        <name>Meghan</name>
        <gender>Female</gender>
        <role>Manager</role>
    </Employee>
</Employees>

Parser class

The class have following methods

  • List item
  • A Method that will return the Employee Name for input ID.
  • A Method that will return list of Employees Name with age greater than the input age.
  • A Method that will return list of Female Employees Name.

Source Code

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class Parser {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        Document doc = null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse("employees.xml");

            // Create XPathFactory object
            XPathFactory xpathFactory = XPathFactory.newInstance();

            // Create XPath object
            XPath xpath = xpathFactory.newXPath();

            String name = getEmployeeNameById(doc, xpath, 4);
            System.out.println("Employee Name with ID 4: " + name);

            List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
            System.out.println("Employees with 'age>30' are:" + Arrays.toString(names.toArray()));

            List<String> femaleEmps = getFemaleEmployeesName(doc, xpath);
            System.out.println("Female Employees names are:" +
                    Arrays.toString(femaleEmps.toArray()));

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }

    }


    private static List<String> getFemaleEmployeesName(Document doc, XPath xpath) {
        List<String> list = new ArrayList<>();
        try {
            //create XPathExpression object
            XPathExpression expr =
                xpath.compile("/Employees/Employee[gender='Female']/name/text()");
            //evaluate expression result on XML document
            NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++)
                list.add(nodes.item(i).getNodeValue());
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return list;
    }


    private static List<String> getEmployeeNameWithAge(Document doc, XPath xpath, int age) {
        List<String> list = new ArrayList<>();
        try {
            XPathExpression expr =
                xpath.compile("/Employees/Employee[age>" + age + "]/name/text()");
            NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++)
                list.add(nodes.item(i).getNodeValue());
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return list;
    }


    private static String getEmployeeNameById(Document doc, XPath xpath, int id) {
        String name = null;
        try {
            XPathExpression expr =
                xpath.compile("/Employees/Employee[@id='" + id + "']/name/text()");
            name = (String) expr.evaluate(doc, XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return name;
    }

}

java.lang.NoClassDefFoundError: Could not initialize class XXX

As mentioned above, this could be a number of things. In my case I had a statically initialized variable which relied on a missing entry in my properties file. Added the missing entry to the properties file and the problem was solved.

How to validate IP address in Python?

I only needed to parse IP v4 addresses. My solution based on Chills strategy follows:

def getIP():
valid = False
while not valid :
octets = raw_input( "Remote Machine IP Address:" ).strip().split(".")
try: valid=len( filter( lambda(item):0<=int(item)<256, octets) ) == 4
except: valid = False
return ".".join( octets )

Global variables in Java

To define Global Variable you can make use of static Keyword

public class Example {
    public static int a;
    public static int b;
}

now you can access a and b from anywhere by calling

Example.a;

Example.b;

Detecting EOF in C

You want to check the result of scanf() to make sure there was a successful conversion; if there wasn't, then one of three things is true:

  1. scanf() is choking on a character that isn't valid for the %f conversion specifier (i.e., something that isn't a digit, dot, 'e', or 'E');
  2. scanf() has detected EOF;
  3. scanf() has detected an error on reading stdin.

Example:

int moreData = 1;
...
printf("Input no: ");
fflush(stdout);
/**
 * Loop while moreData is true
 */
while (moreData)
{
  errno = 0;
  int itemsRead = scanf("%f", &input);
  if (itemsRead == 1)
  {
    printf("Output: %f\n", input);
    printf("Input no: ");
    fflush(stdout);
  }
  else
  {
    if (feof(stdin))
    {
      printf("Hit EOF on stdin; exiting\n");
      moreData = 0;
    }
    else if (ferror(stdin))
    {
      /**
       * I *think* scanf() sets errno; if not, replace
       * the line below with a regular printf() and
       * a generic "read error" message.
       */
      perror("error during read");
      moreData = 0;
    }
    else
    {
      printf("Bad character stuck in input stream; clearing to end of line\n");
      while (getchar() != '\n')
        ; /* empty loop */
      printf("Input no: ");
      fflush(stdout);
    }
 }

Jquery UI Datepicker not displaying

Seems to happen with some themes (cupertino/theme.css) in my case.

And the problem is the .ui-helper-hidden-accessible class which have clip property, like previous users said.

Just Overwrite it and it will be fine

$(document).ready(function() {
    $("#datePicker").datepicker({ dateFormat: "yy-m-d" });
    $('#ui-datepicker-div').css('clip', 'auto');
});

How to trigger event in JavaScript?

If you don't want to use jQuery and aren't especially concerned about backwards compatibility, just use:

let element = document.getElementById(id);
element.dispatchEvent(new Event("change")); // or whatever the event type might be

See the documentation here and here.

EDIT: Depending on your setup you might want to add bubbles: true:

let element = document.getElementById(id);
element.dispatchEvent(new Event('change', { 'bubbles': true }));

Encoding as Base64 in Java

For Java 6-7, the best option is to borrow code from the Android repository. It has no dependencies.

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Base64.java

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

This is my solution:

  1. Copy&paste $ANDROID_SDK/extras/android/support/v7/appcompat to your project ROOT

  2. Open "Project Structure" on Intellij, click "Modules" on "Project Settings", then click "appcompat"->"android', make sure "Library Module" checkbox is checked.

  3. click "YOUR-PROJECT_NAME" under "appcompat", remove "android-support-v4" and "android-support-v7-compat"; ensure the checkbox before "appcompat" is checked. And, click "ok" to close "Project Structure" dialogue.

  4. back to the mainwindow, click "appcompat"->"libs" on the top-left project area. Right-click on "android-support-v4", select menuitem "Add as library", change "Add to Module" to "Your-project". Same with "android-support-v7-compat".

After doing above, intellij should be able to correctly find the android-support-XXXX modules.

Good Luck!

Auto height div with overflow and scroll when needed

_x000D_
_x000D_
$(document).ready(function() {
//Fix dropdown-menu box size upto 2 items but above 2 items scroll the menu box
    $("#dropdown").click(function() {
        var maxHeight = 301;
        if ($(".dropdown-menu").height() > maxHeight) { 
            maxHeight = 302;
            $(".dropdown-menu").height(maxHeight);
            $(".dropdown-menu").css({'overflow-y':'scroll'});
        } else {
            $(".dropdown-menu").height();
            $(".dropdown-menu").css({'overflow-y':'hidden'});
        }
    });
});
_x000D_
_x000D_
_x000D_

The entity type <type> is not part of the model for the current context

I was facing the same issue with EntityFrameworkCore trying to update a range of values.

This approach did not work

  _dbSet.AttachRange(entity);
  _context.Entry(entity).State = EntityState.Modified;
   await _context.SaveChangesAsync().ConfigureAwait(false);

After adding UpdateRange method and removing attach and entry everything work

  _dbSet.UpdateRange(entity);
  await _context.SaveChangesAsync().ConfigureAwait(false);

Graphical user interface Tutorial in C

The two most usual choices are GTK+, which has documentation links here, and is mostly used with C; or Qt which has documentation here and is more used with C++.

I posted these two as you do not specify an operating system and these two are pretty cross-platform.

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

Based on your comments, we need to go over how the Bundling mechanism works in MVC.

Edit: Based on the comment below by VSDev, you need to ensure WebGrease is installed into your project. NuGet would be the easiest was to install this package.

When you set a bundle configuration (Example not from above to illustrate)

bundles.Add(new ScriptBundle("~/bundles/mainJs")
      .Include("~/Scripts/mainSite.js")
      .Include("~/Scripts/helperStuff.js");

You then, in your views, call something like @Scripts.Render("~/bundles/mainJs"). When your web.config is set into a debug compilation OR you explicitly turn off bundling using the following line in your BundleConfig.cs file

BundleTable.EnableOptimizations = false;

Then, in your view, you will see the following rendered out

<script src="/Scripts/mainSite.js" type="text/javascript"></script>
<script src="/Scripts/helperStuff.js" type="text/javascript"></script>

These are the individual items that made up our bundle, uncompressed and listed individually. The reason these list out individually in debug mode is so that you can debug your scripts and see them as you wrote them (actual variable names, etc).

Now, when we are not in a debug compilation and have not turned off the EnableOptimizations feature, MVC will combine those files in our bundles, compress (minify) them and output only a single script tag.

<script src="/bundles/mainJs?v=someBigLongNumber" type="text/javascript"></script>

Notice that the source is the same as the name of the bundle from the bundle configurations. Also, the number after the ?v= will change anytime you change a file in that bundle. This is to help prevent caching of old js and css files by the client browsers.

Your scripts are still there and being outputted, but they are being compressed and combined into a single file called /bundles/mainJs. This feature is present to

A) compress the files and reduce information being transmitted and,

B) reduce the number of calls to a website to retrieve the necessary content to render the page.

Nothing is missing, it sounds like everything is working as intended. In a production site, the minification makes these files almost impossible to read, thus why the minification does not take affect while debugging.

As to why the jQuery UI is still being a single JS file, ensure someone didn't hard code that into your layout view. As for the JS errors, it could be errors that are present on your development box or perhaps something did not compress correctly (however, in all of my MVC development, I have not seen a JS error because of bad minification).

JavaScript get window X/Y position for scroll

Using pure javascript you can use Window.scrollX and Window.scrollY

window.addEventListener("scroll", function(event) {
    var top = this.scrollY,
        left =this.scrollX;
}, false);

Notes

The pageXOffset property is an alias for the scrollX property, and The pageYOffset property is an alias for the scrollY property:

window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true

Here is a quick demo

_x000D_
_x000D_
window.addEventListener("scroll", function(event) {_x000D_
  _x000D_
    var top = this.scrollY,_x000D_
        left = this.scrollX;_x000D_
  _x000D_
    var horizontalScroll = document.querySelector(".horizontalScroll"),_x000D_
        verticalScroll = document.querySelector(".verticalScroll");_x000D_
    _x000D_
    horizontalScroll.innerHTML = "Scroll X: " + left + "px";_x000D_
      verticalScroll.innerHTML = "Scroll Y: " + top + "px";_x000D_
  _x000D_
}, false);
_x000D_
*{box-sizing: border-box}_x000D_
:root{height: 200vh;width: 200vw}_x000D_
.wrapper{_x000D_
    position: fixed;_x000D_
    top:20px;_x000D_
    left:0px;_x000D_
    width:320px;_x000D_
    background: black;_x000D_
    color: green;_x000D_
    height: 64px;_x000D_
}_x000D_
.wrapper div{_x000D_
    display: inline;_x000D_
    width: 50%;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    line-height: 64px_x000D_
}_x000D_
.horizontalScroll{color: orange}
_x000D_
<div class=wrapper>_x000D_
    <div class=horizontalScroll>Scroll (x,y) to </div>_x000D_
    <div class=verticalScroll>see me in action</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python: print a generator expression?

Or you can always map over an iterator, without the need to build an intermediate list:

>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM

Can't specify the 'async' modifier on the 'Main' method of a console app

I'll add an important feature that all of the other answers have overlooked: cancellation.

One of the big things in TPL is cancellation support, and console apps have a method of cancellation built in (CTRL+C). It's very simple to bind them together. This is how I structure all of my async console apps:

static void Main(string[] args)
{
    CancellationTokenSource cts = new CancellationTokenSource();
    
    System.Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        cts.Cancel();
    };

    MainAsync(args, cts.Token).GetAwaiter.GetResult();
}

static async Task MainAsync(string[] args, CancellationToken token)
{
    ...
}

Bootstrap - dropdown menu not working?

I had to download the source files instead of just the compressed files that it says to use for quick start on the bootstrap website

How to set null to a GUID property

extrac Guid values from database functions:

    #region GUID

    public static Guid GGuid(SqlDataReader reader, string field)
    {
        try
        {
            return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
        }
        catch { return Guid.Empty; }
    }

    public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
    {
        try
        {
            return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
        }
        catch { return Guid.Empty; }
    }

    public static Guid? NGuid(SqlDataReader reader, string field)
    {
        try
        {
            if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
        }
        catch { return (Guid?)null; }
    }

    public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
    {
        try
        {
            if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
        }
        catch { return (Guid?)null; }
    }

    #endregion

Calling a PHP function from an HTML form in the same file

Take a look at this example:

<!DOCTYPE HTML> 
<html>
<head>
</head>
<body> 

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = test_input($_POST["name"]);
   $email = test_input($_POST["email"]);
   $website = test_input($_POST["website"]);
   $comment = test_input($_POST["comment"]);
   $gender = test_input($_POST["gender"]);
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   Name: <input type="text" name="name">
   <br><br>
   E-mail: <input type="text" name="email">
   <br><br>
   Website: <input type="text" name="website">
   <br><br>
   Comment: <textarea name="comment" rows="5" cols="40"></textarea>
   <br><br>
   Gender:
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

The problem was the cuDNN Library for me - for whatever reason cudnn-8.0-windows10-x64-v6.0 was NOT working - I used cudnn-8.0-windows10-x64-v5.1 - ALL GOOD!

My setup working with Win10 64 and the Nvidia GTX780M:

  • Be sure you have the lib MSVCP140.DLL by checking your system/path - if not get it here
  • Run the windows installer for python 3.5.3-amd64 from here - DO NOT try newer versions as they probably won't work
  • Get the cuDNN v5.1 for CUDA 8.0 from here - put it under your users folder or in another known location (you will need this in your path)
  • Get CUDA 8.0 x86_64 from here
  • Set PATH vars as expected to point at the cuDNN libs and python (the python path should be added during the python install)
  • Make sure that ".DLL" is included in your PATHEXT variable
  • If you are using tensorflow 1.3 then you want to use cudnn64_6.dll github.com/tensorflow/tensorflow/issues/7705

If you run Windows 32 be sure to get the 32 bit versions of the files mentioned above.

How to compare numbers in bash?

The bracket stuff (e.g., [[ $a -gt $b ]] or (( $a > $b )) ) isn't enough if you want to use float numbers as well; it would report a syntax error. If you want to compare float numbers or float number to integer, you can use (( $(bc <<< "...") )).

For example,

a=2.00
b=1

if (( $(bc <<<"$a > $b") )); then 
    echo "a is greater than b"
else
    echo "a is not greater than b"
fi

You can include more than one comparison in the if statement. For example,

a=2.
b=1
c=1.0000

if (( $(bc <<<"$b == $c && $b < $a") )); then 
    echo "b is equal to c but less than a"
else
    echo "b is either not equal to c and/or not less than a"
fi

That's helpful if you want to check if a numeric variable (integer or not) is within a numeric range.

Data structure for maintaining tabular data in memory?

Have a Table class whose rows is a list of dict or better row objects

In table do not directly add rows but have a method which update few lookup maps e.g. for name if you are not adding rows in order or id are not consecutive you can have idMap too e.g.

class Table(object):
    def __init__(self):
        self.rows =  []# list of row objects, we assume if order of id
        self.nameMap = {} # for faster direct lookup for row by name

    def addRow(self, row):
        self.rows.append(row)
        self.nameMap[row['name']] = row

    def getRow(self, name):
        return self.nameMap[name]


table = Table()
table.addRow({'ID':1,'name':'a'})

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

Just found a quick and simple solution to discover type of a variable.

ES6

export const isType = (type, val) => val.constructor.name.toLowerCase() === type.toLowerCase();

ES5

function isType(type, val) {
  return val.constructor.name.toLowerCase() === type.toLowerCase();
}

Examples:

isType('array', [])
true
isType('array', {})
false
isType('string', '')
true
isType('string', 1)
false
isType('number', '')
false
isType('number', 1)
true
isType('boolean', 1)
false
isType('boolean', true)
true

EDIT

Improvment to prevent 'undefined' and 'null' values:

ES6

export const isType = (type, val) => !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());

ES5

function isType(type, val) {
  return !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
}

Why is it said that "HTTP is a stateless protocol"?

What is stateless??

Once the request is made and the response is rendered back to the client the connection will be dropped or terminated. The server will forget all about the requester.

Why stateless??

The web chooses to go for the stateless protocol. It was a genius choice because the original goal of the web was to allow documents(web pages) to be served to extremely large no. of people using very basic hardware for the server.

Maintaining a long-running connection would have been extremely resource-intensive.

If the web were chosen the stateful protocol then the load on the server would have been increased to maintain the visitor's connection.

TensorFlow not found using pip

If you are trying to install Tensorflow with Anaconda on Windows, a free advice is to please uninstall anaconda and download a 64-bit Python version, ending with amd64 from releases page. For me, its python-3.7.8-amd64.exe

Then install Tensorflow in a virtual environment by following the instructions on official website of Tensorflow.

What's the difference between 'int?' and 'int' in C#?

the symbol ? after the int means that it can be nullable.

The ? symbol is usually used in situations whereby the variable can accept a null or an integer or alternatively, return an integer or null.

Hope the context of usage helps. In this way you are not restricted to solely dealing with integers.

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

For Mac users make sure to sudo and when prompted first give your administrator password and that will be followed by keystore password which typically should be "changeit" unless you actually changed it.

IFrame: This content cannot be displayed in a frame

Use target="_top" attribute in anchor tag that will really work.

C# - Making a Process.Start wait until the process has start-up

I agree with Tom. In addition, to check the processes while performing Thread.Sleep, check the running processes. Something like:

bool found = 0;
while (!found)
{
    foreach (Process clsProcess in Process.GetProcesses())
        if (clsProcess.Name == Name)
            found = true;

    Thread.CurrentThread.Sleep(1000);
}

What is the '.well' equivalent class in Bootstrap 4

Sure officially version says the cards are the new replacements for Bootstrap wells. But Cards are a quite broad Bootstrap components now. In simple terms, you can also use Bootstrap Jumbotron too.

Clicking URLs opens default browser

If you're using a WebView you'll have to intercept the clicks yourself if you don't want the default Android behaviour.

You can monitor events in a WebView using a WebViewClient. The method you want is shouldOverrideUrlLoading(). This allows you to perform your own action when a particular URL is selected.

You set the WebViewClient of your WebView using the setWebViewClient() method.

If you look at the WebView sample in the SDK there's an example which does just what you want. It's as simple as:

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

How do you copy a record in a SQL table but swap out the unique id of the new row?

Specify all fields but your ID field.

INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId)
SELECT FIELD2, NULL, ..., FIELD529, FIELD1
FROM MyTable
WHERE FIELD1 = @Id;

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

As of upgrading from pip 7.x.x to 8.x.x on Python 3.4 (for *.whl support).

Wrong command: pip install --upgrade pip (can't move pip.exe to temporary folder, permisson denied)

OK variant: py -3.4 -m pip install --upgrade pip (do not execute pip.exe)

Removing Spaces from a String in C?

Easiest and most efficient don't usually go together...

Here's a possible solution:

void remove_spaces(char* s) {
    const char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}

Reverse order of foreach list items

If you don't mind destroying the array (or a temp copy of it) you can do:

$stack = array("orange", "banana", "apple", "raspberry");

while ($fruit = array_pop($stack)){
    echo $fruit . "\n<br>"; 
}

produces:

raspberry 
apple 
banana 
orange 

I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:

$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
    echo $stack[$index] ." is in position ". $index . "\n<br>";
    $index--;
} 

But as you can see, you have to be very careful with the index...

How can I rename a single column in a table at select?

if you are using sql server, use brackets or single quotes around alias name in a query you have in code.

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

What is the difference between Class.getResource() and ClassLoader.getResource()?

To answer the question whether there is any caching going on.

I investigated this point further by running a stand-alone Java application that continuously loaded a file from disk using the getResourceAsStream ClassLoader method. I was able to edit the file, and the changes were reflected immediately, i.e., the file was reloaded from disk without caching.

However: I'm working on a project with several maven modules and web projects that have dependencies on each other. I'm using IntelliJ as my IDE to compile and run the web projects.

I noticed that the above seemed to no longer hold true, the reason being that the file that I was being loaded is now baked into a jar and deployed to the depending web project. I only noticed this after trying to change the file in my target folder, to no avail. This made it seem as though there was caching going on.

Execute jQuery function after another function completes

You should use a callback parameter:

function Typer(callback)
{
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];
    var interval = setInterval(function() {
        if(i == srcText.length - 1) {
            clearInterval(interval);
            callback();
            return;
        }
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#message").html(result);
    },
    100);
    return true;


}

function playBGM () {
    alert("Play BGM function");
    $('#bgm').get(0).play();
}

Typer(function () {
    playBGM();
});

// or one-liner: Typer(playBGM);

So, you pass a function as parameter (callback) that will be called in that if before return.

Also, this is a good article about callbacks.

_x000D_
_x000D_
function Typer(callback)_x000D_
{_x000D_
    var srcText = 'EXAMPLE ';_x000D_
    var i = 0;_x000D_
    var result = srcText[i];_x000D_
    var interval = setInterval(function() {_x000D_
        if(i == srcText.length - 1) {_x000D_
            clearInterval(interval);_x000D_
            callback();_x000D_
            return;_x000D_
        }_x000D_
        i++;_x000D_
        result += srcText[i].replace("\n", "<br />");_x000D_
        $("#message").html(result);_x000D_
    },_x000D_
    100);_x000D_
    return true;_x000D_
        _x000D_
    _x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
    alert("Play BGM function");_x000D_
    $('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
    playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Adding ASP.NET MVC5 Identity Authentication to an existing project

Configuring Identity to your existing project is not hard thing. You must install some NuGet package and do some small configuration.

First install these NuGet packages with Package Manager Console:

PM> Install-Package Microsoft.AspNet.Identity.Owin 
PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
PM> Install-Package Microsoft.Owin.Host.SystemWeb 

Add a user class and with IdentityUser inheritance:

public class AppUser : IdentityUser
{
    //add your custom properties which have not included in IdentityUser before
    public string MyExtraProperty { get; set; }  
}

Do same thing for role:

public class AppRole : IdentityRole
{
    public AppRole() : base() { }
    public AppRole(string name) : base(name) { }
    // extra properties here 
}

Change your DbContext parent from DbContext to IdentityDbContext<AppUser> like this:

public class MyDbContext : IdentityDbContext<AppUser>
{
    // Other part of codes still same 
    // You don't need to add AppUser and AppRole 
    // since automatically added by inheriting form IdentityDbContext<AppUser>
}

If you use the same connection string and enabled migration, EF will create necessary tables for you.

Optionally, you could extend UserManager to add your desired configuration and customization:

public class AppUserManager : UserManager<AppUser>
{
    public AppUserManager(IUserStore<AppUser> store)
        : base(store)
    {
    }

    // this method is called by Owin therefore this is the best place to configure your User Manager
    public static AppUserManager Create(
        IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
    {
        var manager = new AppUserManager(
            new UserStore<AppUser>(context.Get<MyDbContext>()));

        // optionally configure your manager
        // ...

        return manager;
    }
}

Since Identity is based on OWIN you need to configure OWIN too:

Add a class to App_Start folder (or anywhere else if you want). This class is used by OWIN. This will be your startup class.

namespace MyAppNamespace
{
    public class IdentityConfig
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new MyDbContext());
            app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) =>
                new RoleManager<AppRole>(
                    new RoleStore<AppRole>(context.Get<MyDbContext>())));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Login"),
            });
        }
    }
}

Almost done just add this line of code to your web.config file so OWIN could find your startup class.

<appSettings>
    <!-- other setting here -->
    <add key="owin:AppStartup" value="MyAppNamespace.IdentityConfig" />
</appSettings>

Now in entire project you could use Identity just like any new project had already installed by VS. Consider login action for example

[HttpPost]
public ActionResult Login(LoginViewModel login)
{
    if (ModelState.IsValid)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
        var authManager = HttpContext.GetOwinContext().Authentication;

        AppUser user = userManager.Find(login.UserName, login.Password);
        if (user != null)
        {
            var ident = userManager.CreateIdentity(user, 
                DefaultAuthenticationTypes.ApplicationCookie);
            //use the instance that has been created. 
            authManager.SignIn(
                new AuthenticationProperties { IsPersistent = false }, ident);
            return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
        }
    }
    ModelState.AddModelError("", "Invalid username or password");
    return View(login);
}

You could make roles and add to your users:

public ActionResult CreateRole(string roleName)
{
    var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();

    if (!roleManager.RoleExists(roleName))
        roleManager.Create(new AppRole(roleName));
    // rest of code
} 

You could also add a role to a user, like this:

UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");

By using Authorize you could guard your actions or controllers:

[Authorize]
public ActionResult MySecretAction() {}

or

[Authorize(Roles = "Admin")]]
public ActionResult MySecretAction() {}

You can also install additional packages and configure them to meet your requirement like Microsoft.Owin.Security.Facebook or whichever you want.

Note: Don't forget to add relevant namespaces to your files:

using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

You could also see my other answers like this and this for advanced use of Identity.

Why do people hate SQL cursors so much?

Can you post that cursor example or link to the question? There's probably an even better way than a recursive CTE.

In addition to other comments, cursors when used improperly (which is often) cause unnecessary page/row locks.

How to get table cells evenly spaced?

In your CSS file:

.TableHeader { width: 100px; }

This will set all of the td tags below each header to 100px. You can also add a width definition (in the markup) to each individual th tag, but the above solution would be easier.

parsing a tab-separated file in Python

I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)

Anyway, here's my take:

Say these are the tab-separated values in your input file:

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20

then this:

with open("tab-separated-values.txt") as inp:
    print( list(zip(*(line.strip().split('\t') for line in inp))) )

would produce the following:

[('1', '6', '11', '16'), 
 ('2', '7', '12', '17'), 
 ('3', '8', '13', '18'), 
 ('4', '9', '14', '19'), 
 ('5', '10', '15', '20')]

As you can see, it put the k-th element of each row into the k-th array.

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

A non-blocking read on a subprocess.PIPE in Python

Existing solutions did not work for me (details below). What finally worked was to implement readline using read(1) (based on this answer). The latter does not block:

from subprocess import Popen, PIPE
from threading import Thread
def process_output(myprocess): #output-consuming thread
    nextline = None
    buf = ''
    while True:
        #--- extract line using read(1)
        out = myprocess.stdout.read(1)
        if out == '' and myprocess.poll() != None: break
        if out != '':
            buf += out
            if out == '\n':
                nextline = buf
                buf = ''
        if not nextline: continue
        line = nextline
        nextline = None

        #--- do whatever you want with line here
        print 'Line is:', line
    myprocess.stdout.close()

myprocess = Popen('myprogram.exe', stdout=PIPE) #output-producing process
p1 = Thread(target=process_output, args=(dcmpid,)) #output-consuming thread
p1.daemon = True
p1.start()

#--- do whatever here and then kill process and thread if needed
if myprocess.poll() == None: #kill process; will automatically stop thread
    myprocess.kill()
    myprocess.wait()
if p1 and p1.is_alive(): #wait for thread to finish
    p1.join()

Why existing solutions did not work:

  1. Solutions that require readline (including the Queue based ones) always block. It is difficult (impossible?) to kill the thread that executes readline. It only gets killed when the process that created it finishes, but not when the output-producing process is killed.
  2. Mixing low-level fcntl with high-level readline calls may not work properly as anonnn has pointed out.
  3. Using select.poll() is neat, but doesn't work on Windows according to python docs.
  4. Using third-party libraries seems overkill for this task and adds additional dependencies.

Tab separated values in awk

Should this not work?

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk '{print $1}'

Why doesn't Mockito mock static methods?

Mockito [3.4.0] can mock static methods!

  1. Replace mockito-core dependency with mockito-inline:3.4.0.

  2. Class with static method:

    class Buddy {
      static String name() {
        return "John";
      }
    }
    
  3. Use new method Mockito.mockStatic():

    @Test
    void lookMomICanMockStaticMethods() {
      assertThat(Buddy.name()).isEqualTo("John");
    
      try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
        theMock.when(Buddy::name).thenReturn("Rafael");
        assertThat(Buddy.name()).isEqualTo("Rafael");
      }
    
      assertThat(Buddy.name()).isEqualTo("John");
    }
    

    Mockito replaces the static method within the try block only.

how to convert a string to a bool

I love extension methods and this is the one I use...

static class StringHelpers
{
    public static bool ToBoolean(this String input, out bool output)
    {
        //Set the default return value
        output = false;

        //Account for a string that does not need to be processed
        if (input == null || input.Length < 1)
            return false;

        if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
            output = true;
        else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
            output = false;
        else
            return false;

        //Return success
        return true;
    }
}

Then to use it just do something like...

bool b;
bool myValue;
data = "1";
if (!data.ToBoolean(out b))
  throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
else
  myValue = b;  //myValue is True

How do I copy a string to the clipboard?

you can try this:

command = 'echo content |clip'
subprocess.check_call(command, shell=True)

init-param and context-param

<context-param> 
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:/META-INF/PersistenceContext.xml
    </param-value>
</context-param>

I have initialized my PersistenceContext.xml within <context-param> because all my servlets will be interacting with database in MVC framework.

Howerver,

<servlet>
    <servlet-name>jersey-servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:ApplicationContext.xml
        </param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.organisation.project.rest</param-value>
    </init-param>
</servlet>

in the aforementioned code, I am configuring jersey and the ApplicationContext.xml only to rest layer. For the same I am using </init-param>

Does VBA have Dictionary Structure?

All the others have already mentioned the use of the scripting.runtime version of the Dictionary class. If you are unable to use this DLL you can also use this version, simply add it to your code.

https://github.com/VBA-tools/VBA-Dictionary/blob/master/Dictionary.cls

It is identical to Microsoft's version.

Android checkbox style

Perhaps you want something like:

<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
    <item name="android:checkboxStyle">@style/customCheckBoxStyle</item>
</style>

<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
    <item name="android:textColor">@android:color/black</item>
</style>

Note, the textColor item.

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

Can a main() method of class be invoked from another class in java

As far as I understand, the question is NOT about recursion. We can easily call main method of another class in your class. Following example illustrates static and calling by object. Note omission of word static in Class2

class Class1{
    public static void main(String[] args) {
        System.out.println("this is class 1");
    }    
}

class Class2{
    public void main(String[] args) {
        System.out.println("this is class 2");
    }    
}

class MyInvokerClass{
    public static void main(String[] args) {

        System.out.println("this is MyInvokerClass");
        Class2 myClass2 = new Class2();
        Class1.main(args);
        myClass2.main(args);
    }    
}

Output Should be:

this is wrapper class

this is class 1

this is class 2

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

How can I use pickle to save a dict?

import pickle

your_data = {'foo': 'bar'}

# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
    pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)

# Load data (deserialize)
with open('filename.pickle', 'rb') as handle:
    unserialized_data = pickle.load(handle)

print(your_data == unserialized_data)

The advantage of HIGHEST_PROTOCOL is that files get smaller. This makes unpickling sometimes much faster.

Important notice: The maximum file size of pickle is about 2GB.

Alternative way

import mpu
your_data = {'foo': 'bar'}
mpu.io.write('filename.pickle', data)
unserialized_data = mpu.io.read('filename.pickle')

Alternative Formats

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

Remove xticks in a matplotlib plot?

There is a better, and simpler, solution than the one given by John Vinyard. Use NullLocator:

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.show()
plt.savefig('plot')

Hope that helps.

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Get the short Git version hash

You can do just about any format you want with --pretty=format:

git log -1 --pretty=format:%h 

How to find and restore a deleted file in a Git repository

To restore a deleted and commited file:

git reset HEAD some/path
git checkout -- some/path

It was tested on Git version 1.7.5.4.

How to connect to LocalDB in Visual Studio Server Explorer?

The following works with Visual Studio 2017 Community Edition on Windows 10 using SQLServer Express 2016.

Open a PowerShell check what it is called using SqlLocalDB.exe info and whether it is Running with SqlLocalDB.exe info NAME. Here's what it looks like on my machine:

> SqlLocalDB.exe info
MSSQLLocalDB
> SqlLocalDB.exe info MSSQLLocalDB
Name:               mssqllocaldb
Version:            13.0.1601.5
Shared name:
Owner:              DESKTOP-I4H3E09\simon
Auto-create:        Yes
State:              Running
Last start time:    4/12/2017 8:24:36 AM
Instance pipe name: np:\\.\pipe\LOCALDB#EFC58609\tsql\query
>

If it isn't running then you need to start it with SqlLocalDB.exe start MSSQLLocalDB. When it is running you see the Instance pipe name: which starts with np:\\. Copy that named pipe string. Within VS2017 open the view Server Explorer and create a new connection of type Microsoft SQL Server (SqlClient) (don't be fooled by the other file types you want the full fat connection type) and set the Server name: to be the instance pipe name you copied from PowerShell.

I also set the Connect to database to be the same database that was in the connection string that was working in my Dotnet Core / Entity Framework Core project which was set up using dotnet ef database update.

You can login and create a database using the sqlcmd and the named pipe string:

sqlcmd -S np:\\.\pipe\LOCALDB#EFC58609\tsql\query 1> create database EFGetStarted.ConsoleApp.NewDb; 2> GO

There are instructions on how to create a user for your application at https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility

How to get date representing the first day of a month?

As of SQL Server 2012 you can use the eomonth built-in function, which is intended for getting the end of the month but can also be used to get the start as so:

select dateadd(day, 1, eomonth(<date>, -1))

If you need the result as a datetime etc., just cast it:

select cast(dateadd(day, 1, eomonth(<date>, -1)) as datetime)

Unicode character as bullet for list-item in CSS

Images are not recommended since they may appear pixelated on some devices (Apple devices with Retina display) or when zoomed in. With a character, your list looks awesome everytime.

Here is the best solution I've found so far. It works great and it's cross-browser (IE 8+).

ul {
    list-style: none;
    padding-left: 1.2em;
    text-indent: -1.2em;
}

li:before {
    content: "?";
    display: block;
    float: left;
    width: 1.2em;
    color: #ff0000;
}

The important thing is to have the character in a floating block with a fixed width so that the text remains aligned if it's too long to fit on a single line. 1.2em is the width you want for your character, change it for your needs. Don't forget to reset padding and margin for ul and li elements.

EDIT: Be aware that the "1.2em" size may vary if you use a different font in ul and li:before. It's safer to use pixels.

How To Execute SSH Commands Via PHP

//Update 2018, works//

Method1:

Download phpseclib v1 and use this code:

<?php
set_include_path(__DIR__ . '/phpseclib1.0.11');
include("Net/SSH2.php");

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  include("Crypt/RSA.php");
  $key = new Crypt_RSA();
  $key->loadKey(file_get_contents('private-key.ppk'));
  */

$ssh = new Net_SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))  exit('Login Failed');

echo $ssh->exec('pwd');
?>

or Method2:

Download newest phpseclib v2 (requires composer install at first):

<?php

set_include_path($path=__DIR__ . '/phpseclib-master/phpseclib');
include ($path.'/../vendor/autoload.php');

$loader = new \Composer\Autoload\ClassLoader();

use phpseclib\Net\SSH2;

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  use phpseclib\Crypt\RSA;
  $key = new RSA();
  $key->load(file_get_contents('private-key.ppk'));
  */

$ssh = new SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))   exit('Login Failed'); 

echo $ssh->exec('pwd');
?>

p.s. if you get "Connection timed out" then it's probably the issue of HOST/FIREWALL (local or remote) or like that, not a fault of script.

Can gcc output C code after preprocessing?

Run:

gcc -E <file>.c

or

g++ -E <file>.cpp

Parsing domain from a URL

function getTrimmedUrl($link)
{
    $str = str_replace(["www.","https://","http://"],[''],$link);
    $link = explode("/",$str);
    return strtolower($link[0]);                
}

Default settings Raspberry Pi /etc/network/interfaces

Assuming that you have a DHCP server running at your router I would use:

# /etc/network/interfaces
auto lo eth0
iface lo inet loopback

iface eth0 inet dhcp

After changing the file issue (as root):

/etc/init.d/networking restart

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Why emulator is very slow in Android Studio?

I tend to load AVD through snapshot which can be setup in the AVD Manager > Choose AVD > Details... > Checking Emulator Options: Snapshot, and then to run the AVD, Select AVD in AVD Manager > Start... > Select Save To Snapshot and Launch from Snapshot. The first time, ensure that save to snapshot is chosen, as no snapshot exists to launch. The next time onwards choose launch from snapshot.

Slightly apprehensive to suggest this as well, but I have noticed a peculiar behavior when loading and running AVD. When I have the laptop battery being charged on my Lenovo laptop - 64 bit Windows 7, 4GB, 2.5GHz machine, the emulator loads and runs slightly faster and also lags less. I wonder if it is the configuration on my laptop to slow down high computational processes. Would be nice to know if someone else has noticed this behavior? Unplug the charger when the AVD is loaded and see if the AVD slows down.

Efficient way to apply multiple filters to pandas DataFrame or Series

If you want to check any/all of multiple columns for a value, you can do:

df[(df[['HomeTeam', 'AwayTeam']] == 'Fulham').any(axis=1)]

Android get image from gallery into ImageView

import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.imageView);
    }

    public void btn_gallery(View view) {

        Intent intent =new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);

        startActivityForResult(intent,100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==100 && resultCode==RESULT_OK)
        {
            Uri uri = data.getData();
            img.setImageURI(uri);
        }
    }
}

How to convert unix timestamp to calendar date moment.js

UNIX timestamp it is count of seconds from 1970, so you need to convert it to JS Date object:

var date = new Date(unixTimestamp*1000);

How can I remove a character from a string using JavaScript?

Your first func is almost right. Just remove the 'g' flag which stands for 'global' (edit) and give it some context to spot the second 'r'.

Edit: didn't see it was the second 'r' before so added the '/'. Needs \/ to escape the '/' when using a regEx arg. Thanks for the upvotes but I was wrong so I'll fix and add more detail for people interested in understanding the basics of regEx better but this would work:

mystring.replace(/\/r/, '/')

Now for the excessive explanation:

When reading/writing a regEx pattern think in terms of: <a character or set of charcters> followed by <a character or set of charcters> followed by <...

In regEx <a character or set of charcters> could be one at a time:

/each char in this pattern/

So read as e, followed by a, followed by c, etc...

Or a single <a character or set of charcters> could be characters described by a character class:

/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)

Or expanded on to match a quantity of characters (but still best to think of as a single element in terms of the sequential pattern):

/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would

/[aA]{1,3}/
//1-3 matches of 'a' or 'A'

/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class

/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)

So smoosh a bunch together:

   var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
   var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can   eat098765';

   joesStr.match(rePattern);

   //returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
   //without the 'g' after the closing '/' it would just stop at the first   match and return:
   //["aaaAAAaaEat at Joes123454321"]

And of course I've over-elaborated but my point was simply that this:

/cat/

is a series of 3 pattern elements (a thing followed by a thing followed by a thing).

And so is this:

/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/

As wacky as regEx starts to look, it all breaks down to series of things (potentially multi-character things) following each other sequentially. Kind of a basic point but one that took me a while to get past so I've gone overboard explaining it here as I think it's one that would help the OP and others new to regEx understand what's going on. The key to reading/writing regEx is breaking it down into those pieces.

Get the value for a listbox item by index

Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.

Items of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.

ListBox control has a GetItemText which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue method.

GetItemValue Extension Method

We can create GetItemValue Extension Method to get item value which works like GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.

This method is applicable on ComboBox and CheckedListBox too.

Build Maven Project Without Running Unit Tests

I like short version: mvn clean install -DskipTests

It's work too: mvn clean install -DskipTests=true

If you absolutely must, you can also use the maven.test.skip property to skip compiling the tests. maven.test.skip is honored by Surefire, Failsafe and the Compiler Plugin. mvn clean install -Dmaven.test.skip=true

and you can add config in maven.xml

<project>
      [...]
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.16</version>
            <configuration>
              <skipTests>true</skipTests>
            </configuration>
          </plugin>
        </plugins>
      </build>
      [...]
    </project>

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

Custom Listview Adapter with filter Android

In your CustomAdapter class implement filterable.

listview with search search listview

 public class CustomAdapter extends BaseAdapter implements Filterable {

    private List<ItemsModel> itemsModelsl;
    private List<ItemsModel> itemsModelListFiltered;
    private Context context;

    public CustomAdapter(List<ItemsModel> itemsModelsl, Context context) {
        this.itemsModelsl = itemsModelsl;
        this.itemsModelListFiltered = itemsModelsl;
        this.context = context;
    }



    @Override
    public int getCount() {
        return itemsModelListFiltered.size();
    }

    @Override
    public Object getItem(int position) {
        return itemsModelListFiltered.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = getLayoutInflater().inflate(R.layout.row_items,null);


        TextView names = view.findViewById(R.id.name);
        TextView emails = view.findViewById(R.id.email);
        ImageView imageView = view.findViewById(R.id.images);

        names.setText(itemsModelListFiltered.get(position).getName());
        emails.setText(itemsModelListFiltered.get(position).getEmail());
        imageView.setImageResource(itemsModelListFiltered.get(position).getImages());

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("main activity","item clicked");
                startActivity(new Intent(MainActivity.this,ItemsPreviewActivity.class).putExtra("items",itemsModelListFiltered.get(position)));

            }
        });

        return view;
    }



    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults filterResults = new FilterResults();
                if(constraint == null || constraint.length() == 0){
                    filterResults.count = itemsModelsl.size();
                    filterResults.values = itemsModelsl;

                }else{
                    List<ItemsModel> resultsModel = new ArrayList<>();
                    String searchStr = constraint.toString().toLowerCase();

                    for(ItemsModel itemsModel:itemsModelsl){
                        if(itemsModel.getName().contains(searchStr) || itemsModel.getEmail().contains(searchStr)){
                            resultsModel.add(itemsModel);

                        }
                         filterResults.count = resultsModel.size();
                            filterResults.values = resultsModel;
                    }


                }

                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                itemsModelListFiltered = (List<ItemsModel>) results.values;
                notifyDataSetChanged();

            }
        };
        return filter;
    }
}

}

You can get the whole tutorial here: ListView With Search/Filter and OnItemClickListener

Github Source Code

PHP Warning: PHP Startup: ????????: Unable to initialize module

This is an old thread, but I stumbled across it when trying to solve a similar problem.

For me, I got this particular error relating to the php_wincache.dll. I was in the process of updating PHP from 5.5.38 to 5.6.31 on a Windows server. For some reason, not all of the DLL files updated with the newest versions. Most did, but some didn't.

So, if you get an error similar to this, make sure all the extensions are in place and updated.

How to view method information in Android Studio?

If you need only Parameter info then:

On Mac, it's assigned to Command+P

On Windows, it's assigned to Ctrl+P

If you need document info then:

On Mac, it's assigned to Command+Q

On Windows, it's assigned to Ctrl+Q

How to get the Development/Staging/production Hosting Environment in ConfigureServices

The hosting environment comes from the ASPNET_ENV environment variable, which is available during Startup using the IHostingEnvironment.IsEnvironment extension method, or one of the corresponding convenience methods of IsDevelopment or IsProduction. Either save what you need in Startup(), or in ConfigureServices call:

var foo = Environment.GetEnvironmentVariable("ASPNET_ENV");

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

How does the bitwise complement operator (~ tilde) work?

~ flips the bits in the value.

Why ~2 is -3 has to do with how numbers are represented bitwise. Numbers are represented as two's complement.

So, 2 is the binary value

00000010

And ~2 flips the bits so the value is now:

11111101

Which, is the binary representation of -3.

When increasing the size of VARCHAR column on a large table could there be any problems?

Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.

JavaScript for...in vs for

Watch out!

If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.

https://developer.mozilla.org/en/DOM/HTMLCollection

If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!

var scriptTags = document.getElementsByTagName("script");

for(var i = 0; i < scriptTags.length; i++)
alert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)

for(var i in scriptTags)
alert(i); // Will print "length", "item" and "namedItem" in addition to your elements!

Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection: https://developer.mozilla.org/en/DOM/document.getElementsByTagName

How to call a parent method from child class in javascript?

Here's a nice way for child objects to have access to parent properties and methods using JavaScript's prototype chain, and it's compatible with Internet Explorer. JavaScript searches the prototype chain for methods and we want the child’s prototype chain to looks like this:

Child instance -> Child’s prototype (with Child methods) -> Parent’s prototype (with Parent methods) -> Object prototype -> null

The child methods can also call shadowed parent methods, as shown at the three asterisks *** below.

Here’s how:

_x000D_
_x000D_
//Parent constructor_x000D_
function ParentConstructor(firstName){_x000D_
    //add parent properties:_x000D_
    this.parentProperty = firstName;_x000D_
}_x000D_
_x000D_
//add 2 Parent methods:_x000D_
ParentConstructor.prototype.parentMethod = function(argument){_x000D_
    console.log(_x000D_
            "Parent says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ParentConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Parent! argument=" + argument);_x000D_
};_x000D_
_x000D_
//Child constructor    _x000D_
function ChildConstructor(firstName, lastName){_x000D_
    //first add parent's properties_x000D_
    ParentConstructor.call(this, firstName);_x000D_
_x000D_
    //now add child's properties:_x000D_
    this.childProperty = lastName;_x000D_
}_x000D_
_x000D_
//insert Parent's methods into Child's prototype chain_x000D_
var rCopyParentProto = Object.create(ParentConstructor.prototype);_x000D_
rCopyParentProto.constructor = ChildConstructor;_x000D_
ChildConstructor.prototype = rCopyParentProto;_x000D_
_x000D_
//add 2 Child methods:_x000D_
ChildConstructor.prototype.childMethod = function(argument){_x000D_
    console.log(_x000D_
            "Child says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ChildConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Child! argument=" + argument);_x000D_
_x000D_
    // *** call Parent's version of common method_x000D_
    ParentConstructor.prototype.commonMethod(argument);_x000D_
};_x000D_
_x000D_
//create an instance of Child_x000D_
var child_1 = new ChildConstructor('Albert', 'Einstein');_x000D_
_x000D_
//call Child method_x000D_
child_1.childMethod('do child method');_x000D_
_x000D_
//call Parent method_x000D_
child_1.parentMethod('do parent method');_x000D_
_x000D_
//call common method_x000D_
child_1.commonMethod('do common method');
_x000D_
_x000D_
_x000D_

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

How to swap two variables in JavaScript

let a = 2, b = 4;
[b, a] = [a, b];

a more verbose approach would be

let a = 2, b = 4;
a = [a, b];
b = a[0];
a = a[1];

What's the best way to set a single pixel in an HTML5 canvas?

If you are concerned about the speed then you could also consider WebGL.

Toolbar navigation icon never set

work for me...

<android.support.v7.widget.Toolbar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toolBar"
        android:background="@color/colorGreen"
        app:title="Title"
        app:titleTextColor="@color/colorBlack"
        app:navigationIcon="@drawable/ic_action_back"/>

Sending intent to BroadcastReceiver from adb

Another thing to keep in mind: Android 8 limits the receivers that can be registered via manifest (e.g., statically)

https://developer.android.com/guide/components/broadcast-exceptions

How to iterate using ngFor loop Map containing key as string and values as map iteration

The below code useful to display in the map insertion order.

<ul>
    <li *ngFor="let recipient of map | keyvalue: asIsOrder">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

.ts file add the below code.

asIsOrder(a, b) {
    return 1;
}

How can I get selector from jQuery object

In collaboration with @drzaus we've come up with the following jQuery plugin.

jQuery.getSelector

!(function ($, undefined) {
    /// adapted http://jsfiddle.net/drzaus/Hgjfh/5/

    var get_selector = function (element) {
        var pieces = [];

        for (; element && element.tagName !== undefined; element = element.parentNode) {
            if (element.className) {
                var classes = element.className.split(' ');
                for (var i in classes) {
                    if (classes.hasOwnProperty(i) && classes[i]) {
                        pieces.unshift(classes[i]);
                        pieces.unshift('.');
                    }
                }
            }
            if (element.id && !/\s/.test(element.id)) {
                pieces.unshift(element.id);
                pieces.unshift('#');
            }
            pieces.unshift(element.tagName);
            pieces.unshift(' > ');
        }

        return pieces.slice(1).join('');
    };

    $.fn.getSelector = function (only_one) {
        if (true === only_one) {
            return get_selector(this[0]);
        } else {
            return $.map(this, function (el) {
                return get_selector(el);
            });
        }
    };

})(window.jQuery);

Minified Javascript

// http://stackoverflow.com/questions/2420970/how-can-i-get-selector-from-jquery-object/15623322#15623322
!function(e,t){var n=function(e){var n=[];for(;e&&e.tagName!==t;e=e.parentNode){if(e.className){var r=e.className.split(" ");for(var i in r){if(r.hasOwnProperty(i)&&r[i]){n.unshift(r[i]);n.unshift(".")}}}if(e.id&&!/\s/.test(e.id)){n.unshift(e.id);n.unshift("#")}n.unshift(e.tagName);n.unshift(" > ")}return n.slice(1).join("")};e.fn.getSelector=function(t){if(true===t){return n(this[0])}else{return e.map(this,function(e){return n(e)})}}}(window.jQuery)

Usage and Gotchas

<html>
    <head>...</head>
    <body>
        <div id="sidebar">
            <ul>
                <li>
                    <a href="/" id="home">Home</a>
                </li>
            </ul>
        </div>
        <div id="main">
            <h1 id="title">Welcome</h1>
        </div>

        <script type="text/javascript">

            // Simple use case
            $('#main').getSelector();           // => 'HTML > BODY > DIV#main'

            // If there are multiple matches then an array will be returned
            $('body > div').getSelector();      // => ['HTML > BODY > DIV#main', 'HTML > BODY > DIV#sidebar']

            // Passing true to the method will cause it to return the selector for the first match
            $('body > div').getSelector(true);  // => 'HTML > BODY > DIV#main'

        </script>
    </body>
</html>

Fiddle w/ QUnit tests

http://jsfiddle.net/CALY5/5/

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

It says that TypeError: document.getElementById(...) is null

Make sure the script is placed in the bottom of the BODY element of the document you're trying to manipulate, not in the HEAD element or placed before any of the elements you want to "get".

It does not matter if you import the script or if it's inline, the important thing is the placing. You don't have to put the command inside a function either; while it's good practice you can just call it directly, it works just fine.

Change the background color of a row in a JTable

One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:

static class MyTableModel extends DefaultTableModel {

    List<Color> rowColours = Arrays.asList(
        Color.RED,
        Color.GREEN,
        Color.CYAN
    );

    public void setRowColour(int row, Color c) {
        rowColours.set(row, c);
        fireTableRowsUpdated(row, row);
    }

    public Color getRowColour(int row) {
        return rowColours.get(row);
    }

    @Override
    public int getRowCount() {
        return 3;
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int row, int column) {
        return String.format("%d %d", row, column);
    }
}

Note that setRowColour calls fireTableRowsUpdated; this will cause just that row of the table to be updated.

The renderer can get the model from the table:

static class MyTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        MyTableModel model = (MyTableModel) table.getModel();
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(model.getRowColour(row));
        return c;
    }
}

Changing a row's colour would be as simple as:

model.setRowColour(1, Color.YELLOW);

Using jQuery to test if an input has focus

I had a .live("focus") event set to select() (highlight) the contents of a text input so that the user wouldn't have to select it before typing a new value.

$(formObj).select();

Because of quirks between different browsers, the select would sometimes be superseded by the click that caused it, and it would deselect the contents right after in favor of placing the cursor within the text field (worked mostly ok in FF but failed in IE)

I thought I could solve this by putting a slight delay on the select...

setTimeout(function(){$(formObj).select();},200);

This worked fine and the select would persist, but a funny problem arose.. If you tabbed from one field to the next, the focus would switch to the next field before the select took place. Since select steals focus, the focus would then go back and trigger a new "focus" event. This ended up in a cascade of input selects dancing all over the screen.

A workable solution would be to check that the field still has focus before executing the select(), but as mentioned, there's no simple way to check... I ended up just dispensing with the whole auto highlight, rather than turning what should be a single jQuery select() call into a huge function laden with subroutines...

jQuery - find table row containing table cell containing specific text

   <input type="text" id="text" name="search">
<table id="table_data">
        <tr class="listR"><td>PHP</td></tr>
        <tr class="listR"><td>MySql</td></tr>
        <tr class="listR"><td>AJAX</td></tr>
        <tr class="listR"><td>jQuery</td></tr>
        <tr class="listR"><td>JavaScript</td></tr>
        <tr class="listR"><td>HTML</td></tr>
        <tr class="listR"><td>CSS</td></tr>
        <tr class="listR"><td>CSS3</td></tr>
</table>

$("#textbox").on('keyup',function(){
        var f = $(this).val();
      $("#table_data tr.listR").each(function(){
            if ($(this).text().search(new RegExp(f, "i")) < 0) {
                $(this).fadeOut();
             } else {
                 $(this).show();
            }
        });
    });

Demo You can perform by search() method with use RegExp matching text

How to use enums in C++

While C++ (excluding C++11) has enums, the values in them are "leaked" into the global namespace.
If you don't want to have them leaked (and don't NEED to use the enum type), consider the following:

class EnumName {  
   public:   
      static int EnumVal1;  
      (more definitions)  
};  
EnumName::EnumVal1 = {value};  
if ([your value] == EnumName::EnumVal1)  ...

element not interactable exception in selenium web automation

If it's working in the debug, then wait must be the proper solution.
I will suggest to use the explicit wait, as given below:

WebDriverWait wait = new WebDriverWait(new ChromeDriver(), 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#Passwd")));

Storyboard - refer to ViewController in AppDelegate

For iOS 13+

in SceneDelegate:

var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options 
connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let storyboard = UIStoryboard(name: "Main", bundle: nil) // Where "Main" is the storyboard file name
    let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") // Where "ViewController" is the ID of your viewController
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

Reading an Excel file in python using pandas

Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:

import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])

Since .sheet_names returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).

How to uninstall a Windows Service when there is no executable for it left on the system?

Create a copy of executables of same service and paste it on the same path of the existing service and then uninstall.

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

Change key pair for ec2 instance

If below steps are followed it will save lot of time and there will be no need to stop the running instance.

  1. Start new t1.micro EC2 instance, using new key pair. Make sure you create it in the same subnet, otherwise you will have to terminate the instance and create it again.
  2. SSH to the new micro instance and copy content of ~/.ssh/authorized_keys somewhere on your computer.
  3. Login to main instance with old ssh key.
  4. Copy & replace the file content from point 2 to ~/.ssh/authorized_keys
  5. Now you can login again only with new key. Old key will not work anymore.

That is it. Enjoy :)

Convert a Map<String, String> to a POJO

The answers provided so far using Jackson are so good, but still you could have a util function to help you convert different POJOs as follows:

    public static <T> T convert(Map<String, Object> aMap, Class<T> t) {
        try {
            return objectMapper
                    .convertValue(aMap, objectMapper.getTypeFactory().constructType(t));
        } catch (Exception e) {
            log.error("converting failed! aMap: {}, class: {}", getJsonString(aMap), t.getClass().getSimpleName(), e);
        }
        return null;
    }

replace String with another in java

Try this: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");

System.out.println(r);

This would print out "Brother How are you!"

Counter inside xsl:for-each loop

Try:

<xsl:value-of select="count(preceding-sibling::*) + 1" />

Edit - had a brain freeze there, position() is more straightforward!

How to compare only date in moment.js

The docs are pretty clear that you pass in a second parameter to specify granularity.

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

For your case you would pass 'day' as the second parameter.

How do you get the selected value of a Spinner?

You have getSelectedXXX methods from the AdapterView class from which the Spinner derives:

getSelectedItem()

getSelectedItemPosition()

getSelectedItemId()

IIS Express gives Access Denied error when debugging ASP.NET MVC

I opened my web.config file, and found and removed this section:

<authorization>
  <deny users="?" />
</authorization>

and my site came up, but there are issuues with the authentication..

Android Studio: Gradle: error: cannot find symbol variable

Another alternative to @TouchBoarder's answer above is that you may also have two layout files with the same name but for different api versions. You should delete the older my_file.xml file

my_file.xml
my_file.xml(v21)

MySQL Database won't start in XAMPP Manager-osx

It can cause because of the software you installed or may be any other software which is using the same port 3306. This 3306 port is used by the Mysql in XAMPP. Similar kind of problem I faced for Apache. I was running skype and trying to run the XAMPP but the skype uses the same port as Apache so it was not working. Then I sign out from skype then the port was free and the apache started. So you should look for the software in you laptop which is blocking or making busy this port. Free that port by closing the software and then run XAMPP and It will work.

Characters allowed in a URL

These are listed in RFC3986. See the Collected ABNF for URI to see what is allowed where and the regex for parsing/validation.

Storing a file in a database as opposed to the file system?

We made the decision to store as varbinary for http://www.freshlogicstudios.com/Products/Folders/ halfway expecting performance issues. I can say that we've been pleasantly surprised at how well it's worked out.

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

selectOneMenu ajax events

The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.

p:selectOneMenu supports change event:

<p:selectOneMenu ..>
    <p:ajax event="change" update="msgtext"
        listener="#{post.subjectSelectionChanged}" />
    <!--...-->
</p:selectOneMenu>

which triggers listener with AjaxBehaviorEvent as argument in signature:

public void subjectSelectionChanged(final AjaxBehaviorEvent event)  {...}

Handling optional parameters in javascript

If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:

function getData(id, opt){
    var data = voodooMagic(id, opt.parameters);
    if (opt.callback!=undefined)
      opt.callback.call(data);
    return data;         
}

getData(5, {parameters: "1,2,3", callback: 
    function(){for (i=0;i<=1;i--)alert("FAIL!");}
});

How to convert list data into json in java

Try like below with Gson Library.

Earlier Conversion List format were:

[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]

and here the conversion source begins.

//** Note I have created the method toString() in Product class.

//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();

//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();

//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());

//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();

//Run while loop till Product Object exists.
while(iterator.hasNext()){

    //Creating a fresh Gson Object
    Gson gs = new Gson();

    //Converting our Product Object to JsonElement 
    //Object by passing the Product Object String value (iterator.next())
    JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);

    //Creating JsonObject from JsonElement
    JsonObject jsonObject = element.getAsJsonObject();

    //Collecting the JsonObject to List
    entities.add(jsonObject);

}

//Do what you want to do with Array of JsonObject
System.out.println(entities);

Converted Json Result is :

[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]

Hope this would help many guys!

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

TL;DR

a) the method/function only reads the array argument => implicit (internal) reference
b) the method/function modifies the array argument => value
c) the method/function array argument is explicitly marked as a reference (with an ampersand) => explicit (user-land) reference

Or this:
- non-ampersand array param: passed by reference; the writing operations alter a new copy of the array, copy which is created on the first write;
- ampersand array param: passed by reference; the writing operations alter the original array.

Remember - PHP does a value-copy the moment you write to the non-ampersand array param. That's what copy-on-write means. I'd love to show you the C source of this behaviour, but it's scary in there. Better use xdebug_debug_zval().

Pascal MARTIN was right. Kosta Kontos was even more so.

Answer

It depends.

Long version

I think I'm writing this down for myself. I should have a blog or something...

Whenever people talk of references (or pointers, for that matter), they usually end up in a logomachy (just look at this thread!).
PHP being a venerable language, I thought I should add up to the confusion (even though this a summary of the above answers). Because, although two people can be right at the same time, you're better off just cracking their heads together into one answer.

First off, you should know that you're not a pedant if you don't answer in a black-and-white manner. Things are more complicated than "yes/no".

As you will see, the whole by-value/by-reference thing is very much related to what exactly are you doing with that array in your method/function scope: reading it or modifying it?

What does PHP says? (aka "change-wise")

The manual says this (emphasis mine):

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

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

As far as I can tell, when big, serious, honest-to-God programmers talk about references, they usually talk about altering the value of that reference. And that's exactly what the manual talks about: hey, if you want to CHANGE the value in a function, consider that PHP's doing "pass-by-value".

There's another case that they don't mention, though: what if I don't change anything - just read?
What if you pass an array to a method which doesn't explicitly marks a reference, and we don't change that array in the function scope? E.g.:

<?php
function readAndDoStuffWithAnArray($array) 
{
    return $array[0] + $array[1] + $array[2];
}

$x = array(1, 2, 3);

echo readAndDoStuffWithAnArray($x);

Read on, my fellow traveller.

What does PHP actually do? (aka "memory-wise")

The same big and serious programmers, when they get even more serious, they talk about "memory optimizations" in regards to references. So does PHP. Because PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting, that's why.

It wouldn't be ideal to pass HUGE arrays to various functions, and PHP to make copies of them (that's what "pass-by-value" does, after all):

<?php

// filling an array with 10000 elements of int 1
// let's say it grabs 3 mb from your RAM
$x = array_fill(0, 10000, 1); 

// pass by value, right? RIGHT?
function readArray($arr) { // <-- a new symbol (variable) gets created here
    echo count($arr); // let's just read the array
}

readArray($x);

Well now, if this actually was pass-by-value, we'd have some 3mb+ RAM gone, because there are two copies of that array, right?

Wrong. As long as we don't change the $arr variable, that's a reference, memory-wise. You just don't see it. That's why PHP mentions user-land references when talking about &$someVar, to distinguish between internal and explicit (with ampersand) ones.

Facts

So, when an array is passed as an argument to a method or function is it passed by reference?

I came up with three (yeah, three) cases:
a) the method/function only reads the array argument
b) the method/function modifies the array argument
c) the method/function array argument is explicitly marked as a reference (with an ampersand)


Firstly, let's see how much memory that array actually eats (run here):

<?php
$start_memory = memory_get_usage();
$x = array_fill(0, 10000, 1);
echo memory_get_usage() - $start_memory; // 1331840

That many bytes. Great.

a) the method/function only reads the array argument

Now let's make a function which only reads the said array as an argument and we'll see how much memory the reading logic takes:

<?php

function printUsedMemory($arr) 
{
    $start_memory = memory_get_usage();

    count($arr);       // read
    $x = $arr[0];      // read (+ minor assignment)
    $arr[0] - $arr[1]; // read

    echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}

$x = array_fill(0, 10000, 1); // this is 1331840 bytes
printUsedMemory($x);

Wanna guess? I get 80! See for yourself. This is the part that the PHP manual omits. If the $arr param was actually passed-by-value, you'd see something similar to 1331840 bytes. It seems that $arr behaves like a reference, doesn't it? That's because it is a references - an internal one.

b) the method/function modifies the array argument

Now, let's write to that param, instead of reading from it:

<?php

function printUsedMemory($arr)
{
    $start_memory = memory_get_usage();

    $arr[0] = 1; // WRITE!

    echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}

$x = array_fill(0, 10000, 1);
printUsedMemory($x);

Again, see for yourself, but, for me, that's pretty close to being 1331840. So in this case, the array is actually being copied to $arr.

c) the method/function array argument is explicitly marked as a reference (with an ampersand)

Now let's see how much memory a write operation to an explicit reference takes (run here) - note the ampersand in the function signature:

<?php

function printUsedMemory(&$arr) // <----- explicit, user-land, pass-by-reference
{
    $start_memory = memory_get_usage();

    $arr[0] = 1; // WRITE!

    echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}

$x = array_fill(0, 10000, 1);
printUsedMemory($x);

My bet is that you get 200 max! So this eats approximately as much memory as reading from a non-ampersand param.

BSTR to std::string (std::wstring) and vice versa

You could also do this

#include <comdef.h>

BSTR bs = SysAllocString("Hello");
std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free

or std::string if you prefer

EDIT: if your original string contains multiple embedded \0 this approach will not work.

Iterating over dictionaries using 'for' loops

If you are looking for a clear and visual example:

cat  = {'name': 'Snowy', 'color': 'White' ,'age': 14}
for key , value in cat.items():
   print(key, ': ', value)

Result:

name:  Snowy
color:  White
age:  14

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Print text in Oracle SQL Developer SQL Worksheet window

enter image description here

for simple comments:

set serveroutput on format wrapped;
begin
    DBMS_OUTPUT.put_line('simple comment');
end;
/

-- do something

begin
    DBMS_OUTPUT.put_line('second simple comment');
end;
/

you should get:

anonymous block completed
simple comment

anonymous block completed
second simple comment

if you want to print out the results of variables, here's another example:

set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
    DBMS_OUTPUT.put_line(a_comment);
end;

/

-- do something


declare
a_comment VARCHAR2(200) :='comment';
begin
    DBMS_OUTPUT.put_line(a_comment || 2);
end;

your output should be:

anonymous block completed
first comment

anonymous block completed
comment2

How to set css style to asp.net button?

You can use CssClass attribute and pass a value as a css class name

<asp:Button CssClass="button" Text="Submit" runat="server"></asp:Button>` 

.button
{
     //write more styles
}

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

TypeError: 'str' object is not callable (Python)

I had the same error. In my case wasn't because of a variable named str. But because I named a function with a str parameter and the variable the same.

same_name = same_name(var_name: str)

I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (same_name =) as a call to the function and detects that the str parameter is not present, so it's missing, then it throws that error.

When do you use the "this" keyword?

I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

Adding a regression line on a ggplot

As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.

You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data).

It would look like this:

# read dataset
df = mtcars

# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)

# save predictions of the model in the new data frame 
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)

# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))

Multiple LR

# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_smooth(method = "lm", se = FALSE)

Single LR

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

The following should unlock a locked working copy (tested on svn client version 1.6.11 and elipse version: Mars.2 Release (4.5.2))

step 1: (go to working copy directory) $cd working_copy_dir

step 2: (connect to svn sqlite database) $sqlite3 .svn/wc.db

step 3: (delete all records from table WC_LOCK) sqlite> delete from WC_LOCK;

step 4: (disconnect from sqlite 3 database) sqlite>ctrl + d

step 5: (from eclipse) right click on your working copy, then click Team -> Refresh/Cleanup

File input 'accept' attribute - is it useful?

It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.

Run C++ in command prompt - Windows

  1. Download MinGW form : https://sourceforge.net/projects/mingw-w64/
  2. use notepad++ to write the C++ source code.
  3. using command line change the directory/folder where the source code is saved(using notepad++)
  4. compile: g++ file_name.cpp -o file_name.exe
  5. run the executable: file_name.exe

regex error - nothing to repeat

It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;

import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)

this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...

How can I determine if an image has loaded, using Javascript/jQuery?

This function checks if an image is loaded based on having measurable dimensions. This technique is useful if your script is executing after some of the images have already been loaded.

imageLoaded = function(node) {
    var w = 'undefined' != typeof node.clientWidth ? node.clientWidth : node.offsetWidth;
    var h = 'undefined' != typeof node.clientHeight ? node.clientHeight : node.offsetHeight;
    return w+h > 0 ? true : false;
};

How do you run CMD.exe under the Local System Account?

Found an answer here which seems to solve the problem by adding /k start to the binPath parameter. So that would give you:

sc create testsvc binpath= "cmd /K start" type= own type= interact

However, Ben said that didn't work for him and when I tried it on Windows Server 2008 it did create the cmd.exe process under local system, but it wasn't interactive (I couldn't see the window).

I don't think there is an easy way to do what you ask, but I'm wondering why you're doing it at all? Are you just trying to see what is happening when you run your service? Seems like you could just use logging to determine what is happening instead of having to run the exe as local system...

File name without extension name VBA

This gets the file type as from the last character (so avoids the problem with dots in file names)

Function getFileType(fn As String) As String

''get last instance of "." (full stop) in a filename then returns the part of the filename starting at that dot to the end
Dim strIndex As Integer
Dim x As Integer
Dim myChar As String

strIndex = Len(fn)
For x = 1 To Len(fn)

    myChar = Mid(fn, strIndex, 1)

    If myChar = "." Then
        Exit For
    End If

    strIndex = strIndex - 1

Next x

getFileType = UCase(Mid(fn, strIndex, Len(fn) - x + 1))

End Function

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

After several tries i found htmlentities function works.

$value = htmlentities($value)

AWS S3 CLI - Could not connect to the endpoint URL

If none of solutions given above works,also check your permissions and firewall settings. In my case adding proxy environment variables did the job.

For Linux or mac

$ export HTTP_PROXY=http://<YOUR PROXY IP>:<PORT>

$ export HTTPS_PROXY=http://<YOUR PROXY IP>:<PORT>

For Windows

set HTTP_PROXY=http://<YOUR PROXY IP>:<PORT>

set HTTPS_PROXY=http://<YOUR PROXY IP>:<PORT> aws cli Windows

enter image description here

What does the "@" symbol do in SQL?

publish data where stoloc = 'AB143' 
|
[select prtnum where stoloc = @stoloc]

This is how the @ works.

How do you migrate an IIS 7 site to another server?

MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool

To create a package, run the following command (replace Default Web Site with your web site name):

msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log

To restore the package, run the following command:

msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log

How to execute UNION without sorting? (SQL)

You can do something like this.

Select distinct name from  (SELECT r.name FROM outsider_role_mapping orm1 
    union all
SELECT r.name FROM user_role_mapping orm2
) tmp;

Loading custom configuration files

the articles posted by Ricky are very good, but unfortunately they don't answer your question.

To solve your problem you should try this piece of code:

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

If need to access a value within the config you can use the index operator:

config.AppSettings.Settings["test"].Value;

Store text file content line by line into array

When you do str = in.readLine()) != null you read one line into str variable and if it's not null execute the while block. You do not need to read the line one more time in arr[i] = in.readLine();. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;

List<String> output = new LinkedList<String>();

while((str = in.readLine()) != null){
    output.add(str);
}

String[] arr = output.toArray(new String[output.size()]);

How to have multiple CSS transitions on an element?

.nav a {
    transition: color .2s, text-shadow .2s;
}

Angular js init ng-model from default values

As others pointed out, it is not good practice to initialize data on views. Initializing data on Controllers, however, is recommended. (see http://docs.angularjs.org/guide/controller)

So you can write

<input name="card[description]" ng-model="card.description">

and

$scope.card = { description: 'Visa-4242' };

$http.get('/getCardInfo.php', function(data) {
   $scope.card = data;
});

This way the views do not contain data, and the controller initializes the value while the real values are being loaded.

Understanding the Gemfile.lock file

in regards to the exclamation mark I just found out it's on gems fetched via :git, e.g.

gem "foo", :git => "[email protected]:company/foo.git"

How to change button color with tkinter

When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

bash, extract string before a colon

This works for me you guys can try it out

INPUT='ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash'
SUBSTRING=$(echo $INPUT| cut -d: -f1)
echo $SUBSTRING

What is the best way to create a string array in python?

In Python, the tendency is usually that one would use a non-fixed size list (that is to say items can be appended/removed to it dynamically). If you followed this, there would be no need to allocate a fixed-size collection ahead of time and fill it in with empty values. Rather, as you get or create strings, you simply add them to the list. When it comes time to remove values, you simply remove the appropriate value from the string. I would imagine you can probably use this technique for this. For example (in Python 2.x syntax):

>>> temp_list = []
>>> print temp_list
[]
>>> 
>>> temp_list.append("one")
>>> temp_list.append("two")
>>> print temp_list
['one', 'two']
>>> 
>>> temp_list.append("three")
>>> print temp_list
['one', 'two', 'three']
>>> 

Of course, some situations might call for something more specific. In your case, a good idea may be to use a deque. Check out the post here: Python, forcing a list to a fixed size. With this, you can create a deque which has a fixed size. If a new value is appended to the end, the first element (head of the deque) is removed and the new item is appended onto the deque. This may work for what you need, but I don't believe this is considered the "norm" for Python.

How to use Jackson to deserialise an array of objects

you could also create a class which extends ArrayList:

public static class MyList extends ArrayList<Myclass> {}

and then use it like:

List<MyClass> list = objectMapper.readValue(json, MyList.class);

How do I pass an object from one activity to another on Android?

You can create a subclass of Application and store your shared object there. The Application object should exist for the lifetime of your app as long as there is some active component.

From your activities, you can access the application object via getApplication().

What is the meaning of @_ in Perl?

Usually, you expand the parameters passed to a sub using the @_ variable:

sub test{
  my ($a, $b, $c) = @_;
  ...
}

# call the test sub with the parameters
test('alice', 'bob', 'charlie');

That's the way claimed to be correct by perlcritic.

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

If is VSCode see the workspace. If you are in other workspace this error can rise

NULL vs nullptr (Why was it replaced?)

nullptr is always a pointer type. 0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

f(int);
f(foo *);

How to get a table cell value using jQuery?

This works

$(document).ready(function() {
    for (var row = 0; row < 3; row++) {
        for (var col = 0; col < 3; col++) {
            $("#tbl").children().children()[row].children[col].innerHTML = "H!";
        }
    }
});