Programs & Examples On #Multiple inheritance

A feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass or base class.

How does Python's super() work with multiple inheritance?

This is to how I solved to issue of having multiple inheritance with different variables for initialization and having multiple MixIns with the same function call. I had to explicitly add variables to passed **kwargs and add a MixIn interface to be an endpoint for super calls.

Here A is an extendable base class and B and C are MixIn classes both who provide function f. A and B both expect parameter v in their __init__ and C expects w. The function f takes one parameter y. Q inherits from all three classes. MixInF is the mixin interface for B and C.


class A(object):
    def __init__(self, v, *args, **kwargs):
        print "A:init:v[{0}]".format(v)
        kwargs['v']=v
        super(A, self).__init__(*args, **kwargs)
        self.v = v


class MixInF(object):
    def __init__(self, *args, **kwargs):
        print "IObject:init"
    def f(self, y):
        print "IObject:y[{0}]".format(y)


class B(MixInF):
    def __init__(self, v, *args, **kwargs):
        print "B:init:v[{0}]".format(v)
        kwargs['v']=v
        super(B, self).__init__(*args, **kwargs)
        self.v = v
    def f(self, y):
        print "B:f:v[{0}]:y[{1}]".format(self.v, y)
        super(B, self).f(y)


class C(MixInF):
    def __init__(self, w, *args, **kwargs):
        print "C:init:w[{0}]".format(w)
        kwargs['w']=w
        super(C, self).__init__(*args, **kwargs)
        self.w = w
    def f(self, y):
        print "C:f:w[{0}]:y[{1}]".format(self.w, y)
        super(C, self).f(y)


class Q(C,B,A):
    def __init__(self, v, w):
        super(Q, self).__init__(v=v, w=w)
    def f(self, y):
        print "Q:f:y[{0}]".format(y)
        super(Q, self).f(y)

Does C# support multiple inheritance?

Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.

interface A { }
interface B { }
class Base { }
class AnotherClass { }

Possible ways to inherit:

class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)

This is not legal:

class SomeClass : Base, AnotherClass { }

What does 'super' do in Python?

Doesn't all of this assume that the base class is a new-style class?

class A:
    def __init__(self):
        print("A.__init__()")

class B(A):
    def __init__(self):
        print("B.__init__()")
        super(B, self).__init__()

Will not work in Python 2. class A must be new-style, i.e: class A(object)

Can a normal Class implement multiple interfaces?

In a word - yes. Actually, many classes in the JDK implement multiple interfaces. E.g., ArrayList implements List, RandomAccess, Cloneable, and Serializable.

Multiple Inheritance in C#

If X inherits from Y, that has two somewhat orthogonal effects:

  1. Y will provide default functionality for X, so the code for X only has to include stuff which is different from Y.
  2. Almost anyplace a Y would be expected, an X may be used instead.

Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).

What is a mixin, and why are they useful?

Maybe an example from ruby can help:

You can include the mixin Comparable and define one function "<=>(other)", the mixin provides all those functions:

<(other)
>(other)
==(other)
<=(other)
>=(other)
between?(other)

It does this by invoking <=>(other) and giving back the right result.

"instance <=> other" returns 0 if both objects are equal, less than 0 if instance is bigger than other and more than 0 if other is bigger.

Can one class extend two classes?

Java doesn't support multiple inheritance. You can implement multiple interfaces, but not extend multiple classes.

Can an interface extend multiple interfaces in Java?

Yes, you can do it. An interface can extend multiple interfaces, as shown here:

interface Maininterface extends inter1, inter2, inter3 {  
  // methods
}

A single class can also implement multiple interfaces. What if two interfaces have a method defining the same name and signature?

There is a tricky point:

interface A {
    void test();
}

interface B {
    void test();
}

class C implements A, B {

    @Override
    public void test() {

    }     

}

Then single implementation works for both :).

Read my complete post here:

http://codeinventions.blogspot.com/2014/07/can-interface-extend-multiple.html

Class extending more than one class Java?

Java didn't provide multiple inheritance.
When you say A extends B then it means that A extends B and B extends Object.
It doesn't mean A extends B, Object.

class A extends Object
class B extends A

Java Multiple Inheritance

There are two fundamental approaches to combining objects together:

  • The first is Inheritance. As you have already identified the limitations of inheritance mean that you cannot do what you need here.
  • The second is Composition. Since inheritance has failed you need to use composition.

The way this works is that you have an Animal object. Within that object you then add further objects that give the properties and behaviors that you require.

For example:

  • Bird extends Animal implements IFlier
  • Horse extends Animal implements IHerbivore, IQuadruped
  • Pegasus extends Animal implements IHerbivore, IQuadruped, IFlier

Now IFlier just looks like this:

 interface IFlier {
     Flier getFlier();
 }

So Bird looks like this:

 class Bird extends Animal implements IFlier {
      Flier flier = new Flier();
      public Flier getFlier() { return flier; }
 }

Now you have all the advantages of Inheritance. You can re-use code. You can have a collection of IFliers, and can use all the other advantages of polymorphism, etc.

However you also have all the flexibility from Composition. You can apply as many different interfaces and composite backing class as you like to each type of Animal - with as much control as you need over how each bit is set up.

Strategy Pattern alternative approach to composition

An alternative approach depending on what and how you are doing is to have the Animal base class contain an internal collection to keep the list of different behaviors. In that case you end up using something closer to the Strategy Pattern. That does give advantages in terms of simplifying the code (for example Horse doesn't need to know anything about Quadruped or Herbivore) but if you don't also do the interface approach you lose a lot of the advantages of polymorphism, etc.

Multiple inheritance for an anonymous class

Anonymous classes always extend superclass or implements interfaces. for example:

button.addActionListener(new ActionListener(){ // ActionListener is an interface
    public void actionPerformed(ActionEvent e){
    }
});

Moreover, although anonymous class cannot implement multiple interfaces, you can create an interface that extends other interface and let your anonymous class to implement it.

Creating NSData from NSString in Swift

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)

Finding the position of bottom of a div with jquery

var top = ($('#bottom').position().top) + ($('#bottom').height());

How do you get the file size in C#?

If you have already a file path as input, this is the code you need:

long length = new System.IO.FileInfo(path).Length;

What is "loose coupling?" Please provide examples

Many integrated products (especially by Apple) such as iPods, iPads are a good example of tight coupling: once the battery dies you might as well buy a new device because the battery is soldered fixed and won't come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.

The same goes for software development: it is generally (much) better to have loosely coupled code to facilitate extension and replacement (and to make individual parts easier to understand). But, very rarely, under special circumstances tight coupling can be advantageous because the tight integration of several modules allows for better optimisation.

Way to get all alphabetic chars in an array in PHP?

Try this :

function missingCharacter($list) {

        // Create an array with a range from array minimum to maximu
        $newArray = range(min($list), max($list));

        // Find those elements that are present in the $newArray but not in given $list
        return array_diff($newArray, $list);
    }
print_r(missCharacter(array('a','b','d','g')));

Unable to allocate array with shape and data type

Sometimes, this error pops up because of the kernel has reached its limit. Try to restart the kernel redo the necessary steps.

Entity Framework: There is already an open DataReader associated with this Command

A good middle-ground between enabling MARS and retrieving the entire result set into memory is to retrieve only IDs in an initial query, and then loop through the IDs materializing each entity as you go.

For example (using the "Blog and Posts" sample entities as in this answer):

using (var context = new BlogContext())
{
    // Get the IDs of all the items to loop through. This is
    // materialized so that the data reader is closed by the
    // time we're looping through the list.
    var blogIds = context.Blogs.Select(blog => blog.Id).ToList();

    // This query represents all our items in their full glory,
    // but, items are only materialized one at a time as we
    // loop through them.
    var blogs =
        blogIds.Select(id => context.Blogs.First(blog => blog.Id == id));

    foreach (var blog in blogs)
    {
        this.DoSomethingWith(blog.Posts);

        context.SaveChanges();
    }
}

Doing this means that you only pull a few thousand integers into memory, as opposed to thousands of entire object graphs, which should minimize memory usage while enabling you to work item-by-item without enabling MARS.

Another nice benefit of this, as seen in the sample, is that you can save changes as you loop through each item, instead of having to wait until the end of the loop (or some other such workaround), as would be needed even with MARS enabled (see here and here).

What is causing this error - "Fatal error: Unable to find local grunt"

If you already have a file package.json in the project and it contains grunt in dependency,

  "devDependencies": {
    "grunt": "~0.4.0",

Then you can run npm install to resolve the issue

How to get the last character of a string in a shell?

expr $str : '.*\(.\)'

Or

echo ${str: -1}

The type arguments for method cannot be inferred from the usage

As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.

Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T generic type parameter.

interface ISignatur<T>
{
    Type Type { get; }
}

interface IAccess<T>
{
    ISignatur<T> Signature { get; }
    T Value { get; set; }
}

class Signatur : ISignatur<bool>
{
    public Type Type
    {
        get { return typeof(bool); }
    }
}

class ServiceGate
{
    public IAccess<T> Get<T>(ISignatur<T> sig)
    {
        throw new NotImplementedException();
    }
}

static class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        var access = service.Get(new Signatur());
    }
}

package javax.mail and javax.mail.internet do not exist

You need the javax.mail.jar library. Download it from the Java EE JavaMail GitHub page and add it to your IntelliJ project:

  1. Download javax.mail.jar
  2. Navigate to File > Project Structure...
  3. Go to the Libraries tab
  4. Click on the + button (Add New Project Library)
  5. Browse to the javax.mail.jar file
  6. Click OK to apply the changes

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I tried it on XP and it doesn't work if the PC is set to International time yyyy-M-d. Place a breakpoint on the line and before it is processed change the date string to use '-' in place of the '/' and you'll find it works. It makes no difference whether you have the CultureInfo or not. Seems strange to be able specify an expercted format only to have the separator ignored.

