Programs & Examples On #Getmodulefilename

Hide options in a select list using jQuery

You cannot do this x-browser. If I recall ie has issues. The easiest thing to do is keep a cloned copy of the select before you remove items, this allows you to easily remove and then append the missing items back.

What is the Swift equivalent to Objective-C's "@synchronized"?

Based on ?eurobur?, test an sub-class case

class Foo: NSObject {
    func test() {
        print("1")
        objc_sync_enter(self)
        defer {
            objc_sync_exit(self)
            print("3")
        }

        print("2")
    }
}


class Foo2: Foo {
    override func test() {
        super.test()

        print("11")
        objc_sync_enter(self)
        defer {
            print("33")
            objc_sync_exit(self)
        }

        print("22")
    }
}

let test = Foo2()
test.test()

Output:

1
2
3
11
22
33

How to compile Go program consisting of multiple files?

Since Go 1.11+, GOPATH is no longer recommended, the new way is using Go Modules.

Say you're writing a program called simple:

  1. Create a directory:

    mkdir simple
    cd simple
    
  2. Create a new module:

    go mod init github.com/username/simple
    # Here, the module name is: github.com/username/simple.
    # You're free to choose any module name.
    # It doesn't matter as long as it's unique.
    # It's better to be a URL: so it can be go-gettable.
    
  3. Put all your files in that directory.

  4. Finally, run:

    go run .
    
  5. Alternatively, you can create an executable program by building it:

    go build .
    
    # then:
    ./simple     # if you're on xnix
    
    # or, just:
    simple       # if you're on Windows
    

For more information, you may read this.

Go has included support for versioned modules as proposed here since 1.11. The initial prototype vgo was announced in February 2018. In July 2018, versioned modules landed in the main Go repository. In Go 1.14, module support is considered ready for production use, and all users are encouraged to migrate to modules from other dependency management systems.

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html

Can't ignore UserInterfaceState.xcuserstate

Here is a very nice explanation of how to remove the files in question recursively from your git history: http://help.github.com/remove-sensitive-data/

Very useful, because otherwise tools tend to 'hang' while trying to show the diff on those huge files that shouldn't have been checked in the first place...

Here's what you can do (in short) to get rid of the largest stuff:

cd YourProject
git filter-branch --index-filter 'git rm --cached --ignore-unmatch -r YourProject.xcodeproj/project.xcworkspace' HEAD
# see what you want to do with your remote here...
# you can: git push origin master --force
# or you can delete it and push a fresh new one from your cleaned-up local...
rm -rf .git/refs/original
git gc --prune=now
git gc --aggressive --prune=now

Worked very nicely for me :)

How to create a md5 hash of a string in C?

I don't know this particular library, but I've used very similar calls. So this is my best guess:

unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);

This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string.

char md5string[33];
for(int i = 0; i < 16; ++i)
    sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);

VirtualBox Cannot register the hard disk already exists

1 - Open the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid (take note to revert this change on step 6)

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

2 - Reboot machine

4 - Stop Virtual Machine (if started)

5 - On terminal:

su vbox
cd /home/virtualbox/WindowsServer/
VBoxManage modifyhd WindowsServer.vdi --resize SIZE
exit
exit

change SIZE for a number in Megabytes, example 80000 (80GB)

6 - Open again the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid whith the original value

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

7 - Reboot machine

Android : difference between invisible and gone?

  • View.INVISIBLE->The View is invisible but it will occupy some space in layout

  • View.GONE->The View is not visible and it will not occupy any space in layout

What does functools.wraps do?

When you use a decorator, you're replacing one function with another. In other words, if you have a decorator

def logged(func):
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

then when you say

@logged
def f(x):
   """does some math"""
   return x + x * x

it's exactly the same as saying

def f(x):
    """does some math"""
    return x + x * x
f = logged(f)

and your function f is replaced with the function with_logging. Unfortunately, this means that if you then say

print(f.__name__)

it will print with_logging because that's the name of your new function. In fact, if you look at the docstring for f, it will be blank because with_logging has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument x; instead it'll be listed as taking *args and **kwargs because that's what with_logging takes.

If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have functools.wraps. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps is itself a decorator, the following code does the correct thing:

from functools import wraps
def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

@logged
def f(x):
   """does some math"""
   return x + x * x

print(f.__name__)  # prints 'f'
print(f.__doc__)   # prints 'does some math'

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

How to check if one of the following items is in a list?

a = {2,3,4}
if {1,2} & a:
    pass

Code golf version. Consider using a set if it makes sense to do so. I find this more readable than a list comprehension.

What is the difference between instanceof and Class.isAssignableFrom(...)?

There is yet another difference. If the type (Class) to test against is dynamic, e.g. passed as a method parameter, then instanceof won't cut it for you.

boolean test(Class clazz) {
   return (this instanceof clazz); // clazz cannot be resolved to a type.
}

but you can do:

boolean test(Class clazz) {
   return (clazz.isAssignableFrom(this.getClass())); // okidoki
}

Oops, I see this answer is already covered. Maybe this example is helpful to someone.

What exactly does an #if 0 ..... #endif block do?

It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:

foo();
bar(x, y); /* x must not be NULL */
baz();

If I want to comment it out, I might try:

/*
foo();
bar(x, y); /* x must not be NULL */
baz();
*/

Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the */ after the word "NULL" terminates the comment, making the baz call not commented out, and the */ after baz a syntax error. On the other hand:

#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif

Works to comment out the entire thing. And the #if 0s will nest with each other, like so:

#if 0
pre_foo();
#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif
quux();
#endif

Although of course this can get a bit confusing and become a maintenance headache if not commented properly.

Sql query to insert datetime in SQL Server

A more language-independent choice for string literals is the international standard ISO 8601 format "YYYY-MM-DDThh:mm:ss". I used the SQL query below to test the format, and it does indeed work in all SQL languages in sys.syslanguages:

declare @sql nvarchar(4000)

declare @LangID smallint
declare @Alias sysname

declare @MaxLangID smallint
select @MaxLangID = max(langid) from sys.syslanguages

set @LangID = 0

while @LangID <= @MaxLangID
begin

    select @Alias = alias
    from sys.syslanguages
    where langid = @LangID

    if @Alias is not null
    begin

        begin try
            set @sql = N'declare @TestLang table (langdate datetime)
    set language ''' + @alias + N''';
    insert into @TestLang (langdate)
    values (''2012-06-18T10:34:09'')'
            print 'Testing ' + @Alias

            exec sp_executesql @sql
        end try
        begin catch
            print 'Error in language ' + @Alias
            print ERROR_MESSAGE()
        end catch
    end

    select @LangID = min(langid)
    from sys.syslanguages
    where langid > @LangID
end

According to the String Literal Date and Time Formats section in Microsoft TechNet, the standard ANSI Standard SQL date format "YYYY-MM-DD hh:mm:ss" is supposed to be "multi-language". However, using the same query, the ANSI format does not work in all SQL languages.

For example, in Danish, you will many errors like the following:

Error in language Danish The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

If you want to build a query in C# to run on SQL Server, and you need to pass a date in the ISO 8601 format, use the Sortable "s" format specifier:

string.Format("select convert(datetime2, '{0:s}'", DateTime.Now);

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

How do you transfer or export SQL Server 2005 data to Excel

If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv

Convert datetime value into string

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

How to divide flask app into multiple py files?

I would like to recommend flask-empty at GitHub.

It provides an easy way to understand Blueprints, multiple views and extensions.

Throughput and bandwidth difference?

Although there are already few answers to this questions but I think some people still may have doubt in actually visualising the differece b/w throughput and bandwidth just like I had ;) until I read this analogy on quora(full credits to that) which proved really helpful

Consider

A highway which has a capacity of moving ,say, 200 vehicles at a time

but

at a random time someone notices only , say, 150 vehicles moving through it..

say due to some traffic-jam in between...

i.e.

capacity is 200 but not all the time it is fully utilised, actual traffic is only 150 out of a max of 200.

i.e. the bandwidth is 200 per unit time but still actual throughput is 150 ...

I thought it might help someone...

How to write an ArrayList of Strings into a text file?

If you need to create each ArrayList item in a single line then you can use this code

private void createFile(String file, ArrayList<String> arrData)
            throws IOException {
        FileWriter writer = new FileWriter(file + ".txt");
        int size = arrData.size();
        for (int i=0;i<size;i++) {
            String str = arrData.get(i).toString();
            writer.write(str);
            if(i < size-1)**//This prevent creating a blank like at the end of the file**
                writer.write("\n");
        }
        writer.close();
    }

Check if TextBox is empty and return MessageBox?

if (MaterialTextBox.Text.length==0)
{
message

}

Lists in ConfigParser

No mention of the converters kwarg for ConfigParser() in any of these answers was rather disappointing.

According to the documentation you can pass a dictionary to ConfigParser that will add a get method for both the parser and section proxies. So for a list:

example.ini

[Germ]
germs: a,list,of,names, and,1,2, 3,numbers

Parser example:

cp = ConfigParser(converters={'list': lambda x: [i.strip() for i in x.split(',')]})
cp.read('example.ini')
cp.getlist('Germ', 'germs')
['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']
cp['Germ'].getlist('germs')
['a', 'list', 'of', 'names', 'and', '1', '2', '3', 'numbers']

This is my personal favorite as no subclassing is necessary and I don't have to rely on an end user to perfectly write JSON or a list that can be interpreted by ast.literal_eval.

Functions are not valid as a React child. This may happen if you return a Component instead of from render

it also happens when you call a function from jsx directly rather than in an event. like

it will show the error if you write like

<h1>{this.myFunc}<h2>

it will go if you write:

<h1 onClick={this.myFunc}>Hit Me</h1>

Abstract Class:-Real Time Example

Here, Something about abstract class...

  1. Abstract class is an incomplete class so we can't instantiate it.
  2. If methods are abstract, class must be abstract.
  3. In abstract class, we use abstract and concrete method both.
  4. It is illegal to define a class abstract and final both.

Real time example--

If you want to make a new car(WagonX) in which all the another car's properties are included like color,size, engine etc.and you want to add some another features like model,baseEngine in your car.Then simply you create a abstract class WagonX where you use all the predefined functionality as abstract and another functionalities are concrete, which is is defined by you.
Another sub class which extend the abstract class WagonX,By default it also access the abstract methods which is instantiated in abstract class.SubClasses also access the concrete methods by creating the subclass's object.
For reusability the code, the developers use abstract class mostly.

abstract class WagonX
{
   public abstract void model();
   public abstract void color();
   public static void baseEngine()
    {
     // your logic here
    }
   public static void size()
   {
   // logic here
   }
}
class Car extends WagonX
{
public void model()
{
// logic here
}
public void color()
{
// logic here
}
}

Server Client send/receive simple text

    static void Main(string[] args)
    {
        //---listen at the specified IP and port no.---
        IPAddress localAdd = IPAddress.Parse(SERVER_IP);
        TcpListener listener = new TcpListener(localAdd, PORT_NO);
        Console.WriteLine("Listening...");
        listener.Start();
        while (true)
        {
            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();

            //---get the incoming data through a network stream---
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received : " + dataReceived);

            //---write back the text to the client---
            Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffer, 0, bytesRead);
            client.Close();
        }
        listener.Stop();
        Console.ReadLine();
    }

In addition to @Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.

Access Https Rest Service using Spring RestTemplate

Here is what I ended up with for the similar problem. The idea is the same as in @Avi's answer, but I also wanted to avoid the static "System.setProperty("https.protocols", "TLSv1");", so that any adjustments won't affect the system. Inspired by an answer from here http://www.coderanch.com/t/637177/Security/Disabling-handshake-message-Java

public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
    try {
        if (!(connection instanceof HttpsURLConnection)) {
            throw new RuntimeException("An instance of HttpsURLConnection is expected");
        }

        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                }
        };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));

        httpsConnection.setHostnameVerifier((hostname, session) -> true);

        super.prepareConnection(httpsConnection, httpMethod);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

/**
 * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
 * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
 */
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {

    private final SSLSocketFactory delegate;

    public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    private Socket overrideProtocol(final Socket socket) {
        if (!(socket instanceof SSLSocket)) {
            throw new RuntimeException("An instance of SSLSocket is expected");
        }
        ((SSLSocket) socket).setEnabledProtocols(new String[] {"SSLv3"});
        return socket;
    }
}
}

Local variable referenced before assignment?

Best solution: Don't use globals

>>> test1 = 0
>>> def test_func(x):
        return x + 1

>>> test1 = test_func(test1)
>>> test1
1

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

Find a class somewhere inside dozens of JAR files?

I didn't know of a utility to do it when I came across this problem, so I wrote the following:

public class Main {

    /**
     * 
     */
    private static String CLASS_FILE_TO_FIND =
            "class.to.find.Here";
    private static List<String> foundIn = new LinkedList<String>();

    /**
     * @param args the first argument is the path of the file to search in. The second may be the
     *        class file to find.
     */
    public static void main(String[] args) {
        if (!CLASS_FILE_TO_FIND.endsWith(".class")) {
            CLASS_FILE_TO_FIND = CLASS_FILE_TO_FIND.replace('.', '/') + ".class";
        }
        File start = new File(args[0]);
        if (args.length > 1) {
            CLASS_FILE_TO_FIND = args[1];
        }
        search(start);
        System.out.println("------RESULTS------");
        for (String s : foundIn) {
            System.out.println(s);
        }
    }