how to get the current working directory's absolute path from irb

This will give you the working directory of the current file.

File.dirname(__FILE__)

Example:

current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"

result: "/Users/nemrow/SITM/folder1/folder2"

pytest cannot import module while python can

Another special case:

I had the problem using tox. So my program ran fine, but unittests via tox kept complaining. After installing packages (needed for the program) you need to additionally specify the packages used in the unittests in the tox.ini

[testenv]
deps =
    package1
    package2 
...

Generating all permutations of a given string

This can be done iteratively by simply inserting each letter of the string in turn in all locations of the previous partial results.

We start with [A], which with B becomes [BA, AB], and with C, [CBA, BCA, BAC, CAB, etc].

The running time would be O(n!), which, for the test case ABCD, is 1 x 2 x 3 x 4.

In the above product, the 1 is for A, the 2 is for B, etc.

Dart sample:

void main() {

  String insertAt(String a, String b, int index)
  {
    return a.substring(0, index) + b + a.substring(index);
  }

  List<String> Permute(String word) {

    var letters = word.split('');

    var p_list = [ letters.first ];

    for (var c in letters.sublist(1)) {

      var new_list = [ ];

      for (var p in p_list)
        for (int i = 0; i <= p.length; i++)
          new_list.add(insertAt(p, c, i));

      p_list = new_list;
    }

    return p_list;
  }

  print(Permute("ABCD"));

}

Performing user authentication in Java EE / JSF using j_security_check

The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.

Updating is quite straightforward:

glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update

How can I disable inherited css styles?

Give the div you don't want him inheriting the property background too.

SystemError: Parent module '' not loaded, cannot perform relative import

I had the same problem and I solved it by using an absolute import instead of a relative one.

for example in your case, you will write something like this:

from app.mymodule import myclass

You can see in the documentation.

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

How to parse JSON string in Typescript

You can additionally use libraries that perform type validation of your json, such as Sparkson. They allow you to define a TypeScript class, to which you'd like to parse your response, in your case it could be:

import { Field } from "sparkson";
class Response {
   constructor(
      @Field("name") public name: string,
      @Field("error") public error: boolean
   ) {}
}

The library will validate if the required fields are present in the JSON payload and if their types are correct. It can also do a bunch of validations and conversions.

Find duplicate records in MySQL

SELECT date FROM logs group by date having count(*) >= 2

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

how to release localhost from Error: listen EADDRINUSE

When you get an error Error: listen EADDRINUSE,

Try running the following shell commands:

netstat -a -o | grep 8080
taskkill /F /PID 6204

I greped for 8080, because I know my server is running on port 8080. (static tells me when I start it: 'serving "." at http://127.0.0.1:8080'.) You might have to search for a different port.

How to dismiss ViewController in Swift?

I have a solution for your problem. Please try this code to dismiss the view controller if you present the view using modal:

Swift 3:

self.dismiss(animated: true, completion: nil)

OR

If you present the view using "push" segue

self.navigationController?.popViewController(animated: true)

bind/unbind service example (android)

Add these methods to your Activity:

private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        myServiceBinder = ((MyService.MyBinder) binder).getService();
        Log.d("ServiceConnection","connected");
        showServiceData();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
};

public Handler myHandler = new Handler() {
    public void handleMessage(Message message) {
        Bundle data = message.getData();
    }
};

public void doBindService() {
    Intent intent = null;
    intent = new Intent(this, BTService.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(myHandler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override
protected void onResume() {

    Log.d("activity", "onResume");
    if (myService == null) {
        doBindService();
    }
    super.onResume();
}

@Override
protected void onPause() {
    //FIXME put back

    Log.d("activity", "onPause");
    if (myService != null) {
        unbindService(myConnection);
        myService = null;
    }
    super.onPause();
}

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;

@Override
public IBinder onBind(Intent arg0) {
    Bundle extras = arg0.getExtras();
    Log.d("service","onBind");
    // Get messager from the Activity
    if (extras != null) {
        Log.d("service","onBind with extra");
        outMessenger = (Messenger) extras.get("MESSENGER");
    }
    return mBinder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

After you defined these methods you can reach the methods of your service at your Activity:

private void showServiceData() {  
    myServiceBinder.myMethod();
}

and finally you can start your service when some event occurs like _BOOT_COMPLETED_

public class MyReciever  extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Intent service = new Intent(context, myService.class);
            context.startService(service);
        }
    }
}

note that when starting a service the onCreate() and onStartCommand() is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:

<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

SQL Select between dates

Or you can cast your string to Date format with date function. Even the date is stored as TEXT in the DB. Like this (the most workable variant):

SELECT * FROM test WHERE date(date) 
BETWEEN date('2011-01-11') AND date('2011-8-11')

SELECT where row value contains string MySQL

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

but it's not suggested. use PDO

How can I get the selected VALUE out of a QCombobox?

I'm astonished that there isn't an activated signal and have the same problem. I solved it by making a subclass of QComboBox. I think it's better to avoid having to directly access the object and call its functions because that means more tight coupling and goes against Qt's philosophy. So here's the class I made that works for me.

class SmartComboBox : public QComboBox {

    Q_OBJECT

private slots:

    void triggerVariantActivated(int index);

public:

    SmartComboBox(QWidget *parent);

signals:

    void activated(const QVariant &);

};

And the implementation

void SmartComboBox::triggerVariantActivated(int index)
{
    activated(itemData(index));
}

SmartComboBox::SmartComboBox(QWidget *parent)
:QComboBox(parent)
{
    connect(this, SIGNAL(activated(int)), this, SLOT(triggerVariantActivated(int)));
}

How to change the color of winform DataGridview header?

dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

Using Jquery Ajax to retrieve data from Mysql

Please make sure your $row[1] , $row[2] contains correct value, we do assume here that 1 = Name , and 2 here is your Address field ?

Assuming you have correctly fetched your records from your Records.php, You can do something like this:

$(document).ready(function()
{
    $('#getRecords').click(function()
    {
        var response = '';
        $.ajax({ type: 'POST',   
                 url: "Records.php",   
                 async: false,
                 success : function(text){
                               $('#table1').html(text);
                           }
           });
    });

}

In your HTML

<table id="table1"> 
    //Let jQuery AJAX Change This Text  
</table>
<button id='getRecords'>Get Records</button>

A little note:

Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions are no longer encouraged..

How to detect chrome and safari browser (webkit)

Many answers here. Here is my first consideration.

Without JavaScript, including the possibility Javascript is initially disabled by the user in his browser for security purposes, to be white listed by the user if the user trusts the site, DOM will not be usable because Javascript is off.

Programmatically, you are left with a backend server-side or frontend client-side consideration.

With the backend, you can use common denominator HTTP "User-Agent" request header and/or any possible proprietary HTTP request header issued by the browser to output browser specific HTML stuff.

With the client site, you may want to enforce Javascript to allow you to use DOM. If so, then you probably will want to first use the following in your HTML page:

<noscript>This site requires Javascript. Please turn on Javascript.</noscript>

While we are heading to a day with every web coder will be dependent on Javascript in some way (or not), today, to presume every user has javascript enabled would be design and product development QA mistake.

I've seen far too may sites who end up with a blank page or the site breaks down because it presumed every user has javascript enabled. No. For security purposes, they may have Javascript initially off and some browsers, like Chrome, will allow the user to white list the web site on a domain by domain basis. Edge is the only browser I am aware of where Microsoft made the decision to completely disable the user's ability to turn off Javascript. Edge doesn't offer a white listing concept hence it is one reason I don't personally use Edge.

Using the tag is a simple way to inform the user your site won't work without Javascript. Once the user turns it on and refreshes/reload the page, DOM is now available to use the techniques cited by the thread replies to detect chrome vs safari.

Ironically, I got here because I was updating by platform and google the same basic question; chrome vs sarafi. I didn't know Chrome creates a DOM object named "chrome" which is really all you need to detect "chrome" vs everything else.

var isChrome = typeof(chrome) === "object";

If true, you got Chrome, if false, you got some other browser.

Check to see if Safari create its own DOM object as well, if so, get the object name and do the same thing, for example:

var isSafari = (typeof(safari) === "object");

Hope these tips help.

How to change the server port from 3000?

You can change it inside bs-config.json file as mentioned in the docs https://github.com/johnpapa/lite-server#custom-configuration

For example,

{
  "port": 8000,
  "files": ["./src/**/*.{html,htm,css,js}"],
  "server": { "baseDir": "./src" }
}

How do I add an existing Solution to GitHub from Visual Studio 2013

My problem is that when i use https for the remote URL, it doesn't work, so I use http instead. This allows me to publish/sync with GitHub from Team Explorer instantly.

Android: I lost my android key store, what should I do?

No, there is no chance to do that. You just learned how important a backup can be.

How to catch and print the full exception traceback without halting/exiting the program?

traceback.format_exception

If you only have the exception object, you can get the traceback as a string from any point of the code in Python 3 with:

import traceback

''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))

Full example:

#!/usr/bin/env python3

import traceback

def f():
    g()

def g():
    raise Exception('asdf')

try:
    g()
except Exception as e:
    exc = e

tb_str = ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
print(tb_str)

Output:

Traceback (most recent call last):
  File "./main.py", line 12, in <module>
    g()
  File "./main.py", line 9, in g
    raise Exception('asdf')
Exception: asdf

Documentation: https://docs.python.org/3.7/library/traceback.html#traceback.format_exception

See also: Extract traceback info from an exception object

Tested in Python 3.7.3.

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

Reading numbers from a text file into an array in C