    private static void search(File start) {
        try {
            final FileFilter filter = new FileFilter() {

                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".jar") || pathname.isDirectory();
                }
            };
            for (File f : start.listFiles(filter)) {
                if (f.isDirectory()) {
                    search(f);
                } else {
                    searchJar(f);
                }
            }
        } catch (Exception e) {
            System.err.println("Error at: " + start.getPath() + " " + e.getMessage());
        }
    }

    private static void searchJar(File f) {
        try {
            System.out.println("Searching: " + f.getPath());
            JarFile jar = new JarFile(f);
            ZipEntry e = jar.getEntry(CLASS_FILE_TO_FIND);
            if (e == null) {
                e = jar.getJarEntry(CLASS_FILE_TO_FIND);
                if (e != null) {
                    foundIn.add(f.getPath());
                }
            } else {
                foundIn.add(f.getPath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Transfer data between databases with PostgreSQL

Just like leonbloy suggested, using two schemas in a database is the way to go. Suppose a source schema (old DB) and a target schema (new DB), you can try something like this (you should consider column names, types, etc.):

INSERT INTO target.Awards SELECT * FROM source.Nominations;

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Import existing Gradle Git project into Eclipse

Open eclipse and right click in the package explorer ? import Select gradle Browse to the location where you checked out Click “Build Model” Select all the projects and hit finish

Convert PDF to PNG using ImageMagick

Reducing the image size before output results in something that looks sharper, in my case:

convert -density 300 a.pdf -resize 25% a.png

Best way to access a control on another form in Windows Forms?

With the property (highlighted) I can get the instance of the MainForm class. But this is a good practice? What do you recommend?

For this I use the property MainFormInstance that runs on the OnLoad method.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LightInfocon.Data.LightBaseProvider;
using System.Configuration;

namespace SINJRectifier
{

    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            UserInterface userInterfaceObj = new UserInterface();
            this.chklbBasesList.Items.AddRange(userInterfaceObj.ExtentsList(this.chklbBasesList));
            MainFormInstance.MainFormInstanceSet = this; //Here I get the instance
        }

        private void btnBegin_Click(object sender, EventArgs e)
        {
            Maestro.ConductSymphony();
            ErrorHandling.SetExcecutionIsAllow();
        }
    }

    static class MainFormInstance  //Here I get the instance
    {
        private static MainForm mainFormInstance;

        public static MainForm MainFormInstanceSet { set { mainFormInstance = value; } }

        public static MainForm MainFormInstanceGet { get { return mainFormInstance; } }
    }
}

How to force Selenium WebDriver to click on element which is not currently visible?

I get into ElementNotVisibleException exception using selenium for functional tests on a django site with bootstrap glyphicons as links in templates as:

<a href="{% url 'item-add' %}"><span class="glyphicon glyphicon-plus text-danger"></span></a>

During my functional tests, the bootstrap style is not loaded, then trying to click on such links will raise ElementNotVisibleException. I manage to make them clickable just adding a space in the tag, like that:

<a href="{% url 'item-add' %}"><span class="glyphicon glyphicon-plus text-danger">&nbsp;</span></a>

jQuery's .click - pass parameters to user function

You need to use an anonymous function like this:

$('.leadtoscore').click(function() {
  add_event('shot')
});

You can call it like you have in the example, just a function name without parameters, like this:

$('.leadtoscore').click(add_event);

But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:

$('.leadtoscore').bind('click', { param: 'shot' }, add_event);

And access it in add_event, like this:

function add_event(event) {
  //event.data.param == "shot", use as needed
}

show distinct column values in pyspark dataframe: python

If you want to see the distinct values of a specific column in your dataframe , you would just need to write -

    df.select('colname').distinct().show(100,False)

This would show the 100 distinct values (if 100 values are available) for the colname column in the df dataframe.

If you want to do something fancy on the distinct values, you can save the distinct values in a vector

    a = df.select('colname').distinct()

Here, a would have all the distinct values of the column colname

Typescript import/as vs import/require?

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

How do I trim() a string in angularjs?

JS .trim() is supported in basically everthing, except IE 8 and below.

If you want it to work with that, then, you can use JQuery, but it'll need to be <2.0.0 (as they removed support for IE8 in the 2.x.x line).

Your other option, if you care about IE7/8 (As you mention earlier), is to add trim yourself:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

How to create an Oracle sequence starting with max value from a table?

use dynamic sql

BEGIN
            DECLARE
            maxId NUMBER;
              BEGIN
              SELECT MAX(id)+1
              INTO maxId
              FROM table_name;          
              execute immediate('CREATE SEQUENCE sequane_name MINVALUE '||maxId||' START WITH '||maxId||' INCREMENT BY 1 NOCACHE NOCYCLE');
              END;
END;

git replacing LF with CRLF

Git has three modes of how it treats line endings:

$ git config core.autocrlf
# that command will print "true" or "false" or "input"

You can set the mode to use by adding an additional parameter of true or false to the above command line.

If core.autocrlf is set to true, that means that any time you add a file to the git repo that git thinks is a text file, it will turn all CRLF line endings to just LF before it stores it in the commit. Whenever you git checkout something, all text files automatically will have their LF line endings converted to CRLF endings. This allows development of a project across platforms that use different line-ending styles without commits being very noisy because each editor changes the line ending style as the line ending style is always consistently LF.

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

If core.autocrlf is set to false, no line-ending conversion is ever performed, so text files are checked in as-is. This usually works ok, as long as all your developers are either on Linux or all on Windows. But in my experience I still tend to get text files with mixed line endings that end up causing problems.

My personal preference is to leave the setting turned ON, as a Windows developer.

See http://kernel.org/pub/software/scm/git/docs/git-config.html for updated info that includes the "input" value.

iOS 7 status bar overlapping UI

I've got a problem opening the inApp browser with phonegap. Gimi's fix worked well, but everytime I opened the inApp browser the screen was shrinked at the bottom. So I've added an if statement to check if the webview's y origin was 0. The inApp browser hasn't the y origin 0 anymore so it solved my problem.

// ios 7 status bar fix
- (void)viewWillAppear:(BOOL)animated
{
    // View defaults to full size.  If you want to customize the view's size, or its subviews (e.g. webView),
    // you can do so here.
    //Lower screen 20px on ios 7
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        if(self.webView.frame.origin.y == 0) {
            CGRect viewBounds = [self.webView bounds];
            viewBounds.origin.y = 20;
            viewBounds.size.height = viewBounds.size.height - 20;
            self.webView.frame = viewBounds;
        }
    }

    [super viewWillAppear:animated];
}

The solution is not really mine but I can't find the source. Hope it helps!

How to clear the Entry widget after a button is pressed in Tkinter?

Simply define a function and set the value of your Combobox to empty/null or whatever you want. Try the following.

def Reset():
    cmb.set("")

here, cmb is a variable in which you have assigned the Combobox. Now call that function in a button such as,

btn2 = ttk.Button(root, text="Reset",command=Reset)

How to set text color to a text view programmatically

TextView tt;
int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;
tt.setTextColor(color);

also

tt.setBackgroundColor(Integer.parseInt("d4d446", 16)+0xFF000000);

also

tt.setBackgroundColor(Color.parseColor("#d4d446"));

see:

Java/Android String to Color conversion

CodeIgniter - How to return Json response from controller

This is not your answer and this is an alternate way to process the form submission

$('.signinform').click(function(e) { 
      e.preventDefault();
      $.ajax({
      type: "POST",
      url: 'index.php/user/signin', // target element(s) to be updated with server response 
      dataType:'json',
      success : function(response){ console.log(response); alert(response)}
     });
}); 

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

Change values of select box of "show 10 entries" of jquery datatable

 $('#tblSub1View').dataTable({
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers",
                    "bDestroy": true,
                    "aoColumnDefs": [{
                        'bSortable': false,
                        'aTargets': [0, 1]
                    }],
                    "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                    "iDisplayLength": 10,
                });

What is the meaning of single and double underscore before an object name?

Excellent answers so far but some tidbits are missing. A single leading underscore isn't exactly just a convention: if you use from foobar import *, and module foobar does not define an __all__ list, the names imported from the module do not include those with a leading underscore. Let's say it's mostly a convention, since this case is a pretty obscure corner;-).

The leading-underscore convention is widely used not just for private names, but also for what C++ would call protected ones -- for example, names of methods that are fully intended to be overridden by subclasses (even ones that have to be overridden since in the base class they raise NotImplementedError!-) are often single-leading-underscore names to indicate to code using instances of that class (or subclasses) that said methods are not meant to be called directly.

For example, to make a thread-safe queue with a different queueing discipline than FIFO, one imports Queue, subclasses Queue.Queue, and overrides such methods as _get and _put; "client code" never calls those ("hook") methods, but rather the ("organizing") public methods such as put and get (this is known as the Template Method design pattern -- see e.g. here for an interesting presentation based on a video of a talk of mine on the subject, with the addition of synopses of the transcript).

Edit: The video links in the description of the talks are now broken. You can find the first two videos here and here.

Generating a random password in php

TL;DR:

  • Use random_int() and the given random_str() below.
  • If you don't have random_int(), use random_compat.

Explanation:

Since you are generating a password, you need to ensure that the password you generate is unpredictable, and the only way to ensure this property is present in your implementation is to use a cryptographically secure pseudorandom number generator (CSPRNG).

The requirement for a CSPRNG can be relaxed for the general case of random strings, but not when security is involved.

The simple, secure, and correct answer to password generation in PHP is to use RandomLib and don't reinvent the wheel. This library has been audited by industry security experts, as well as myself.

For developers who prefer inventing your own solution, PHP 7.0.0 will provide random_int() for this purpose. If you're still on PHP 5.x, we wrote a PHP 5 polyfill for random_int() so you can use the new API before PHP 7 is released. Using our random_int() polyfill is probably safer than writing your own implementation.

With a secure random integer generator on hand, generating a secure random string is easier than pie:

<?php
/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    $length,
    $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) {
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    if ($max < 1) {
        throw new Exception('$keyspace must be at least two characters long');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}

How to obtain the start time and end time of a day?

For java 8 the following single line statements are working. In this example I use UTC timezone. Please consider to change TimeZone that you currently used.

System.out.println(new Date());

final LocalDateTime endOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
final Date          endOfDayAsDate = Date.from(endOfDay.toInstant(ZoneOffset.UTC));

System.out.println(endOfDayAsDate);

final LocalDateTime startOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
final Date          startOfDayAsDate = Date.from(startOfDay.toInstant(ZoneOffset.UTC));

System.out.println(startOfDayAsDate);

If no time difference with output. Try: ZoneOffset.ofHours(0)

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

How to do a non-greedy match in grep?

Actualy the .*? only works in perl. I am not sure what the equivalent grep extended regexp syntax would be. Fortunately you can use perl syntax with grep so grep -P would work but grep -E which is same as egrep would not work (it would be greedy).

See also: http://blog.vinceliu.com/2008/02/non-greedy-regular-expression-matching.html

PHP-FPM doesn't write to error log

in my case I show that the error log was going to /var/log/php-fpm/www-error.log . so I commented this line in /etc/php-fpm.d/www.conf

php_flag[display_errors]   is commented
php_flag[display_errors] = on  log will be at /var/log/php-fpm/www-error.log

and as said above I also uncommented this line

catch_workers_output = yes

Now I can see logs in the file specified by nginx.

How to read input with multiple lines in Java

The easilest way is

import java.util.*;

public class Stdio4 {

public static void main(String[] args) {
    int a=0;
    int arr[] = new int[3];
    Scanner scan = new Scanner(System.in);
    for(int i=0;i<3;i++)
    { 
         a = scan.nextInt();  //Takes input from separate lines
         arr[i]=a;


    }
    for(int i=0;i<3;i++)
    { 
         System.out.println(arr[i]);   //outputs in separate lines also
    }

}

}

Jasmine JavaScript Testing - toBe vs toEqual

To quote the jasmine github project,

expect(x).toEqual(y); compares objects or primitives x and y and passes if they are equivalent

expect(x).toBe(y); compares objects or primitives x and y and passes if they are the same object

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

This error happened to me, generally it'll be a problem due to not including the mysql-connector.jar in your eclipse project (or your IDE).

In my case, it was because of a problem on the OS.

I was editing a table in phpmyadmin, and mysql hung, I restarted Ubuntu. I cleaned the project without being successful. This morning, when I've tried the web server, it work perfectly the first time.

At the first reboot, the OS recognized that there was a problem, and after the second one, it was fixed. I hope this will save some time to somebody that "could" have this problem!

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

How to update a claim in ASP.NET Identity?

You can update claims for the current user by implementing a CookieAuthenticationEvents class and overriding ValidatePrincipal. There you can remove the old claim, add the new one, and then replace the principal using CookieValidatePrincipalContext.ReplacePrincipal. This does not affect any claims stored in the database. This is using ASP.NET Core Identity 2.2.

public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
    string newAccountNo = "102";

    public override Task ValidatePrincipal(CookieValidatePrincipalContext context)
    {
        // first remove the old claim
        var claim = context.Principal.FindFirst(ClaimTypes.UserData);
        if (claim != null)
        {
            ((ClaimsIdentity)context.Principal.Identity).RemoveClaim(claim);
        }

        // add the new claim
        ((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim(ClaimTypes.UserData, newAccountNo));

        // replace the claims
        context.ReplacePrincipal(context.Principal);
        context.ShouldRenew = true;

        return Task.CompletedTask;
    }
}

You need to register the events class in Startup.cs:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddScoped<MyCookieAuthenticationEvents>();

    services.ConfigureApplicationCookie(o =>
    {
        o.EventsType = typeof(MyCookieAuthenticationEvents);
    });
}

You can inject services into the events class to access the new AccountNo value but as per the warning on this page you should avoid doing anything too expensive:

Warning

The approach described here is triggered on every request. Validating authentication cookies for all users on every request can result in a large performance penalty for the app.

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

how to check if object already exists in a list

If you use EF core add

 .UseSerialColumn();

Example

modelBuilder.Entity<JobItem>(entity =>
        {
            entity.ToTable("jobs");

            entity.Property(e => e.Id)
                .HasColumnName("id")
                .UseSerialColumn();
});

Partial Dependency (Databases)

I hope this explaination gives a more intuitive appeal to dependency than the answers previously given.