There are two problems in your code:

  • the return value of scanf must be checked
  • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, j;
    short unsigned digitArray[16];
    i = 0;
    while (
        i != sizeof(digitArray) / sizeof(digitArray[0])
     && 1 == scanf("%1hu", digitArray + i)
    ) {
        i++;
    }
    for (j = 0; j != i; j++) {
        printf("%hu\n", digitArray[j]);
    }
    return 0;
}

CSS3 100vh not constant in mobile browser

I just found a web app i designed has this issue with iPhones and iPads, and found an article suggesting to solve it using media queries targeted at specific Apple devices.

I don't know whether I can share the code from that article here, but the address is this: http://webdesignerwall.com/tutorials/css-fix-for-ios-vh-unit-bug

Quoting the article: "just match the element height with the device height using media queries that targets the older versions of iPhone and iPad resolution."

They added just 6 media queries to adapt full height elements, and it should work as it is fully CSS implemented.

Edit pending: I'm unable to test it right now, but I will come back and report my results.

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

Hosting a Maven repository on github

The best solution I've been able to find consists of these steps:

  1. Create a branch called mvn-repo to host your maven artifacts.
  2. Use the github site-maven-plugin to push your artifacts to github.
  3. Configure maven to use your remote mvn-repo as a maven repository.

There are several benefits to using this approach:

  • Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
  • Unlike some other proposed solutions, it doesn't conflict with your gh-pages if you're using them.
  • Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would

The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let's patch into that mechanism for this solution.

First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml:

<distributionManagement>
    <repository>
        <id>internal.repo</id>
        <name>Temporary Staging Repository</name>
        <url>file://${project.build.directory}/mvn-repo</url>
    </repository>
</distributionManagement>

<plugins>
    <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
            <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
        </configuration>
    </plugin>
</plugins>

Now try running mvn clean deploy. You'll see that it deployed your maven repository to target/mvn-repo. The next step is to get it to upload that directory to GitHub.

Add your authentication information to ~/.m2/settings.xml so that the github site-maven-plugin can push to GitHub:

<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>YOUR-USERNAME</username>
      <password>YOUR-PASSWORD</password>
    </server>
  </servers>
</settings>

(As noted, please make sure to chmod 700 settings.xml to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)

Then tell the GitHub site-maven-plugin about the new server you just configured by adding the following to your pom:

<properties>
    <!-- github server corresponds to entry in ~/.m2/settings.xml -->
    <github.global.server>github</github.global.server>
</properties>

Finally, configure the site-maven-plugin to upload from your temporary staging repo to your mvn-repo branch on Github:

<build>
    <plugins>
        <plugin>
            <groupId>com.github.github</groupId>
            <artifactId>site-maven-plugin</artifactId>
            <version>0.11</version>
            <configuration>
                <message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
                <noJekyll>true</noJekyll>                                  <!-- disable webpage processing -->
                <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
                <branch>refs/heads/mvn-repo</branch>                       <!-- remote branch name -->
                <includes><include>**/*</include></includes>
                <repositoryName>YOUR-REPOSITORY-NAME</repositoryName>      <!-- github repo name -->
                <repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner>    <!-- github username  -->
            </configuration>
            <executions>
              <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
              <execution>
                <goals>
                  <goal>site</goal>
                </goals>
                <phase>deploy</phase>
              </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The mvn-repo branch does not need to exist, it will be created for you.

Now run mvn clean deploy again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO] 
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------

Visit github.com in your browser, select the mvn-repo branch, and verify that all your binaries are now there.

enter image description here

Congratulations!

You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy.

There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:

<repositories>
    <repository>
        <id>YOUR-PROJECT-NAME-mvn-repo</id>
        <url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Now any project that requires your jar files will automatically download them from your github maven repository.

Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.

urllib2.HTTPError: HTTP Error 403: Forbidden

This will work in Python 3

import urllib.request

user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,} 

request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need

Calling Member Functions within Main C++

On an informal note, you can also call non-static member functions on temporaries:

MyClass().printInformation();

(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

So I had a similar situation with the same error. I forgot I changed the compatibility mode on my dev machine and I had a console.log command in my javascript as well. I changed compatibility mode back in IE, and removed the console.log command. No more issue.

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

what is the use of Eval() in asp.net

IrishChieftain didn't really address the question, so here's my take:

eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

How do I translate an ISO 8601 datetime string into a Python datetime object?

You should keep an eye on the timezone information, as you might get into trouble when comparing non-tz-aware datetimes with tz-aware ones.

It's probably the best to always make them tz-aware (even if only as UTC), unless you really know why it wouldn't be of any use to do so.

#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------

utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------

def to_iso8601(when=None, tz=BERLIN):
  if not when:
    when = datetime.datetime.now(tz)
  if not when.tzinfo:
    when = tz.localize(when)
  _when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
  return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------

def from_iso8601(when=None, tz=BERLIN):
  _when = dateutil.parser.parse(when)
  if not _when.tzinfo:
    _when = tz.localize(_when)
  return _when
#-----------------------------------------------

How to add more than one machine to the trusted hosts list using winrm

I prefer to work with the PSDrive WSMan:\.

Get TrustedHosts

Get-Item WSMan:\localhost\Client\TrustedHosts

Set TrustedHosts

provide a single, comma-separated, string of computer names

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'

or (dangerous) a wild-card

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'

to append to the list, the -Concatenate parameter can be used

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate

Make var_dump look pretty

I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.

<?php
function debug_display($var,$show = false) {
    if($show) { $dis = 'block'; }else { $dis = 'none'; }
    ob_start();
    echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
        <pre>';
    if(is_bool($var)) {
        echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
    }else {
        if(FALSE == empty($var) && $var !== NULL && $var != '0') {
            if(is_array($var)) {
                echo "Number of Indexes: " . count($var) . "\n";
                print_r($var);
            } elseif(is_object($var)) {
                print_r($var);
            } elseif(@is_file($var)){
                $stat = stat($var);
                $perm = substr(sprintf('%o',$stat['mode']), -4);
                $accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
                $modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
                $change = gmdate('Y/m/d H:i:s', $stat['ctime']);
                echo "
    file path : $var
    file size : {$stat['size']} Byte
    device number : {$stat['dev']}
    permission : {$perm}
    last access time was : {$accesstime}
    last modified time was : {$modification}
    last change time was : {$change}
    ";
            }elseif(is_string($var)) {
                print_r(htmlentities(str_replace("\t", '  ', $var)));
            }  else {
                print_r($var);
            }
        }else {
            echo 'Undefined';
        }
    }
    echo '</pre>
    </div>';
    $output = ob_get_contents();
    ob_end_clean();
    echo $output;
    unset($output);
}

Call int() function on every list element?

This is what list comprehensions are for:

numbers = [ int(x) for x in numbers ]

Dockerfile copy keep subdirectory structure

To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.

COPY ./files/. /files/

Self Join to get employee manager name

create table abc(emp_ID int, manager varchar(20) , manager_id int)

emp_ID  manager manager_id
1       abc     NULL
2       def     1
3       ghi     2
4       klm     3
5       def1    1
6       ghi1    2
7       klm1    3

select a.emp_ID , a.manager emp_name,b.manager manager_name
from abc a
left join abc b
on a.manager_id = b.emp_ID

Result:
emp_ID  emp_name  manager_name
1       abc       NULL
2       def       abc
3       ghi       def
4       klm       ghi
5       def1      abc
6       ghi1      def
7       klm1      ghi

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

Where to download Microsoft Visual c++ 2003 redistributable

Another way:

using Unofficial (Full Size: 26.1 MB) VC++ All in one that contained your needed files:

http://www.wincert.net/forum/topic/9790-aio-microsoft-visual-bcfj-redistributable-x86x64/

OR (Smallest 5.10 MB) Microsoft Visual Basic/C++ Runtimes 1.1.1 RePacked Here:

http://www.wincert.net/forum/topic/9794-bonus-microsoft-visual-basicc-runtimes-111/

Psexec "run as (remote) admin"

Use psexec -s

The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.

How to evaluate http response codes from bash/shell script?

With netcat and awk you can handle the server response manually:

if netcat 127.0.0.1 8080 <<EOF | awk 'NR==1{if ($2 == "500") exit 0; exit 1;}'; then
GET / HTTP/1.1
Host: www.example.com

EOF

    apache2ctl restart;
fi

Remove plot axis values

you can also put labels inside plot:

plot(spline(sub$day, sub$counts), type ='l', labels = FALSE)

you'll get a warning. i think this is because labels is actually a parameter that's being passed down to a subroutine that plot runs (axes?). the warning will pop up because it wasn't directly a parameter of the plot function.

Maven Installation OSX Error Unsupported major.minor version 51.0

I solved it putting a old version of maven (2.x), using brew:

brew uninstall maven
brew tap homebrew/versions 
brew install maven2

Format date to MM/dd/yyyy in JavaScript

ISO compliant dateString

If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:

const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString);                 // {object Date}

from here you can extract the desired values by using Date Getters:

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Non-standard date string

If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);

// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s);  // {object Date}


D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

How to insert pandas dataframe via mysqldb into database?

Andy Hayden mentioned the correct function (to_sql). In this answer, I'll give a complete example, which I tested with Python 3.5 but should also work for Python 2.7 (and Python 3.x):

First, let's create the dataframe:

# Create dataframe
import pandas as pd
import numpy as np

np.random.seed(0)
number_of_samples = 10
frame = pd.DataFrame({
    'feature1': np.random.random(number_of_samples),
    'feature2': np.random.random(number_of_samples),
    'class':    np.random.binomial(2, 0.1, size=number_of_samples),
    },columns=['feature1','feature2','class'])

print(frame)

Which gives:

   feature1  feature2  class
0  0.548814  0.791725      1
1  0.715189  0.528895      0
2  0.602763  0.568045      0
3  0.544883  0.925597      0
4  0.423655  0.071036      0
5  0.645894  0.087129      0
6  0.437587  0.020218      0
7  0.891773  0.832620      1
8  0.963663  0.778157      0
9  0.383442  0.870012      0

To import this dataframe into a MySQL table:

# Import dataframe into MySQL
import sqlalchemy
database_username = 'ENTER USERNAME'
database_password = 'ENTER USERNAME PASSWORD'
database_ip       = 'ENTER DATABASE IP'
database_name     = 'ENTER DATABASE NAME'
database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.
                                               format(database_username, database_password, 
                                                      database_ip, database_name))
frame.to_sql(con=database_connection, name='table_name_for_df', if_exists='replace')

One trick is that MySQLdb doesn't work with Python 3.x. So instead we use mysqlconnector, which may be installed as follows:

pip install mysql-connector==2.1.4  # version avoids Protobuf error

Output:

enter image description here

Note that to_sql creates the table as well as the columns if they do not already exist in the database.

How do I get the project basepath in CodeIgniter

Codeigniter has a function that retrieves your base path which is:

FCPATH and BASEPATH i recommand use FCPATH.

for your base url use:

<?=base_url()?>

if your php short tag is off

<?php echo base_url(); ?>

for example: if you want to link you css files which is in your base path

<script src='<?=base_url()?>js/jquery.js' type='text/javascript' />

Making a button invisible by clicking another button in HTML

Use the id of the element to do the same.

document.getElementById(id).style.visibility = 'hidden';

Optimal way to Read an Excel file (.xls/.xlsx)

Using OLE Query, it's quite simple (e.g. sheetName is Sheet1):

DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
{           
    DataTable sheetData = new DataTable();
    using (OleDbConnection conn = this.returnConnection(fileName))
    {
       conn.Open();
       // retrieve the data using data adapter
       OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
       sheetAdapter.Fill(sheetData);
       conn.Close();
    }                        
    return sheetData;
}

private OleDbConnection returnConnection(string fileName)
{
    return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}

For newer Excel versions:

return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");

You can also use Excel Data Reader an open source project on CodePlex. Its works really well to export data from Excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

Reference: How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Comparing strings in Java

did the same here needed to show "success" twice response is data from PHP

 String res=response.toString().trim;

                            Toast.makeText(sign_in.this,res,Toast.LENGTH_SHORT).show();
    if ( res.compareTo("success")==0){
    Toast.makeText(this,res,Toast.LENGTH_SHORT).show();
    }

How to get text from EditText?

Place the following after the setContentView() method.

final EditText edit =  (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);

Using jQuery Fancybox or Lightbox to display a contact form

Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.

Kiss Jquery UI goodbye and a lightbox hello. You can get it here.

Why do I need to configure the SQL dialect of a data source?

A dialect is a form of the language that is spoken by a particular group of people.

Here, in context of hibernate framework, When hibernate wants to talk(using queries) with the database it uses dialects.

The SQL dialect's are derived from the Structured Query Language which uses human-readable expressions to define query statements.
A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries.

The dialect of hibernate can be configured using below property:

hibernate.dialect

Here, is a complete list of hibernate dialects.

Note: The dialect property of hibernate is not mandatory.

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
    $simple = 'simple string';
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple = '<?php echo $simple; ?>';
    var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.

How can I catch all the exceptions that will be thrown through reading and writing a file?

Catch the base exception 'Exception'

   try { 
         //some code
   } catch (Exception e) {
        //catches exception and all subclasses 
   }

Hibernate SessionFactory vs. JPA EntityManagerFactory

EntityManager interface is similar to sessionFactory in hibernate. EntityManager under javax.persistance package but session and sessionFactory under org.hibernate.Session/sessionFactory package.

Entity manager is JPA specific and session/sessionFactory are hibernate specific.

case-insensitive matching in xpath?

for selenium xpath lower-case will not work ... Translate will help Case 1 :

  1. using Attribute //*[translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']
  2. Using any attribute //[translate(@,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']

Case 2 : (with contains) //[contains(translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'login_field')]

case 3 : for Text property //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'username')]


QA Automator is automation management tool on cloud platform , where you can create, execute and maintenance the automation test scripts https://www.youtube.com/watch?v=iFk1Na_627U&t=53s

jQuery: read text file from file system

specify the full path of the file url

Initializing C dynamic arrays

p = {1,2,3} is wrong.

You can never use this:

int * p;
p = {1,2,3};

loop is right

int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
    p[i] = i;

Rolling back bad changes with svn in Eclipse

You have two choices to do this.

The Quick and Dirty is selecting your files (using ctrl) in Project Explorer view, right-click them, choose Replace with... and then you choose the best option for you, from Latest from Repository, or some Branch version. After getting those files you modify them (with a space, or fix something, your call and commit them to create a newer revision.

A more clean way is choosing Merge at team menu and navigate through the wizard that will help you to recovery the old version in the actual revision.

Both commands have their command-line equivalents: svn revert and svn merge.

long long in C/C++

your code compiles here fine (even with that line uncommented. had to change it to

num3 = 100000000000000000000;

to start getting the warning.

Iterator Loop vs index loop

By writing your client code in terms of iterators you abstract away the container completely.

Consider this code:

class ExpressionParser // some generic arbitrary expression parser
{
public:
    template<typename It>
    void parse(It begin, const It end)
    {
        using namespace std;
        using namespace std::placeholders;
        for_each(begin, end, 
            bind(&ExpressionParser::process_next, this, _1);
    }
    // process next char in a stream (defined elsewhere)
    void process_next(char c);
};

client code:

ExpressionParser p;

std::string expression("SUM(A) FOR A in [1, 2, 3, 4]");
p.parse(expression.begin(), expression.end());

std::istringstream file("expression.txt");
p.parse(std::istringstream<char>(file), std::istringstream<char>());

char expr[] = "[12a^2 + 13a - 5] with a=108";
p.parse(std::begin(expr), std::end(expr));

Edit: Consider your original code example, implemented with :

using namespace std;

vector<int> myIntVector;
// Add some elements to myIntVector
myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);

copy(myIntVector.begin(), myIntVector.end(), 
    std::ostream_iterator<int>(cout, " "));

How to switch to another domain and get-aduser

best solution TNX to Drew Chapin and all of you too:

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

my script:

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
 Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } `  -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv

Python/Django: log to console under runserver, log to file under Apache

I use this:

logging.conf:

[loggers]
keys=root,applog
[handlers]
keys=rotateFileHandler,rotateConsoleHandler

[formatters]
keys=applog_format,console_format

[formatter_applog_format]
format=%(asctime)s-[%(levelname)-8s]:%(message)s

[formatter_console_format]
format=%(asctime)s-%(filename)s%(lineno)d[%(levelname)s]:%(message)s

[logger_root]
level=DEBUG
handlers=rotateFileHandler,rotateConsoleHandler

[logger_applog]
level=DEBUG
handlers=rotateFileHandler
qualname=simple_example

[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=applog_format
args=('applog.log', 'a', 10000, 9)

[handler_rotateConsoleHandler]
class=StreamHandler
level=DEBUG
formatter=console_format
args=(sys.stdout,)

testapp.py:

import logging
import logging.config

def main():
    logging.config.fileConfig('logging.conf')
    logger = logging.getLogger('applog')

    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    #logging.shutdown()

if __name__ == '__main__':
    main()

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

How to get a path to a resource in a Java JAR file

In my case, I have used a URL object instead Path.

File

File file = new File("my_path");
URL url = file.toURI().toURL();

Resource in classpath using classloader

URL url = MyClass.class.getClassLoader().getResource("resource_name")

When I need to read the content, I can use the following code:

InputStream stream = url.openStream();

And you can access the content using an InputStream.

Convert datetime to valid JavaScript date

You can use get methods:

_x000D_
_x000D_
var fullDate = new Date();_x000D_
console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_

JavaScript: How to find out if the user browser is Chrome?

To know the names of different desktop browsers (Firefox, IE, Opera, Edge, Chrome). Except Safari.

function getBrowserName() {
  var browserName = '';
  var userAgent = navigator.userAgent;
  (typeof InstallTrigger !== 'undefined') && (browserName = 'Firefox');
  ( /* @cc_on!@*/ false || !!document.documentMode) && (browserName = 'IE');
  (!!window.chrome && userAgent.match(/OPR/)) && (browserName = 'Opera');
  (!!window.chrome && userAgent.match(/Edge/)) && (browserName = 'Edge');
  (!!window.chrome && !userAgent.match(/(OPR|Edge)/)) && (browserName = 'Chrome');

  /**
   * Expected returns
   * Firefox, Opera, Edge, Chrome
   */
  return browserName;
}

Works in the following browser versions:

Opera - 58.0.3135.79
Firefox - 65.0.2 (64-bit)
IE - 11.413.15063 (JS Fiddle no longer supports IE just paste in Console)
Edge - 44.17763.1.0
Chrome - 72.0.3626.121 (Official Build) (64-bit)

View the gist here and the fiddle here

The original code snippet no longer worked for Chrome and I forgot where I found it. It had safari before but I no longer have access to safari so I cannot verify anymore.

Only the Firefox and IE codes were part of the original snippet.

The checking for Opera, Edge, and Chrome is straight forward. They have differences in the userAgent. OPR only exists in Opera. Edge only exists in Edge. So to check for Chrome these string shouldn't be there.

As for the Firefox and IE, I cannot explain what they do.

I'll be adding this functionality to a package i'm writing

Show a child form in the centre of Parent form in C#

The parent probably isn't yet set when you are trying to access it.

Try this:

loginForm = new SubLogin();
loginForm.Show(this);
loginForm.CenterToParent()

How to set menu to Toolbar in Android