Functional Dependency

An analysis of dependency operates on the attribute level, i.e. one or more attribute is determined by another attribute, it comes before the concept of keys. 'The role of a key is based on the concept of determination. 'Determination is the state in which knowing the value of one attribute makes it possible to determine the value of another.' Database Systems 12ed

Functional dependency is when one or more attributes determine one or more attributes. For instance:

Social Security Number -> First Name, Last Name.

However, by definition of functional dependency:

(SSN, First Name) -> Last Name

This is also a valid functional dependency. The determinants (The attribute that which determines another attribution) are called super key.

Full Functional Dependency

Thus, as a subset of functional dependency, there is the concept of full functional dependency, where the bare minimal determinant is considered. We refer those bare minimal determinants collectively as one candidate key (weird linguistic quirk in my opinion, like the concept of vector).

Partial Functional Dependency

However, sometimes one of the attributes in the candidate key is sufficient to determine another attribute(s), BUT not all, in a relation (a table with no rows). That, is when you have a partial functional dependency within a relation.

Android Studio AVD - Emulator: Process finished with exit code 1

I had same issue for windows , the cause of the problem was currupted or missing dll files. I had to change them.

In android studio ,

Help Menu -> Show log in explorer.

It opens log folder, where you can find all logs . In my situation error like "Emulator terminated with exit code -1073741515"

  1. Try to run emulator from command prompt ,
  • Go to folder ~\Android\Sdk\emulator

  • Run this command:

    emulator.exe -netdelay none -netspeed full -avd <virtual device name> 
    
    ex: emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_26.avd
    

    You can find this command from folder ~.android\avd\xxx.avd\emu-launch-params.txt

  1. If you get error about vcruntime140 ,
  • Search and download the appropriate vcruntime140.dll file for your system from the internet (32 / 64 bit version) , and replace it with the vcruntime140.dll file in the folder ~\Android\Sdk\emulator

  • Try step 1

  • If you get error about vcruntime140_1 , change the file name as vcruntime140_1.dll ,try step 1

  1. If you get error about msvcp140.dll
  • Search and download the appropriate msvcp140.dll file for your system from the internet (32 / 64 bit version)
  • Replace the file in the folder C:\Windows\System32 with file msvcp140.dll
  • Try step 1

If it runs , you can run it from Android Studio also.

How do I get the current date and current time only respectively in Django?

 import datetime

Current Date and time

     print(datetime.datetime.now())
     #2019-09-08 09:12:12.473393

Current date only

     print(datetime.date.today())
     #2019-09-08

Current year only

     print(datetime.date.today().year)
     #2019

Current month only

     print(datetime.date.today().month)
     #9

Current day only

     print(datetime.date.today().day)
     #8

ExecJS and could not find a JavaScript runtime

For amazon linux(AMI):

sudo yum install nodejs npm --enablerepo=epel

jQuery change event on dropdown

Or you can use this javascript

$(function () {
    $("#projectKey").change(function () {
        alert($('#projectKey option:selected').text());
    });
});

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException in Netty means your game server tries to send data to a client, but that client has closed connection to your server.

And that exception is not the only one! There're several others. See BadClientSilencer in Xitrum. I had to add that to prevent those errors from messing my log file.

How to change an Android app's name?

It depends what you want to do. I personally wanted to rename my project so it didn't say MainActivity at the top of the app and underneath the icon on my phone menu.

To do this I went into the Android Manifest.xml file and edited

<activity
        android:name=".MainActitivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And edited the android:name=".Mynewname" and then edited the string title_activity_main in the strings.xml file to match the name.

Hope that helps!

find difference between two text files with one item per line

You can use the comm command to compare two sorted files

comm -13 <(sort file1) <(sort file2)

Difference Between Schema / Database in MySQL

Microsoft SQL Server for instance, Schemas refer to a single user and is another level of a container in the order of indicating the server, database, schema, tables, and objects.

For example, when you are intending to update dbo.table_a and the syntax isn't full qualified such as UPDATE table.a the DBMS can't decide to use the intended table. Essentially by default the DBMS will utilize myuser.table_a

How can I add a line to a file in a shell script?

This adds custom text at the beginning of your file:

echo 'your_custom_escaped_content' > temp_file.csv
cat testfile.csv >> temp_file.csv
mv temp_file.csv testfile.csv

Switch statement for greater-than/less-than

I hate using 30 if statements

I had the same situation lately, that's how I solved it:

before:

if(wind_speed >= 18) {
    scale = 5;
} else if(wind_speed >= 12) {
    scale = 4;
} else if(wind_speed >= 9) {
    scale = 3;
} else if(wind_speed >= 6) {
    scale = 2;
} else if(wind_speed >= 4) {
    scale = 1;
}

after:

var scales = [[4, 1], [6, 2], [9, 3], [12, 4], [18, 5]];
scales.forEach(function(el){if(wind_speed > el[0]) scale = el[1]});

And if you set "1, 2, 3, 4, 5" then it can be even simpler:

var scales = [4, 6, 9, 12, 18];
scales.forEach(function(el){if(wind_speed >= el) scale++});

Installing a specific version of angular with angular cli

I would suggest using NVM to keep different versions of node and npm and then install the compatible angular-cli

sqlalchemy IS NOT NULL select

In case anyone else is wondering, you can use is_ to generate foo IS NULL:

>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL

Remove a marker from a GoogleMap

use the following code:

 mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
       @Override
       public boolean onMarkerClick(Marker marker) {

           marker.remove();
           return true;
       }
   });

once you click on "a marker", you can remove it.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

I would try to specify something like

var searchPattern = "as?x";

it should work.

Difference Between Select and SelectMany

Select many is like cross join operation in SQL where it takes the cross product.
For example if we have

Set A={a,b,c}
Set B={x,y}

Select many can be used to get the following set

{ (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }

Note that here we take the all the possible combinations that can be made from the elements of set A and set B.

Here is a LINQ example you can try

List<string> animals = new List<string>() { "cat", "dog", "donkey" };
List<int> number = new List<int>() { 10, 20 };

var mix = number.SelectMany(num => animals, (n, a) => new { n, a });

the mix will have following elements in flat structure like

{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}

HTML 5 Geo Location Prompt in Chrome

None of the above helped me.

After a little research I found that as of M50 (April 2016) - Chrome now requires a secure origin (such as HTTPS) for Geolocation.

Deprecated Features on Insecure Origins

The host "localhost" is special b/c its "potentially secure". You may not see errors during development if you are deploying to your development machine.

SQL - Update multiple records in one query

Execute the below code if you want to update all record in all columns:

update config set column1='value',column2='value'...columnN='value';

and if you want to update all columns of a particular row then execute below code:

update config set column1='value',column2='value'...columnN='value' where column1='value'

Check if multiple strings exist in another string

Just some more info on how to get all list elements availlable in String

a = ['a', 'b', 'c']
str = "a123" 
list(filter(lambda x:  x in str, a))

How to fill in proxy information in cntlm config file?

Just to add , if you are performing a "pip" operation , you might need to add and additional "--proxy=localhost:port_number"

e.g pip install --proxy=localhost:3128 matplotlib

Visit this link to see full details.

Django Rest Framework -- no module named rest_framework

In my case, I had installed it in the virtualenv but forgot to activate the virtualenv while running the command

 python3 manage.py makemigrations 

So in my case I had to just activate the environment and then run the command

source [virtualenv folder-name]/bin/activate
python3 manage.py makemigrations

This solved my problem.

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

In android studio add/change this line at the end of gradle.properties (Global Properties):

...
org.gradle.jvmargs=-XX\:MaxHeapSize\=1024m -Xmx1024m 

if it doesn't work you can retry with bigger than 1024 heap size.

Insert 2 million rows into SQL Server quickly

  1. I think its better you read data of text file in DataSet

  2. Try out SqlBulkCopy - Bulk Insert into SQL from C# App

    // connect to SQL
    using (SqlConnection connection = new SqlConnection(connString))
    {
        // make sure to enable triggers
        // more on triggers in next post
        SqlBulkCopy bulkCopy = new SqlBulkCopy(
            connection, 
            SqlBulkCopyOptions.TableLock | 
            SqlBulkCopyOptions.FireTriggers | 
            SqlBulkCopyOptions.UseInternalTransaction,
            null
            );
    
        // set the destination table name
        bulkCopy.DestinationTableName = this.tableName;
        connection.Open();
    
        // write the data in the "dataTable"
        bulkCopy.WriteToServer(dataTable);
        connection.Close();
    }
    // reset
    this.dataTable.Clear();
    

or

after doing step 1 at the top

  1. Create XML from DataSet
  2. Pass XML to database and do bulk insert

you can check this article for detail : Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function

But its not tested with 2 million record, it will do but consume memory on machine as you have to load 2 million record and insert it.

How can I change the color of a Google Maps marker?

Personally, I think the icons generated by the Google Charts API look great and are easy to customise dynamically.

See my answer on Google Maps API 3 - Custom marker color for default (dot) marker

How can I run a PHP script in the background after a form is submitted?

In my case I have 3 params, one of them is string (mensaje):

exec("C:\wamp\bin\php\php5.5.12\php.exe C:/test/N/trunk/api/v1/Process.php $idTest2 $idTest3 \"$mensaje\" >> c:/log.log &");

In my Process.php I have this code:

if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3]))
{   
    die("Error.");
} 

$idCurso = $argv[1];
$idDestino = $argv[2];
$mensaje = $argv[3];

How to set variables in HIVE scripts

You can store the output of another query in a variable and latter you can use the same in your code:

set var=select count(*) from My_table;
${hiveconf:var};

How to convert a Java object (bean) to key-value pairs (and vice versa)?

JSON, for example using XStream + Jettison, is a simple text format with key value pairs. It is supported for example by the Apache ActiveMQ JMS message broker for Java object exchange with other platforms / languages.

How to take MySQL database backup using MySQL Workbench?

In workbench 6.0 Connect to any of the database. You will see two tabs.

1.Management 2. Schemas

By default Schemas tab is selected. Select Management tab then select Data Export . You will get list of all databases. select the desired database and and the file name and ther options you wish and start export. You are done with backup.

How to add calendar events in Android?

Just in case if someone needs this for Xamarin in c#:

        Intent intent = new Intent(Intent.ActionInsert);
        intent.SetData(Android.Provider.CalendarContract.Events.ContentUri);
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventBeginTime, Utils.Tools.CurrentTimeMillis(game.Date));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.AllDay, false);
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.EventLocation, "Location");
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Description, "Description");
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventEndTime, Utils.Tools.CurrentTimeMillis(game.Date.AddHours(2)));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Title, "Title");
        StartActivity(intent);

Helper Functions:

    private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long CurrentTimeMillis(DateTime date)
    {
        return (long)(date.ToUniversalTime() - Jan1st1970).TotalMilliseconds;
    }

How to determine whether a year is a leap year?

Use calendar.isleap:

import calendar
print(calendar.isleap(1900))

Fastest way to flatten / un-flatten nested JSON objects

3 ½ Years later...

For my own project I wanted to flatten JSON objects in mongoDB dot notation and came up with a simple solution:

/**
 * Recursively flattens a JSON object using dot notation.
 *
 * NOTE: input must be an object as described by JSON spec. Arbitrary
 * JS objects (e.g. {a: () => 42}) may result in unexpected output.
 * MOREOVER, it removes keys with empty objects/arrays as value (see
 * examples bellow).
 *
 * @example
 * // returns {a:1, 'b.0.c': 2, 'b.0.d.e': 3, 'b.1': 4}
 * flatten({a: 1, b: [{c: 2, d: {e: 3}}, 4]})
 * // returns {a:1, 'b.0.c': 2, 'b.0.d.e.0': true, 'b.0.d.e.1': false, 'b.0.d.e.2.f': 1}
 * flatten({a: 1, b: [{c: 2, d: {e: [true, false, {f: 1}]}}]})
 * // return {a: 1}
 * flatten({a: 1, b: [], c: {}})
 *
 * @param obj item to be flattened
 * @param {Array.string} [prefix=[]] chain of prefix joined with a dot and prepended to key
 * @param {Object} [current={}] result of flatten during the recursion
 *
 * @see https://docs.mongodb.com/manual/core/document/#dot-notation
 */
function flatten (obj, prefix, current) {
  prefix = prefix || []
  current = current || {}

  // Remember kids, null is also an object!
  if (typeof (obj) === 'object' && obj !== null) {
    Object.keys(obj).forEach(key => {
      this.flatten(obj[key], prefix.concat(key), current)
    })
  } else {
    current[prefix.join('.')] = obj
  }

  return current
}

Features and/or caveats

  • It only accepts JSON objects. So if you pass something like {a: () => {}} you might not get what you wanted!
  • It removes empty arrays and objects. So this {a: {}, b: []} is flattened to {}.

Key Presses in Python

AutoHotKey is perfect for this kind of tasks (keyboard automation / remapping)

Script to send "A" 100 times:

Send {A 100}

That's all

EDIT: to send the keys to an specific application:

WinActivate Word
Send {A 100}

javascript - Create Simple Dynamic Array

I hope you have to get last element from array variable so my solution

var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var mynumber = arr [arr .length - 1];
//var mynumber = 10;

Count number of occurrences of a pattern in a file (even on same line)

Hack grep's color function, and count how many color tags it prints out:

echo -e "a\nb  b b\nc\ndef\nb e brb\nr" \
| GREP_COLOR="033" grep --color=always  b \
| perl -e 'undef $/; $_=<>; s/\n//g; s/\x1b\x5b\x30\x33\x33/\n/g; print $_' \
| wc -l

Check/Uncheck all the checkboxes in a table

This will select and deselect all checkboxes:

function checkAll()
{
     var checkboxes = document.getElementsByTagName('input'), val = null;    
     for (var i = 0; i < checkboxes.length; i++)
     {
         if (checkboxes[i].type == 'checkbox')
         {
             if (val === null) val = checkboxes[i].checked;
             checkboxes[i].checked = val;
         }
     }
 }

Demo

Update:

You can use querySelectAll directly on the table to get the list of checkboxes instead of searching the whole document, but It might not be compatible with old browsers so you need to check that first:

 function checkAll()
 {
     var table = document.getElementById ('dataTable');
     var checkboxes = table.querySelectorAll ('input[type=checkbox]');
     var val = checkboxes[0].checked;
     for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = val;
 }

Or to be more specific for the provided html structure in the OP question, this would be more efficient when selecting the checkboxes as it will access them directly instead of searching for them:

function checkAll (tableID)
{
    var table = document.getElementById (tableID);
    var val = table.rows[0].cells[0].children[0].checked;
    for (var i = 1; i < table.rows.length; i++)
    {
        table.rows[i].cells[0].children[0].checked = val;
    }
}

Demo

How to delete a specific file from folder using asp.net

In my project i am using ajax and i create a web method in my code behind like this

in front

 $("#attachedfiles a").live("click", function () {
            var row = $(this).closest("tr");
            var fileName = $("td", row).eq(0).html();
            $.ajax({
                type: "POST",
                url: "SendEmail.aspx/RemoveFile",
                data: '{fileName: "' + fileName + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () { },
                failure: function (response) {
                    alert(response.d);
                }
            });
            row.remove();
        });  

in code behind

        [WebMethod]
        public static void RemoveFile(string fileName)
        {
            List<HttpPostedFile> files = (List<HttpPostedFile>)HttpContext.Current.Session["Files"];
            files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));

            if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName)))
            {
                System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName));
            }
        }

i think this will help you.

ReactJS SyntheticEvent stopPropagation() only works with React events?

A quick workaround is using window.addEventListener instead of document.addEventListener.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Enable TLs 1.2 from IE and add the following

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

Return string without trailing slash

I'd use a regular expression:

function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}

You'll want to make sure that the variable site is a string, though.

Generating CSV file for Excel, how to have a newline inside a value

Recently I had similar problem, I solved it by importing a HTML file, the baseline example would be like this:

<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
  <head>
    <style>
      <!--
      br {mso-data-placement:same-cell;}
      -->
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td>first line<br/>second line</td>
        <td style="white-space:normal">first line<br/>second line</td>
      </tr>
    </table>
  </body>
</html>

I know, it is not a CSV, and might work differently for various versions of Excel, but I think it is worth a try.

I hope this helps ;-)

Getting current directory in VBScript

'-----Implementation of VB6 App object in VBScript-----
Class clsApplication
    Property Get Path()
          Dim sTmp
          If IsObject(Server) Then
               'Classic ASP
               Path = Server.MapPath("../")
          ElseIf IsObject(WScript) Then 
               'Windows Scripting Host
               Path = Left(WScript.ScriptFullName, InStr(WScript.ScriptFullName, WScript.ScriptName) - 2)
          ElseIf IsObject(window) Then
               'Internet Explorer HTML Application (HTA)
               sTmp = Replace( Replace(Unescape(window.location), "file:///", "") ,"/", "\")
               Path = Left(sTmp, InstrRev( sTmp , "\") - 1)
          End If
    End Property
End Class
Dim App : Set App = New clsApplication 'use as App.Path

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

try

unset($_POST);
unset($_REQUEST);
header('Location: ...');

it worked for me

How to open an Excel file in C#?

For opening a file, try this:

objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.xls",
    missing, missing, missing, missing, missing, missing, missing,
    missing, missing, missing, missing, missing,missing, missing);

You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

Select something that has more/less than x character

JonH has covered very well the part on how to write the query. There is another significant issue that must be mentioned too, however, which is the performance characteristics of such a query. Let's repeat it here (adapted to Oracle):

SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(EmployeeName) > 4;

This query is restricting the result of a function applied to a column value (the result of applying the LENGTH function to the EmployeeName column). In Oracle, and probably in all other RDBMSs, this means that a regular index on EmployeeName will be useless to answer this query; the database will do a full table scan, which can be really costly.

However, various databases offer a function indexes feature that is designed to speed up queries like this. For example, in Oracle, you can create an index like this:

CREATE INDEX EmployeeTable_EmployeeName_Length ON EmployeeTable(LENGTH(EmployeeName));

This might still not help in your case, however, because the index might not be very selective for your condition. By this I mean the following: you're asking for rows where the name's length is more than 4. Let's assume that 80% of the employee names in that table are longer than 4. Well, then the database is likely going to conclude (correctly) that it's not worth using the index, because it's probably going to have to read most of the blocks in the table anyway.

However, if you changed the query to say LENGTH(EmployeeName) <= 4, or LENGTH(EmployeeName) > 35, assuming that very few employees have names with fewer than 5 character or more than 35, then the index would get picked and improve performance.

Anyway, in short: beware of the performance characteristics of queries like the one you're trying to write.

How to find rows that have a value that contains a lowercase letter

IN MS SQL server use the COLLATE clause.

SELECT Column1
FROM Table1
WHERE Column1 COLLATE Latin1_General_CS_AS = 'casesearch'

Adding COLLATE Latin1_General_CS_AS makes the search case sensitive.

Default Collation of the SQL Server installation SQL_Latin1_General_CP1_CI_AS is not case sensitive.

To change the collation of the any column for any table permanently run following query.

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(20)
COLLATE Latin1_General_CS_AS

To know the collation of the column for any table run following Stored Procedure.

EXEC sp_help DatabaseName

Source : SQL SERVER – Collate – Case Sensitive SQL Query Search

Docker official registry (Docker Hub) URL

It's just docker pull busybox, are you using an up to date version of the docker client. I think they stopped supporting clients lower than 1.5.

Incidentally that curl works for me:

$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]

Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

The easiest solution to workaround this is to create 'temporary' input with type submit and trigger click:

var submitInput = $("<input type='submit' />");
$("#aspnetForm").append(submitInput);
submitInput.trigger("click");

Converting ArrayList to Array in java

This is the right answer you want and this solution i have run my self on netbeans

ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);