You can still use the answer provided using Toolbar.inflateMenu even while using setSupportActionBar(toolbar).

I had a scenario where I had to move toolbar setup functionality into a separate class outside of activity which didn't by-itself know of the event onCreateOptionsMenu.

So, to implement this, all I had to do was wait for Toolbar to be drawn before calling inflateMenu by doing the following:

toolbar.post {
    toolbar.inflateMenu(R.menu.my_menu)
}

Might not be considered very clean but still gets the job done.

How can I rename a field for all documents in MongoDB?

please try db.collectionName.update({}, { $rename : { 'name.additional' : 'name.last' } }, { multi: true } )

and read this :) http://docs.mongodb.org/manual/reference/operator/rename/#_S_rename

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

A attempt using os.popen to read it in a variable:

import os
ver = os.popen('python -V').read().strip()
print(ver)

How to remove unused dependencies from composer?

following commands will do the same perfectly

rm -rf vendor

composer install 

Get PHP class property by string

There might be answers to this question, but you may want to see these migrations to PHP 7

backward incompatible change

source: php.net

String to list in Python

Or for fun:

>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>> 

ast.literal_eval

What are these ^M's that keep showing up in my files in emacs?

instead of query-replace you may also use M-x delete-trailing-whitespace

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

I is because you are using predefined variables to naming your filename. change your filename from e.g register.asp to registerUser.asp. That will solve your issue

How to specify the JDK version in android studio?

In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:

Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase

Count number of occurences for each unique value

It is a one-line approach by using aggregate.

> aggregate(data.frame(count = v), list(value = v), length)

  value count
1     1    25
2     2    75

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

Updates on 19th Sep 2013:

fixed scaling bugs by adding self.window.bounds = CGRectMake(0, 20, self.window.frame.size.width, self.window.frame.size.height);

corrected typos in the NSNotificationCenter statement


Updates on 12th Sep 2013:

corrected UIViewControllerBasedStatusBarAppearance to NO

added a solution for apps with screen rotation

added an approach to change the background color of the status bar.


There is, apparently, no way to revert the iOS7 status bar back to how it works in iOS6.

However, we can always write some codes and turn the status bar into iOS6-like, and this is the shortest way I can come up with:

  1. Set UIViewControllerBasedStatusBarAppearance to NO in info.plist (To opt out of having view controllers adjust the status bar style so that we can set the status bar style by using the UIApplicationstatusBarStyle method.)

  2. In AppDelegate's application:didFinishLaunchingWithOptions, call

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
        self.window.clipsToBounds =YES;
        self.window.frame =  CGRectMake(0,20,self.window.frame.size.width,self.window.frame.size.height-20);
    
        //Added on 19th Sep 2013
        self.window.bounds = CGRectMake(0, 20, self.window.frame.size.width, self.window.frame.size.height);
    }
    return YES;
    


in order to:

  1. Check if it's iOS 7.

  2. Set status bar's content to be white, as opposed to UIStatusBarStyleDefault.

  3. Avoid subviews whose frames extend beyond the visible bounds from showing up (for views animating into the main view from top).

  4. Create the illusion that the status bar takes up space like how it is in iOS 6 by shifting and resizing the app's window frame.


For apps with screen rotation,

use NSNotificationCenter to detect orientation changes by adding

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidChangeStatusBarOrientation:)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];

in if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) and create a new method in AppDelegate:

- (void)applicationDidChangeStatusBarOrientation:(NSNotification *)notification
{
    int a = [[notification.userInfo objectForKey: UIApplicationStatusBarOrientationUserInfoKey] intValue];
    int w = [[UIScreen mainScreen] bounds].size.width;
    int h = [[UIScreen mainScreen] bounds].size.height;
    switch(a){
        case 4:
            self.window.frame =  CGRectMake(0,20,w,h);
            break;
        case 3:
            self.window.frame =  CGRectMake(-20,0,w-20,h+20);
            break;
        case 2:
            self.window.frame =  CGRectMake(0,-20,w,h);
            break;
        case 1:
           self.window.frame =  CGRectMake(20,0,w-20,h+20);
    }
}

So that when orientation changes, it will trigger a switch statement to detect app's screen orientation (Portrait, Upside Down, Landscape Left, or Landscape Right) and change the app's window frame respectively to create the iOS 6 status bar illusion.


To change the background color of your status bar:

Add

 @property (retain, nonatomic) UIWindow *background;

in AppDelegate.h to make background a property in your class and prevent ARC from deallocating it. (You don't have to do it if you are not using ARC.)

After that you just need to create the UIWindow in if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1):

background = [[UIWindow alloc] initWithFrame: CGRectMake(0, 0, self.window.frame.size.width, 20)];
background.backgroundColor =[UIColor redColor];
[background setHidden:NO];

Don't forget to @synthesize background; after @implementation AppDelegate!

Run cURL commands from Windows console

If you have Git installed on windows you can use the GNU Bash.... it's built in.

https://superuser.com/questions/134685/run-curl-commands-from-windows-console/#483964

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

Add the jstl-1.2.jar into the tomcat/lib folder.

With this, your dependency error will be fixed again.

How to set seekbar min and max value

    private static final int MIN_METERS = 100;
    private static final int JUMP_BY = 50;

    metersText.setText(meters+"");
    metersBar.setProgress((meters-MIN_METERS));
    metersBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
            progress = progress + MIN_METERS;
            progress = progress / JUMP_BY;
            progress = progress * JUMP_BY;
            metersText.setText((progress)+"");
        }
    });
}

Retrieve list of tasks in a queue in Celery

With subprocess.run:

import subprocess
import re
active_process_txt = subprocess.run(['celery', '-A', 'my_proj', 'inspect', 'active'],
                                        stdout=subprocess.PIPE).stdout.decode('utf-8')
return len(re.findall(r'worker_pid', active_process_txt))

Be careful to change my_proj with your_proj

How to configure logging to syslog in Python?

import syslog
syslog.openlog(ident="LOG_IDENTIFIER",logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0)
syslog.syslog('Log processing initiated...')

the above script will log to LOCAL0 facility with our custom "LOG_IDENTIFIER"... you can use LOCAL[0-7] for local purpose.

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true
       }
     }

visit for more in info developer.android.com

Initialising an array of fixed size in python

>>> n = 5                     #length of list
>>> list = [None] * n         #populate list, length n with n entries "None"
>>> print(list)
[None, None, None, None, None]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, None, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, 1, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, 1, 1, 1]

or with really nothing in the list to begin with:

>>> n = 5                     #length of list
>>> list = []                 # create list
>>> print(list)
[]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1]

on the 4th iteration of append:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1]

5 and all subsequent:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1,1]

GROUP BY and COUNT in PostgreSQL

I think you just need COUNT(DISTINCT post_id) FROM votes.

See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

EDIT: Corrected my careless mistake per Erwin's comment.

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

Difference between JPanel, JFrame, JComponent, and JApplet

You might find it useful to lookup the classes on oracle. Eg:

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html

There you can see that JFrame extends JComponent and JContainer.

JComponent is a a basic object that can be drawn, JContainer extends this so that you can add components to it. JPanel and JFrame both extend JComponent as you can add things to them. JFrame provides a window, whereas JPanel is just a panel that goes inside a window. If that makes sense.

how to change color of TextinputLayout's label and edittext underline android

Change bottom line color:

<item name="colorControlNormal">#c5c5c5</item>
<item name="colorControlActivated">@color/accent</item>
<item name="colorControlHighlight">@color/accent</item>

For more info check this thread.

Change hint color when it is floating

<style name="MyHintStyle" parent="@android:style/TextAppearance">
    <item name="android:textColor">@color/main_color</item>
</style>

and use it like this:

<android.support.design.widget.TextInputLayout
    ...
    app:hintTextAppearance="@style/MyHintStyle">

Change hint color when it is not a floating label:

<android.support.design.widget.TextInputLayout
    ...
    app:hintTextAppearance="@style/MyHintStyle"
    android:textColorHint="#c1c2c4">

Thanks to @AlbAtNf

Better way to cast object to int

Convert.ToInt32(myobject);

This will handle the case where myobject is null and return 0, instead of throwing an exception.

Automatically set appsettings.json for dev and release environments in asp.net core?

  1. Create multiple appSettings.$(Configuration).json files like:

    • appSettings.staging.json
    • appSettings.production.json
  2. Create a pre-build event on the project which copies the respective file to appSettings.json:

    copy appSettings.$(Configuration).json appSettings.json
    
  3. Use only appSettings.json in your Config Builder:

    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
    
    Configuration = builder.Build();
    

How to change content on hover

This exact example is present on mozilla developers page:

::after

As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);, and store it in data-descr="ADD" attribute of your HTML tag (which is nice because you can e.g translate it)

CSS content can only be usef with :after and :before pseudo-elements, so you can try to proceed with something like this:

.item a p.new-label span:after{
  position: relative;
  content: 'NEW'
}
.item:hover a p.new-label span:after {
  content: 'ADD';
}

The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

Search for string and get count in vi editor

(similar as Gustavo said, but additionally: )

For any previously search, you can do simply:

:%s///gn

A pattern is not needed, because it is already in the search-register (@/).

"%" - do s/ in the whole file
"g" - search global (with multiple hits in one line)
"n" - prevents any replacement of s/ -- nothing is deleted! nothing must be undone!
(see: :help s_flag for more informations)

(This way, it works perfectly with "Search for visually selected text", as described in vim-wikia tip171)

Understanding the map function

Simplifying a bit, you can imagine map() doing something like this:

def mymap(func, lst):
    result = []
    for e in lst:
        result.append(func(e))
    return result

As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements in the input list. I said "simplifying a bit" because in reality map() can process more than one iterable:

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.