int b[]= new int [6];
        Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
        m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
    b[i]=m[i]; 
    System.out.println(b[i]);
}   
    System.out.println(a.size());

Pycharm: run only part of my Python file

  1. Go to File >> Settings >> Plugins and install the plugin PyCharm cell mode
  2. Go to File >> Settings >> Appearance & Behavior >> Keymap and assign your keyboard shortcuts for Run Cell and Run Cell and go to next

A cell is delimited by ##

Ref https://plugins.jetbrains.com/plugin/7858-pycharm-cell-mode

Python truncate a long string

Even more concise:

data = data[:75]

If it is less than 75 characters there will be no change.

Iterating through a string word by word

This is one way to do it:

string = "this is a string"
ssplit = string.split()
for word in ssplit:
    print (word)

Output:

this
is
a
string

Firebase Storage How to store and Retrieve images

Update (20160519): Firebase just released a new feature called Firebase Storage. This allows you to upload images and other non-JSON data to a dedicated storage service. We highly recommend that you use this for storing images, instead of storing them as base64 encoded data in the JSON database.

You certainly can! Depending on how big your images are, you have a couple options:

1. For smaller images (under 10mb)

We have an example project that does that here: https://github.com/firebase/firepano

The general approach is to load the file locally (using FileReader) so you can then store it in Firebase just as you would any other data. Since images are binary files, you'll want to get the base64-encoded contents so you can store it as a string. Or even more convenient, you can store it as a data: url which is then ready to plop in as the src of an img tag (this is what the example does)!

2. For larger images

Firebase does have a 10mb (of utf8-encoded string data) limit. If your image is bigger, you'll have to break it into 10mb chunks. You're right though that Firebase is more optimized for small strings that change frequently rather than multi-megabyte strings. If you have lots of large static data, I'd definitely recommend S3 or a CDN instead.

What is the difference between a symbolic link and a hard link?

Symbolic links link to a path name. This can be anywhere in a system's file tree, and doesn't even have to exist when the link is created. The target path can be relative or absolute.

Hard links are additional pointers to an inode, meaning they can exist only on the same volume as the target. Additional hard links to a file are indistinguishable from the "original" name used to reference a file.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Rename multiple files in a directory in Python

Here is a more general solution:

This code can be used to remove any particular character or set of characters recursively from all filenames within a directory and replace them with any other character, set of characters or no character.

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('C:\FolderName')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('#', '-')
    if newname != path:
        os.rename(path, newname)

Bad Request - Invalid Hostname IIS7

So, I solved this by going to my website in IIS Manager and changing the host name in site bindings from localhost to *. Started working immediately.

Site Bindings in IIS

What is the best way to add options to a select from a JavaScript object with jQuery?

The simple way is:

$('#SelectId').html("<option value='0'>select</option><option value='1'>Laguna</option>");

show/hide html table columns using css

I don't think there is anything you can do to avoid what you are already doing, however, if you are building the table on the client with javascript, you can always add the style rules dynamically, so you can allow for any number of columns without cluttering up your css file with all those rules. See http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript if you don't know how to do this.

Edit: For your "sticky" toggle, you should just append class names rather than replacing them. For instance, you can give it a class name of "hide2 hide3" etc. I don't think you really need the "show" classes, since that would be the default. Libraries like jQuery make this easy, but in the absence, a function like this might help:

var modifyClassName = function (elem, add, string) {
var s = (elem.className) ? elem.className : "";
var a = s.split(" ");
if (add) {
  for (var i=0; i<a.length; i++) {
      if (a[i] == string) {
          return;
          }
      }
  s += " " + string;
  }
else {
    s = "";
    for (var i=0; i<a.length; i++) {
        if (a[i] != string)
            s += a[i] + " "; 
        }
    }
elem.className = s;
}

How to get a MemoryStream from a Stream in .NET?

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

MySQL Workbench: How to keep the connection alive

in mysql-workbech 5.7 edit->preference-> SSH -> SSH Connect timeout (for SSH DB connection) enter image description here

'this' vs $scope in AngularJS controllers

The reason 'addPane' is assigned to this is because of the <pane> directive.

The pane directive does require: '^tabs', which puts the tabs controller object from a parent directive, into the link function.

addPane is assigned to this so that the pane link function can see it. Then in the pane link function, addPane is just a property of the tabs controller, and it's just tabsControllerObject.addPane. So the pane directive's linking function can access the tabs controller object and therefore access the addPane method.

I hope my explanation is clear enough.. it's kind of hard to explain.

count distinct values in spreadsheet

Not exactly what the user asked, but an easy way to just count unique values:

Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:

=COUNTUNIQUE(A1:B10)

enabling cross-origin resource sharing on IIS7

The 405 response is a "Method not allowed" response. It sounds like your server isn't properly configured to handle CORS preflight requests. You need to do two things:

1) Enable IIS7 to respond to HTTP OPTIONS requests. You are getting the 405 because IIS7 is rejecting the OPTIONS request. I don't know how to do this as I'm not familiar with IIS7, but there are probably others on Stack Overflow who do.

2) Configure your application to respond to CORS preflight requests. You can do this by adding the following two lines underneath the Access-Control-Allow-Origin line in the <customHeaders> section:

<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />

You may have to add other values to the Access-Control-Allow-Headers section based on what headers your request is asking for. Do you have the sample code for making a request?

You can learn more about CORS and CORS preflight here: http://www.html5rocks.com/en/tutorials/cors/

C++ unordered_map using a custom class type as the key

check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.

  • the custom class must implement the == operator
  • must create a hash function for the class (for primitive types like int and also types like string the hash function is predefined)

Background color for Tk in Python

Its been updated so

root.configure(background="red")

is now:

root.configure(bg="red")

How can I create an array/list of dictionaries in python?

Use

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

Why does sudo change the PATH?

Just comment out "Defaults env_reset" in /etc/sudoers

How do I write a correct micro-benchmark in Java?

Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.

How to check SQL Server version

Following are possible ways to see the version:

Method 1: Connect to the instance of SQL Server, and then run the following query:

Select @@version

An example of the output of this query is as follows:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 
10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Express 
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.

Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files. The entries may resemble the following:

2011-03-27 22:31:33.50 Server      Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)                 Mar 29 2009 10:11:52                 Copyright (c) 1988-2008 Microsoft Corporation                Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.

Method 4: Connect to the instance of SQL Server, and then run the following query:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Note This query works with any instance of SQL Server 2000 or of a later version

Searching for Text within Oracle Stored Procedures

 SELECT * FROM ALL_source WHERE UPPER(text) LIKE '%BLAH%'

EDIT Adding additional info:

 SELECT * FROM DBA_source WHERE UPPER(text) LIKE '%BLAH%'

The difference is dba_source will have the text of all stored objects. All_source will have the text of all stored objects accessible by the user performing the query. Oracle Database Reference 11g Release 2 (11.2)

Another difference is that you may not have access to dba_source.

How to use if-else option in JSTL

Yes, but it's clunky as hell, e.g.

<c:choose>
  <c:when test="${condition1}">
    ...
  </c:when>
  <c:when test="${condition2}">
    ...
  </c:when>
  <c:otherwise>
    ...
  </c:otherwise>
</c:choose>

Vue.js redirection to another page

When inside a component script tag you can use the router and do something like this

this.$router.push('/url-path')

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

I fixed this error on Ubuntu by carefully following the instructions for installing R. This included:

  1. adding deb http://cran.utstat.utoronto.ca/bin/linux/ubuntu trusty/ to my /etc/apt/sources.list file
  2. Running sudo apt-get update
  3. Running sudo apt-get install r-base-dev

For step 1 you can chose any CRAN download mirror in place of my University of Toronto one if you would like.