For the second part in the question: What role does this play in making a Cartesian product? well, map() could be used for generating the cartesian product of a list like this:

lst = [1, 2, 3, 4, 5]

from operator import add
reduce(add, map(lambda i: map(lambda j: (i, j), lst), lst))

... But to tell the truth, using product() is a much simpler and natural way to solve the problem:

from itertools import product
list(product(lst, lst))

Either way, the result is the cartesian product of lst as defined above:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
 (2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
 (3, 1), (3, 2), (3, 3), (3, 4), (3, 5),
 (4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
 (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]

How to get an input text value in JavaScript

Edit:

  1. Move your javascript to end of the page to make sure DOM (html elements) is loaded before accessing them (javascript to end for fast loading).
  2. Declare your variables always like in example using var textInputVal = document.getElementById('textInputId').value;
  3. Use descriptive names for inputs and elements (makes easier to understand your own code and when someone other is looking it).
  4. To see more about getElementById, see: http://www.tizag.com/javascriptT/javascript-getelementbyid.php
  5. Using library such as jQuery makes using javascript hundred times easier, to learn more: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Checking if an object is null in C#

As of C# 9 you can do

if (obj is null) { ... }

For not null use

if (obj is not null) { ... }

If you need to override this behaviour use == and != accordingly.

How can I simulate an array variable in MySQL?

Here’s how I did it.

First, I created a function that checks whether a Long/Integer/whatever value is in a list of values separated by commas:

CREATE DEFINER = 'root'@'localhost' FUNCTION `is_id_in_ids`(
        `strIDs` VARCHAR(255),
        `_id` BIGINT
    )
    RETURNS BIT(1)
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN

  DECLARE strLen    INT DEFAULT 0;
  DECLARE subStrLen INT DEFAULT 0;
  DECLARE subs      VARCHAR(255);

  IF strIDs IS NULL THEN
    SET strIDs = '';
  END IF;

  do_this:
    LOOP
      SET strLen = LENGTH(strIDs);
      SET subs = SUBSTRING_INDEX(strIDs, ',', 1);

      if ( CAST(subs AS UNSIGNED) = _id ) THEN
        -- founded
        return(1);
      END IF;

      SET subStrLen = LENGTH(SUBSTRING_INDEX(strIDs, ',', 1));
      SET strIDs = MID(strIDs, subStrLen+2, strLen);

      IF strIDs = NULL or trim(strIds) = '' THEN
        LEAVE do_this;
      END IF;

  END LOOP do_this;

   -- not founded
  return(0);

END;

So now you can search for an ID in a comma-separated list of IDs, like this:

select `is_id_in_ids`('1001,1002,1003',1002);

And you can use this function inside a WHERE clause, like this:

SELECT * FROM table1 WHERE `is_id_in_ids`('1001,1002,1003',table1_id);

This was the only way I found to pass an "array" parameter to a PROCEDURE.

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.

How to check certificate name and alias in keystore files?

In a bash-like environment you can use:

keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo

This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep.

eclipse stuck when building workspace

The accepted answer allowed me to get Eclipse started again, but it seems that the projects lost their metadata. (E.g., all the Git/Gradle/Spring icons disappeared from the project names.) I have a lot of projects in there, and I didn't want to have to import them all over again.

So here's what worked for me under Kepler. YMMV but I wanted to record this just in case it helps somebody.

Step 1. Temporarily move the .projects file out of the way:

$ cd .metadata/.plugins/org.eclipse.core.resources
$ mv .projects .projects.bak

Step 2. Then start Eclipse. The metadata will be missing, but at least Eclipse starts without getting stuck.

Step 3. Close Eclipse.

Step 4. Revert the .projects.bak file to its original name:

$ mv .projects.bak .projects

Step 5. Restart Eclipse. It may build some stuff, but this time it should get through. (At least it did for me.)

Angular 6: How to set response type as text while making http call

You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.

Instead you should set the option responseType to text:

addToCart(productId: number, quantity: number): Observable<any> {
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');

  return this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'}
  ).pipe(catchError(this.errorHandlerService.handleError));
}

Doctrine findBy 'does not equal'

I used the QueryBuilder to get the data,

$query=$this->dm->createQueryBuilder('AppBundle:DocumentName')
             ->field('fieldName')->notEqual(null);

$data=$query->getQuery()->execute();

How can I extract all values from a dictionary in Python?

Use values()

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}

>>> d.values()
<<< [-0.3246, -0.9185, -3985]

What is the main difference between Collection and Collections in Java?

Collection is a base interface for most collection classes (it is the root interface of java collection framework) Collections is a utility class

Collections class is a utility class having static methods It implements Polymorphic algorithms which operate on collections.

How to replace multiple patterns at once with sed?

sed is a stream editor. It searches and replaces greedily. The only way to do what you asked for is using an intermediate substitution pattern and changing it back in the end.

echo 'abcd' | sed -e 's/ab/xy/;s/cd/ab/;s/xy/cd/'

How to start rails server?

For newest Rails versions

If you have trouble with rails s, sometimes terminal fails.

And you should try to use:

./bin/rails

To access command.

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

I have been using this change in my code :

old code :

 <td>
  @Html.DisplayFor(modelItem => item.dataakt)
 </td>

new :

<td>
 @Convert.ToDateTime(item.dataakt).ToString("dd/MM/yyyy")
</td>

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

When to use margin vs padding in CSS

TL;DR: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.

To me, the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't.

Consider two elements one above the other each with padding of 1em. This padding is considered to be part of the element and is always preserved.

So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element.

Thus the content of the two elements will end up being 2em apart.

Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap.

So in this example, you will end up with the content of the first element followed by 1em of combined margin followed by the content of the second element. So the content of the two elements is only 1em apart.

This can be really useful when you know that you want to say 1em of spacing around an element, regardless of what element it is next to.

The other two big differences are that padding is included in the click region and background color/image, but not the margin.

_x000D_
_x000D_
div.box > div { height: 50px; width: 50px; border: 1px solid black; text-align: center; }_x000D_
div.padding > div { padding-top: 20px; }_x000D_
div.margin > div { margin-top: 20px; }
_x000D_
<h3>Default</h3>_x000D_
<div class="box">_x000D_
  <div>A</div>_x000D_
  <div>B</div>_x000D_
  <div>C</div>_x000D_
</div>_x000D_
_x000D_
<h3>padding-top: 20px</h3>_x000D_
<div class="box padding">_x000D_
  <div>A</div>_x000D_
  <div>B</div>_x000D_
  <div>C</div>_x000D_
</div>_x000D_
_x000D_
<h3>margin-top: 20px; </h3>_x000D_
<div class="box margin">_x000D_
  <div>A</div>_x000D_
  <div>B</div>_x000D_
  <div>C</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I count occurrence of duplicate items in array

There is a magical function PHP is offering to you it called in_array().

Using parts of your code we will modify the loop as follows:

<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
    if (in_array($array[$arr], $arr2)) {
        ++$counter;
        continue;
    }
    else{
        $arr2[] = $array[$arr];
    }
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>

The above code snippet will return the number total number of repeated items i.e. form the sample array 43 is repeated 5 times, 78 is repeated 1 time and 21 is repeated 1 time, then it returns an array without repeat.

ReactJS - Does render get called any time "setState" is called?

Even though it's stated in many of the other answers here, the component should either:

  • implement shouldComponentUpdate to render only when state or properties change

  • switch to extending a PureComponent, which already implements a shouldComponentUpdate method internally for shallow comparisons.

Here's an example that uses shouldComponentUpdate, which works only for this simple use case and demonstration purposes. When this is used, the component no longer re-renders itself on each click, and is rendered when first displayed, and after it's been clicked once.