What's a good (free) visual merge tool for Git? (on windows)

  • TortoiseMerge (part of ToroiseSVN) is much better than kdiff3 (I use both and can compare);
  • p4merge (from Perforce) works also very well;
  • Diffuse isn't so bad;
  • Diffmerge from SourceGear has only one flaw in handling UTF8-files without BOM, making in unusable for this case.

How to remove extension from string (only real extension!)

$image_name = "this-is.file.name.jpg";
$last_dot_index = strrpos($image_name, ".");
$without_extention = substr($image_name, 0, $last_dot_index);

Output:

this-is.file.name

PHP, display image with Header()

There is a better why to determine type of an image. with exif_imagetype

If you use this function, you can tell image's real extension.

with this function filename's extension is completely irrelevant, which is good.

function setHeaderContentType(string $filePath): void
{
    $numberToContentTypeMap = [
        '1' => 'image/gif',
        '2' => 'image/jpeg',
        '3' => 'image/png',
        '6' => 'image/bmp',
        '17' => 'image/ico'
    ];

    $contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;
    
    if ($contentType === null) {
        throw new Exception('Unable to determine content type of file.');
    }

    header("Content-type: $contentType");
}

You can add more types from the link.

Hope it helps.

how to use javascript Object.defineProperty

_x000D_
_x000D_
import { CSSProperties } from 'react'_x000D_
import { BLACK, BLUE, GREY_DARK, WHITE } from '../colours'_x000D_
_x000D_
export const COLOR_ACCENT = BLUE_x000D_
export const COLOR_DEFAULT = BLACK_x000D_
export const FAMILY = "'Segoe UI', sans-serif"_x000D_
export const SIZE_LARGE = '26px'_x000D_
export const SIZE_MEDIUM = '20px'_x000D_
export const WEIGHT = 400_x000D_
_x000D_
type Font = {_x000D_
  color: string,_x000D_
  size: string,_x000D_
  accent: Font,_x000D_
  default: Font,_x000D_
  light: Font,_x000D_
  neutral: Font,_x000D_
  xsmall: Font,_x000D_
  small: Font,_x000D_
  medium: Font,_x000D_
  large: Font,_x000D_
  xlarge: Font,_x000D_
  xxlarge: Font_x000D_
} & (() => CSSProperties)_x000D_
_x000D_
function font (this: Font): CSSProperties {_x000D_
  const css = {_x000D_
    color: this.color,_x000D_
    fontFamily: FAMILY,_x000D_
    fontSize: this.size,_x000D_
    fontWeight: WEIGHT_x000D_
  }_x000D_
  delete this.color_x000D_
  delete this.size_x000D_
  return css_x000D_
}_x000D_
_x000D_
const dp = (type: 'color' | 'size', name: string, value: string) => {_x000D_
  Object.defineProperty(font, name, { get () {_x000D_
    this[type] = value_x000D_
    return this_x000D_
  }})_x000D_
}_x000D_
_x000D_
dp('color', 'accent', COLOR_ACCENT)_x000D_
dp('color', 'default', COLOR_DEFAULT)_x000D_
dp('color', 'light', COLOR_LIGHT)_x000D_
dp('color', 'neutral', COLOR_NEUTRAL)_x000D_
dp('size', 'xsmall', SIZE_XSMALL)_x000D_
dp('size', 'small', SIZE_SMALL)_x000D_
dp('size', 'medium', SIZE_MEDIUM)_x000D_
_x000D_
export default font as Font
_x000D_
_x000D_
_x000D_

How to create a HTTP server in Android?

Consider this one: https://github.com/NanoHttpd/nanohttpd. Very small, written in Java. I used it without any problem.

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

Just to be complete...

For 32 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

*******OR*******

For 64 bit OS you must add a registry entry to:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

This entry must be a DWORD, with the name being the name of your executable, that hosts the Webbrowser control; i.e.:

myappname.exe (DON'T USE "Contoso.exe" as in the MSDN web page...it's just a placeholder name)

Then give it a DWORD value, according to the table on:

http://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx#browser_emulation

I changed to 11001 decimal or 0x2AF9 hex --- (IE 11 EMULATION) since that isn't the DEFAULT value (if you have IE 11 installed -- or whatever version).

That MSDN article contains notes on several other Registry changes that affects Internet Explorer web browser behavior.

Query to check index on a table

On SQL Server, this will list all the indexes for a specified table:

select * from sys.indexes
where object_id = (select object_id from sys.objects where name = 'MYTABLE')

This query will list all tables without an index:

SELECT name
FROM sys.tables 
WHERE OBJECTPROPERTY(object_id,'IsIndexed') = 0

And this is an interesting MSDN FAQ on a related subject:
Querying the SQL Server System Catalog FAQ

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In my case I am using Visual Studio and Nuget packages its failing because have duplicated libraries one in the same folder as jQuery and another in the folder umd. By removing the popper javascript files from the same level as jQuery and refere to the popper.js inside the umd folder fixed my issue and I can see the tooltips correctly.

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

nvm is not compatible with the npm config "prefix" option:

Delete and Reset the prefix

$ npm config delete prefix 
$ npm config set prefix $NVM_DIR/versions/node/v6.11.1

Note: Change the version number with the one indicated in the error message.

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local" Run "npm config delete prefix" or "nvm use --delete-prefix v6.11.1 --silent" to unset it.


Credits to @gabfiocchi on Github - "You need to overwrite nvm prefix"

Counting number of characters in a file through shell script

To get exact character count of string, use printf, as opposed to echo, cat, or running wc -c directly on a file, because using echo, cat, etc will count a newline character, which will give you the amount of characters including the newline character. So a file with the text 'hello' will print 6 if you use echo etc, but if you use printf it will return the exact 5, because theres no newline element to count.

How to use printf for counting characters within strings:

$printf '6chars' | wc -m
6

To turn this into a script you can run on a text file to count characters, save the following in a file called print-character-amount.sh:

#!/bin/bash
characters=$(cat "$1")
printf "$characters" | wc -m

chmod +x on file print-character-amount.sh containing above text, place the file in your PATH (i.e. /usr/bin/ or any directory exported as PATH in your .bashrc file) then to run script on text file type:

print-character-amount.sh file-to-count-characters-of.txt

Where Is Machine.Config?

In your asp.net app use this

using System.Configuration;
Response.Write(ConfigurationManager.OpenMachineConfiguration().FilePath);

Javascript get the text value of a column from a particular row of an html table

document.getElementById("tblBlah").rows[i].columns[j].innerHTML;

Should be:

document.getElementById("tblBlah").rows[i].cells[j].innerHTML;

But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:

function alertInnerHTML(e)
{
    e = e || window.event;//IE
    alert(this.innerHTML);
}

var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
    for(var j=0;j<theTbl.rows[i].cells.length;j++)
    {
        theTbl.rows[i].cells[j].onclick = alertInnerHTML;
    }
}

That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML function, in which the this object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)

Anaconda Navigator won't launch (windows 10)

I was also facing same problem. Running below command from conda command prompt solved my problem

pip install pyqt5

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

What online brokers offer APIs?

I've been using parts of the marketcetera platform. They support all kinds of marketdata sources and brokers and you should easily be able to add more brokers and/or data providers. This is not a direct broker API of course, but that helps you avoid vendor lock-in so that might be a good thing. And of course all the tools they use are open source.

Undo a Git merge that hasn't been pushed yet

I was able to resolve this problem with a single command that doesn't involve looking up a commit id.

git reset --hard remotes/origin/HEAD

The accepted answer didn't work for me but this command achieved the results I was looking for.

Running vbscript from batch file

Well i am trying to open a .vbs within a batch file without having to click open but the answer to this question is ...

SET APPDATA=%CD%

start (your file here without the brackets with a .vbs if it is a vbd file)

Returning a C string from a function

You can create the array in the caller, which is the main function, and pass the array to the callee which is your myFunction(). Thus myFunction can fill the string into the array. However, you need to declare myFunction() as

char* myFunction(char * buf, int buf_len){
  strncpy(buf, "my string", buf_len);
  return buf;
}

And in main function, myFunction should be called in this way:

char array[51];
memset(array, 0, 51); /* All bytes are set to '\0' */
printf("%s", myFunction(array, 50)); /* The buf_len argument  is 50, not 51. This is to make sure the string in buf is always null-terminated (array[50] is always '\0') */

However, a pointer is still used.

Oracle query execution time

I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.

But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.

How do I join two lines in vi?

This should do it:

J

How to run a javascript function during a mouseover on a div

Here is how I show hover text using JavaScript tooltip:

<script language="JavaScript" type="text/javascript" src="javascript/wz_tooltip.js"></script>

<div class="curhand" onmouseover="this.T_WIDTH=125; return escape('Welcome')">Are you New Here?</div>

How to get UTC time in Python?

Try this code that uses datetime.utcnow():

from datetime import datetime
datetime.utcnow()

For your purposes when you need to calculate an amount of time spent between two dates all that you need is to substract end and start dates. The results of such substraction is a timedelta object.

From the python docs:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

And this means that by default you can get any of the fields mentioned in it's definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10*6) / 10*6 computed with true division enabled.

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

How can I clear the terminal in Visual Studio Code?

I am using Visual Studio Code 1.52.1 on windows 10 machine.'cls' or 'Clear' doesn't clear the terminal.

just write

exit

It will close the terminal and press