_x000D_
_x000D_
var TimeInChild = React.createClass({_x000D_
    render: function() {_x000D_
        var t = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <p>Time in child:{t}</p>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Main = React.createClass({_x000D_
    onTest: function() {_x000D_
        this.setState({'test':'me'});_x000D_
    },_x000D_
_x000D_
    shouldComponentUpdate: function(nextProps, nextState) {_x000D_
      if (this.state == null)_x000D_
        return true;_x000D_
  _x000D_
      if (this.state.test == nextState.test)_x000D_
        return false;_x000D_
        _x000D_
      return true;_x000D_
  },_x000D_
_x000D_
    render: function() {_x000D_
        var currentTime = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <div onClick={this.onTest}>_x000D_
            <p>Time in main:{currentTime}</p>_x000D_
            <p>Click me to update time</p>_x000D_
            <TimeInChild/>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(<Main/>, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
_x000D_
_x000D_
_x000D_

Why won't bundler install JSON gem?

$ bundle update json
$ bundle install

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

In case anyone else faces this, it's a case of PHP not having access to the mysql client libraries. Having a MySQL server on the system is not the correct fix. Fix for ubuntu (and PHP 5):

sudo apt-get install php5-mysql

After installing the client, the webserver should be restarted. In case you're using apache, the following should work:

sudo service apache2 restart

How to check if a variable exists in a FreeMarker template?

Also I think if_exists was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?

scrollable div inside container

_x000D_
_x000D_
function start() {_x000D_
 document.getElementById("textBox1").scrollTop +=5;_x000D_
    scrolldelay = setTimeout(function() {start();}, 40);_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
_x000D_
function reset(){_x000D_
 var loc = document.getElementById("textBox1").scrollTop;_x000D_
 document.getElementById("textBox1").scrollTop -= loc;_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
//adjust height of paragraph in css_x000D_
//element textbox in div_x000D_
//adjust speed at scrolltop and start 
_x000D_
_x000D_
_x000D_

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

Pandas: Subtracting two date columns and the result being an integer

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

Why an interface can not implement another interface?

Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You may need to clear the plugin column for your root account. On my fresh install, all of the root user accounts had unix_socket set in the plugin column. This was causing the root sql account to be locked only to the root unix account, since only system root could login via socket.

If you update user set plugin='' where User='root';flush privileges;, you should now be able to login to the root account from any localhost unix account (with a password).

See this AskUbuntu question and answer for more details.

Ajax Upload image

Here is simple way using HTML5 and jQuery:

1) include two JS file

<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>

2) include CSS to have cool buttons

<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />

3) create DIV or SPAN

<div class="demo" > </div>

4) write this code in your HTML page

$('.demo').ajaxupload({
    url:'upload.php'
});

5) create you upload.php file to have PHP code to upload data.

You can download required JS file from here Here is Example

Its too cool and too fast And easy too! :)

Best way to simulate "group by" from bash?

I understand you are looking for something in Bash, but in case someone else might be looking for something in Python, you might want to consider this:

mySet = set()
for line in open("ip_address_file.txt"):
     line = line.rstrip()
     mySet.add(line)

As values in the set are unique by default and Python is pretty good at this stuff, you might win something here. I haven't tested the code, so it might be bugged, but this might get you there. And if you want to count occurrences, using a dict instead of a set is easy to implement.

Edit: I'm a lousy reader, so I answered wrong. Here's a snippet with a dict that would count occurences.

mydict = {}
for line in open("ip_address_file.txt"):
    line = line.rstrip()
    if line in mydict:
        mydict[line] += 1
    else:
        mydict[line] = 1

The dictionary mydict now holds a list of unique IP's as keys and the amount of times they occurred as their values.

TOMCAT - HTTP Status 404

  1. Click on Window > Show view > Server or right click on the server in "Servers" view, select "Properties".
  2. In the "General" panel, click on the "Switch Location" button.
  3. The "Location: [workspace metadata]" should replace by something else.
  4. Open the Overview screen for the server by double clicking it.
  5. In the Server locations tab , select "Use Tomcat location".
  6. Save the configurations and restart the Server.

You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.

server Locations in eclipse view

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Bootstrap 3 Glyphicons are not working

If the other solutions aren't working, you may want to try importing Glyphicons from an external source, rather than relying on Bootstrap to do everything for you. To do this:

You can either do this in HTML:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

Or CSS:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css")

Credit to edsiofi from this thread: Bootstrap 3 Glyphicons CDN

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

  • Use a nonbacktracking expression to match the whole password first, if it has at least 8 characters (this way, there is no combinatorial explosion for long, but invalid passwords): (?>{8,})
  • Use lookbehind assertions to check for presence of all required characters (AND-conditions). (?<=...)
  • At least one uppercase character: (?<=\p{Lu}.*)
  • At least one special character (a bit ambiguous, but let's use not-word): (?<=\W.*)
  • At least one alphanumeric character (: (?<=\w.*)

Summed up:

(?>.{8,})(?<=\p{Lu}.*)(?<=\W.*)(?<=\w.*)

What are the differences between a clustered and a non-clustered index?

A clustered index is essentially a sorted copy of the data in the indexed columns.

The main advantage of a clustered index is that when your query (seek) locates the data in the index then no additional IO is needed to retrieve that data.

The overhead of maintaining a clustered index, especially in a frequently updated table, can lead to poor performance and for that reason it may be preferable to create a non-clustered index.

Color different parts of a RichTextBox string

Here is an extension method that overloads the AppendText method with a color parameter:

public static class RichTextBoxExtensions
{
    public static void AppendText(this RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }
}

And this is how you would use it:

var userid = "USER0001";
var message = "Access denied";
var box = new RichTextBox
              {
                  Dock = DockStyle.Fill,
                  Font = new Font("Courier New", 10)
              };

box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);

new Form {Controls = {box}}.ShowDialog();

Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

How to round each item in a list of floats to 2 decimal places?

Another option which doesn't require numpy is:

precision = 2  
myRoundedList = [int(elem*(10**precision)+delta)/(10.0**precision) for elem in myList]

# delta=0 for floor
# delta = 0.5 for round
# delta = 1 for ceil

How to Rotate a UIImage 90 degrees?

What about something like:

static inline double radians (double degrees) {return degrees * M_PI/180;}
UIImage* rotate(UIImage* src, UIImageOrientation orientation)
{
    UIGraphicsBeginImageContext(src.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orientation == UIImageOrientationRight) {
        CGContextRotateCTM (context, radians(90));
    } else if (orientation == UIImageOrientationLeft) {
        CGContextRotateCTM (context, radians(-90));
    } else if (orientation == UIImageOrientationDown) {
        // NOTHING
    } else if (orientation == UIImageOrientationUp) {
        CGContextRotateCTM (context, radians(90));
    }

    [src drawAtPoint:CGPointMake(0, 0)];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

ADB Shell Input Events

If you want to send a text to specific device when multiple devices connected. First look for the attached devices using adb devices

adb devices
List of devices attached
3004e25a57192200        device
31002d9e592b7300        device

then get your specific device id and try the following

adb -s 31002d9e592b7300 shell input text 'your text'

Google Authenticator available as a public service?

The project is open source. I have not used it. But it's using a documented algorithm (noted in the RFC listed on the open source project page), and the authenticator implementations support multiple accounts.

The actual process is straightforward. The one time code is, essentially, a pseudo random number generator. A random number generator is a formula that once given a seed, or starting number, continues to create a stream of random numbers. Given a seed, while the numbers may be random to each other, the sequence itself is deterministic. So, once you have your device and the server "in sync" then the random numbers that the device creates, each time you hit the "next number button", will be the same, random, numbers the server expects.

A secure one time password system is more sophisticated than a random number generator, but the concept is similar. There are also other details to help keep the device and server in sync.

So, there's no need for someone else to host the authentication, like, say OAuth. Instead you need to implement that algorithm that is compatible with the apps that Google provides for the mobile devices. That software is (should be) available on the open source project.

Depending on your sophistication, you should have all you need to implement the server side of this process give the OSS project and the RFC. I do not know if there is a specific implementation for your server software (PHP, Java, .NET, etc.)

But, specifically, you don't need an offsite service to handle this.

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

Invoking a PHP script from a MySQL trigger

I was thinking about this exact issue for a case with long polling where I didn't want the php script to have to continually poll the db. Polling would need to be done somewhere, memory would probably be best. So if somehow the trigger could put the info into something like memcache, then php could poll that would would be much less intensive overall. Just need a method for mysql to use memcache. Perhaps into a predefined variable with a specific user id. Once the data is retrieved php could reset the var until the db sets it again. Not sure about timing issues though. Perhaps a second variable to store the previous key selected.

Return zero if no record is found

I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0 would be SELECT 0 FROM DUAL)

SELECT SUM(sub.value)
FROM
( 
  SELECT SUM(columnA) as value FROM my_table
  WHERE columnB = 1
  UNION
  SELECT 0 as value
) sub

Maybe this would work for postgresql too?

Normalizing a list of numbers in Python

Use :

norm = [float(i)/sum(raw) for i in raw]

to normalize against the sum to ensure that the sum is always 1.0 (or as close to as possible).

use

norm = [float(i)/max(raw) for i in raw]

to normalize against the maximum

Apache Name Virtual Host with SSL

Apache doesn't support SSL on name-based virtual host, only on IP based Virtual Hosts.

Source: Apache 2.2 SSL FAQ question Why is it not possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts?

Unlike SSL, the TLS specification allows for name-based hosts (SNI as mentioned by someone else), but Apache doesn't yet support this feature. It supposedly will in a future release when compiled against openssl 0.9.8.

Also, mod_gnutls claims to support SNI, but I've never actually tried it.

How to get child element by class name?

To me it seems like you want the fourth span. If so, you can just do this:

document.getElementById("test").childNodes[3]

or

document.getElementById("test").getElementsByTagName("span")[3]

This last one ensures that there are not any hidden nodes that could mess it up.

Built in Python hash() function

It probably just asks the operating system provided function, rather than its own algorithm.

As other comments says, use hashlib or write your own hash function.

Align contents inside a div

You can do it like this also:

HTML

<body>
    <div id="wrapper_1">
        <div id="container_1"></div>
    </div>
</body>

CSS

body { width: 100%; margin: 0; padding: 0; overflow: hidden; }

#wrapper_1 { clear: left; float: left; position: relative; left: 50%; }

#container_1 { display: block; float: left; position: relative; right: 50%; }

As Artem Russakovskii mentioned also, read the original article by Mattew James Taylor for full description.

java.lang.IllegalArgumentException: contains a path separator

You cannot use path with directory separators directly, but you will have to make a file object for every directory.

NOTE: This code makes directories, yours may not need that...

File file= context.getFilesDir();
file.mkdir();

String[] array=filePath.split("/");
for(int t=0; t< array.length -1 ;t++)
{
    file=new File(file,array[t]);
    file.mkdir();
}

File f=new File(file,array[array.length-1]);

RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append);

Find which rows have different values for a given column in Teradata SQL

Personally, I would print them to a file using Perl or Python in the format

<COL_NAME>:  <COL_VAL>

for each row so that the file has as many lines as there are columns. Then I'd do a diff between the two files, assuming you are on Unix or compare them using some equivalent utilty on another OS. If you have multiple recordsets (i.e. more than one row), I would prepend to each file row and then the file would have NUM_DB_ROWS * NUM_COLS lines

How to insert data into elasticsearch

Simple fundamentals, Elastic community has exposed indexing, searching, deleting operation as rest web service. You can interact elastic using curl or sense(chrome plugin) or any rest client like postman.

If you are just testing few commands, I would recommend can use of sense chrome plugin which has simple UI and pretty mature plugin now.

How to refresh activity after changing language (Locale) inside application

After changing language newly created activities display with changed new language, but current activity and previously created activities which are in pause state are not updated.How to update activities ?

Pre API 11 (Honeycomb), the simplest way to make the existing activities to be displayed in new language is to restart it. In this way you don't bother to reload each resources by yourself.

private void restartActivity() {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Register an OnSharedPreferenceChangeListener, in its onShredPreferenceChanged(), invoke restartActivity() if language preference was changed. In my example, only the PreferenceActivity is restarted, but you should be able to restart other activities on activity resume by setting a flag.

Update (thanks @stackunderflow): As of API 11 (Honeycomb) you should use recreate() instead of restartActivity().

public class PreferenceActivity extends android.preference.PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    // ...

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("pref_language")) {
            ((Application) getApplication()).setLocale();
            restartActivity();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }
}

I have a blog post on this topic with more detail, but it's in Chinese. The full source code is on github: PreferenceActivity.java

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

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

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

HTML:-

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

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


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

    </ul>

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

JS:-

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

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

CSS:-

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

li{
padding: 20px;
}

How can I represent an 'Enum' in Python?

From Python 3.4 there will be official support for enums. You can find documentation and examples here on Python 3.4 documentation page.

Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows:

from enum import Enum
class Color(Enum):
     red = 1
     green = 2
     blue = 3

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Please take a look at my project on Sourceforge which has user types for standard SQL Date and Time types as well as JSR 310 and Joda Time. All of the types try to address the offsetting issue. See http://sourceforge.net/projects/usertype/

EDIT: In response to Derek Mahar's question attached to this comment:

"Chris, do your user types work with Hibernate 3 or greater? – Derek Mahar Nov 7 '10 at 12:30"

Yes these types support Hibernate 3.x versions including Hibernate 3.6.

How do I get into a non-password protected Java keystore or change the password?

which means that cacerts keystore isn't password protected

That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:

In order to verify its integrity, you must provide your keystore password.

Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

In python 2.7 adding Trusted root CA details at the end in file C:\Python27\lib\site-packages\certifi\cacert.pem helped

after that i did run (using admin rights) pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org packageName

n-grams in python, four, five, six grams?

For four_grams it is already in NLTK, here is a piece of code that can help you toward this:

 from nltk.collocations import *
 import nltk
 #You should tokenize your text
 text = "I do not like green eggs and ham, I do not like them Sam I am!"
 tokens = nltk.wordpunct_tokenize(text)
 fourgrams=nltk.collocations.QuadgramCollocationFinder.from_words(tokens)
 for fourgram, freq in fourgrams.ngram_fd.items():  
       print fourgram, freq

I hope it helps.

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

Using

mapper.configure(
    JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), 
    true
);

See javadoc:

/**
 * Feature that determines whether parser will allow
 * JSON Strings to contain unescaped control characters
 * (ASCII characters with value less than 32, including
 * tab and line feed characters) or not.
 * If feature is set false, an exception is thrown if such a
 * character is encountered.
 *<p>
 * Since JSON specification requires quoting for all control characters,
 * this is a non-standard feature, and as such disabled by default.
 */

Old option JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS was deprecated since 2.10.

Please see also github thread.

Setting TIME_WAIT TCP

Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.

A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.

For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.

write multiple lines in a file in python

You're confusing the braces. Do it like this:

target.write("%s \n %s \n %s \n" % (line1, line2, line3))

Or even better, use writelines:

target.writelines([line1, line2, line3])

How to effectively work with multiple files in Vim

Why not use tabs (introduced in Vim 7)? You can switch between tabs with :tabn and :tabp, With :tabe <filepath> you can add a new tab; and with a regular :q or :wq you close a tab. If you map :tabn and :tabp to your F7/F8 keys you can easily switch between files.

If there are not that many files or you don't have Vim 7 you can also split your screen in multiple files: :sp <filepath>. Then you can switch between splitscreens with Ctrl+W and then an arrow key in the direction you want to move (or instead of arrow keys, w for next and W for previous splitscreen)

How can I clear an HTML file input with JavaScript?

Unfortunately none of the above answers appear to cover all the bases - at least not with my testing with vanilla javascript.

  • .value = null appears to work on FireFox, Chome, Opera and IE11 (but not IE8/9/10)

  • .cloneNode (and .clone() in jQuery) on FireFox appears to copy the .value over, therefore making the clone pointless.

So here is the vanilla javascript function I have written that works on FireFox (27 and 28), Chrome (33), IE (8, 9, 10, 11), Opera (17)... these are the only browsers currently available to me to test with.

function clearFileInput(ctrl) {
  try {
    ctrl.value = null;
  } catch(ex) { }
  if (ctrl.value) {
    ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
  }
}

The ctrl parameter is the file input itself, so the function would be called as...

clearFileInput(document.getElementById("myFileInput"));

How to right align widget in horizontal linear layout Android?

Add android:gravity="right" to LinearLayout. Assuming the TextView has layout_width="wrap_content"

How to insert blank lines in PDF?

document.add(new Paragraph("")) 

It is ineffective above,must add a blank string, like this:

document.add(new Paragraph(" "));

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You are using datetimepicker when it should be datepicker. As per the docs. Try this and it should work.

<script type="text/javascript">
  $(function () {
    $('#datetimepicker9').datepicker({
      viewMode: 'years'
    });
  });
 </script>

What is the OR operator in an IF statement

you need

if (title == "User greeting" || title == "User name") {do stuff};

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Why doesn't calling a Python string method do anything unless you assign its output?

This is because strings are immutable in Python.

Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

X.replace("hello", "goodbye")

with this line:

X = X.replace("hello", "goodbye")

More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace,strip,translate,lower/upper,join,...

You must assign their output to something if you want to use it and not throw it away, e.g.

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

and so on.

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

Access VBA | How to replace parts of a string with another string

I was reading this thread and would like to add information even though it is surely no longer timely for the OP.

BiggerDon above points out the difficulty of rote replacing "North" with "N". A similar problem exists with "Avenue" to "Ave" (e.g. "Avenue of the Americas" becomes "Ave of the Americas": still understandable, but probably not what the OP wants.

The replace() function is entirely context-free, but addresses are not. A complete solution needs to have additional logic to interpret the context correctly, and then apply replace() as needed.

Databases commonly contain addresses, and so I wanted to point out that the generalized version of the OP's problem as applied to addresses within the United States has been addressed (humor!) by the Coding Accuracy Support System (CASS). CASS is a database tool that accepts a U.S. address and completes or corrects it to meet a standard set by the U.S. Postal Service. The Wikipedia entry https://en.wikipedia.org/wiki/Postal_address_verification has the basics, and more information is available at the Post Office: https://ribbs.usps.gov/index.cfm?page=address_info_systems

How to enable native resolution for apps on iPhone 6 and 6 Plus?

An error was encountered while running (Domain = LaunchServicesError, Code = 0)

Usually this indicates that installd returned an error during the install process (bad resources or similar).

Unfortunately, Xcode does not display the actual underlying error (feel free to file dupes of this known bug).

You should check ~/Library/Logs/CoreSimulator/CoreSimulator.log which will log the underlying error for you.

How to pad a string with leading zeros in Python 3

Python integers don't have an inherent length or number of significant digits. If you want them to print a specific way, you need to convert them to a string. There are several ways you can do so that let you specify things like padding characters and minimum lengths.

To pad with zeros to a minimum of three characters, try:

length = 1
print(format(length, '03'))

How do I update the element at a certain position in an ArrayList?

 arrList.set(5,newValue);

and if u want to update it then add this line also

 youradapater.NotifyDataSetChanged();

post ajax data to PHP and return data

 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

Clarification

i think you are confusing

{data:the_id}

with

success:function(data){

both the data are different for your own clarity sake you can modify it as

success:function(vote_count){
$(span#someId).html(vote_count);

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

How to get the selected item from ListView?

You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.

What you should change, in your above example, is to

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    MyClass item = (MyClass) adapter.getItem(position);
}

How to show/hide if variable is null

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;

Multiple condition in single IF statement

Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

SQL Server - Adding a string to a text column (concat equivalent)

like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:

-- create a test table 
create table test (
    a text
) 
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works: 
update test set a = cast ( a as nvarchar(max))  + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added

hope that helps

Java Regex Capturing Groups

The issue you're having is with the type of quantifier. You're using a greedy quantifier in your first group (index 1 - index 0 represents the whole Pattern), which means it'll match as much as it can (and since it's any character, it'll match as many characters as there are in order to fulfill the condition for the next groups).

In short, your 1st group .* matches anything as long as the next group \\d+ can match something (in this case, the last digit).

As per the 3rd group, it will match anything after the last digit.

If you change it to a reluctant quantifier in your 1st group, you'll get the result I suppose you are expecting, that is, the 3000 part.

Note the question mark in the 1st group.

String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 2: " + matcher.group(2));
    System.out.println("group 3: " + matcher.group(3));
}

Output:

group 1: This order was placed for QT
group 2: 3000
group 3: ! OK?

More info on Java Pattern here.

Finally, the capturing groups are delimited by round brackets, and provide a very useful way to use back-references (amongst other things), once your Pattern is matched to the input.

In Java 6 groups can only be referenced by their order (beware of nested groups and the subtlety of ordering).

In Java 7 it's much easier, as you can use named groups.

Is there a css cross-browser value for "width: -moz-fit-content;"?

Mozilla's MDN suggests something like the following [source]:

 p {
  width: intrinsic;           /* Safari/WebKit uses a non-standard name */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
}

Invoking a jQuery function after .each() has completed

You have to queue the rest of your request for it to work.

var elems = $(parentSelect).nextAll();
var lastID = elems.length - 1;

elems.each( function(i) {
    $(this).fadeOut(200, function() { 
        $(this).remove(); 
        if (i == lastID) {
            $j(this).queue("fx",function(){ doMyThing;});
        }
    });
});