ctrl+shift+`

to open new terminal.

How do I get the scroll position of a document?

It uses HTML DOM Elements, but not jQuery selector. It can be used like:

var height = document.body.scrollHeight;

Generate random string/characters in JavaScript

Generate a secure random alphanumeric Base-62 string:

_x000D_
_x000D_
function generateUID(length)
{
    return window.btoa(Array.from(window.crypto.getRandomValues(new Uint8Array(length * 2))).map((b) => String.fromCharCode(b)).join("")).replace(/[+/]/g, "").substring(0, length);
}

console.log(generateUID(22)); // "yFg3Upv2cE9cKOXd7hHwWp"
console.log(generateUID(5)); // "YQGzP"
_x000D_
_x000D_
_x000D_

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

How to load local html file into UIWebView

Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.

How to serve .html files with Spring

I faced the same issue and tried various solutions to load the html page from Spring MVC, following solution worked for me

Step-1 in server's web.xml comment these two lines

<!--     <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>--> 
<!--     <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
 -->

Step-2 enter following code in application's web xml

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

Step-3 create a static controller class

@Controller 
public class FrontController {
     @RequestMapping("/landingPage") 
    public String getIndexPage() { 
    return "CompanyInfo"; 

    }

}

Step-4 in the Spring configuration file change the suffix to .htm .htm

Step-5 Rename page as .htm file and store it in WEB-INF and build/start the server

localhost:8080/.../landingPage

How do I list all tables in a schema in Oracle SQL?

You can query USER_TABLES

select TABLE_NAME from user_tables

PHP array: count or sizeof?

sizeof() is just an alias of count() as mentioned here

http://php.net/manual/en/function.sizeof.php

AttributeError: 'module' object has no attribute

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

Correct import:

from package.MyEnumClass import MyEnumClass

Hope that helps someone

Split an NSString to access one particular piece

Either of these 2:

NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];

Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.

The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Use:

overflow: hidden;
height: 100%;
position: fixed;
width: 100%;

Why is my CSS bundling not working with a bin deployed MVC4 app?

Another thing to consider is the references cannot have the same name. For example, if you have jQuery UI in the libraries directory, and bundle its JavaScript file like so:

bundles.Add(new ScriptBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.js"));

and then try to bundle its CSS files like so:

bundles.Add(new StyleBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.css"));
...

it will fail. They have to have unique names. So do something like ScriptBundle("~/libraries/js")... and ScriptBundle("~/libraries/css")... or whatever.

Xcopy Command excluding files and folders

It is same as above answers, but is simple in steps

c:\SRC\folder1

c:\SRC\folder2

c:\SRC\folder3

c:\SRC\folder4

to copy all above folders to c:\DST\ except folder1 and folder2.

Step1: create a file c:\list.txt with below content, one folder name per one line

folder1\

folder2\

Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt

cast a List to a Collection

Casting never needs a new:

Collection<T> collection = myList;

You don't even make the cast explicit, because Collection is a super-type of List, so it will work just like this.

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

What's the difference between align-content and align-items?

What I have learned from every answer and visiting the blog is

what is the cross axis and main axis

  • main axis is horizontal row and cross axis is vertical column - for flex-direction: row
  • main axis is vertical column and cross axis is horizontal row - for flex-direction: column

Now align-content and align-items

align-content is for the row, it works if the container has (more than one row) Properties of align-content

.container {
  align-content: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline + ... safe | unsafe;
}

align-items is for the items in row Properties of align-items

.container {
  align-items: stretch | flex-start | flex-end | center | baseline | first baseline | last baseline | start | end | self-start | self-end + ... safe | unsafe;
}

For more reference visit to flex

Add a properties file to IntelliJ's classpath

I had a similar problem with a log4j.xml file for a unit test, did all of the above. But figured out it was because I was only re-running a failed test....if I re-run the entire test class the correct file is picked up. This is under Intelli-j 9.0.4

How to Add a Dotted Underline Beneath HTML Text

You can use border bottom with dotted option.

border-bottom: 1px dotted #807f80;

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

How to debug PDO database queries?

Here's a function to see what the effective SQL will be, adpated from a comment by "Mark" at php.net:

function sql_debug($sql_string, array $params = null) {
    if (!empty($params)) {
        $indexed = $params == array_values($params);
        foreach($params as $k=>$v) {
            if (is_object($v)) {
                if ($v instanceof \DateTime) $v = $v->format('Y-m-d H:i:s');
                else continue;
            }
            elseif (is_string($v)) $v="'$v'";
            elseif ($v === null) $v='NULL';
            elseif (is_array($v)) $v = implode(',', $v);

            if ($indexed) {
                $sql_string = preg_replace('/\?/', $v, $sql_string, 1);
            }
            else {
                if ($k[0] != ':') $k = ':'.$k; //add leading colon if it was left out
                $sql_string = str_replace($k,$v,$sql_string);
            }
        }
    }
    return $sql_string;
}

Using a batch to copy from network drive to C: or D: drive

This might be due to a security check. This thread might help you.

There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...

How to set layout_gravity programmatically?

Modify the existing layout params and set layout params again

//Get the current layout params and update the Gravity
(iv.layoutParams as FrameLayout.LayoutParams).gravity = Gravity.START
//Set layout params again (this updates the view)
iv.layoutParams = layoutParams

Node.js: get path from the request

You can use this in app.js file .

var apiurl = express.Router();
apiurl.use(function(req, res, next) {
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});
app.use('/', apiurl);

How to get a path to the desktop for current user in C#?

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

php delete a single file in directory

The script you downloaded lists the content of a specified folder. You probably put the unlink - call in one of the while-loops that list the files.

EDIT - Now that you posted your code:

echo '<a href="'.unlink($FileLink).'"><img src="images/icons/delete.gif"></a></td>';

Doing this calls the unlink-function each time the line is written, deleting your file. You have to write a link to a script that contains a delete function and pass some parameter that tells your script what to delete.

Example:

<a href="/path/to/script.php?delete='. $FileLink .'">delete</a>

You should not pass the path to a file this script and just delete it though, because malevolent being might use it to just delete everything or do other evil things.

Hide Spinner in Input Number - Firefox 29

Faced the same issue post Firefox update to 29.0.1, this is also listed out here https://bugzilla.mozilla.org/show_bug.cgi?id=947728

Solutions: They(Mozilla guys) have fixed this by introducing support for "-moz-appearance" for <input type="number">. You just need to have a style associated with your input field with "-moz-appearance:textfield;".

I prefer the CSS way E.g.:-

.input-mini{
-moz-appearance:textfield;}

Or

You can do it inline as well:

<input type="number" style="-moz-appearance: textfield">

OpenMP set_num_threads() is not working

Besides calling omp_get_num_threads() outside of the parallel region in your case, calling omp_set_num_threads() still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads() is used to override the value of the environment variable OMP_NUM_THREADS and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS) or for any consequent parallel region (after a call to omp_set_num_threads()). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0) or by setting the environment variable OMP_DYNAMIC to false.

To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads():

omp_set_dynamic(0);     // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
    ... 4 threads used here ...
}

or with the num_threads OpenMP clause:

omp_set_dynamic(0);     // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
    ... 4 threads used here ...
}

How to increase the vertical split window size in Vim

CTRL-W >

and

CTRL-W <

to make the window wider or narrower.

Windows equivalent to UNIX pwd

In PowerShell pwd is an alias to Get-Location so you can simply run pwd in it like in bash

It can also be called from cmd like this powershell -Command pwd although cd or echo %cd% in cmd would work just fine

Working with $scope.$emit and $scope.$on

Scope(s) can be used to propagate, dispatch event to the scope children or parent.

$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.

example index.html:

<div ng-app="appExample" ng-controller="EventCtrl">
      Root(Parent) scope count: {{count}}
  <div>
      <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
      <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>

      Childrent scope count: {{count}} 
  </div>
</div>

example app.js:

angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
  $scope.count = 0;
  $scope.$on('MyEvent', function() {
    $scope.count++;
  });
}]);

Here u can test code: http://jsfiddle.net/zp6v0rut/41/

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

I was having some difficulty translating actual VB.NET to the Expression subset that SSRS uses. You definitely inspired me though and this is what I came up with.

StartDate  
=dateadd("d",0,dateserial(year(dateadd("d",-1,dateserial(year(Today),month(Today),1))),month(dateadd("d",-1,dateserial(year(Today),month(Today),1))),1))

End Date
=dateadd("d",0,dateserial(year(Today),month(Today),1))  

I know it's a bit recursive for the StartDate (first day of last month). Is there anything I'm missing here? These are strictly date fields (i.e. no time), but I think this should capture leap year, etc.

How did I do?

What's the difference between Thread start() and Runnable run()

Start() method call run override method of Thread extended class and Runnable implements interface.

But by calling run() it search for run method but if class implementing Runnable interface then it call run() override method of Runnable.

ex.:

`

public class Main1
{
A a=new A();
B b=new B();
a.run();//This call run() of Thread because run() of Thread only call when class 
        //implements with Runnable not when class extends Thread.
b.run();//This not run anything because no run method found in class B but it 
        //didn't show any error.

a.start();//this call run() of Thread
b.start();//this call run() of Thread
}

class A implements Runnable{
@Override
    public void run() {
            System.out.println("A ");
    }
}

class B extends Thread {

    @Override
    public void run() {
            System.out.println("B ");
    }
}

`