Programs & Examples On #Suspend

Applying an ellipsis to multiline text

This man have the best solution. Only css:

.multiline-ellipsis {
    display: block;
    display: -webkit-box;
    max-width: 400px;
    height: 109.2px;
    margin: 0 auto;
    font-size: 26px;
    line-height: 1.4;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

Kotlin unresolved reference in IntelliJ

Simplest Solution:

Tools->Kotlin->Configure Kotin in Project

Upvote if found Usefull.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Check to see if you have previously disabled caching in Chrome when the developer console is open - the setting is under the console, settings icon > General tab: Disable cache (while DevTools is open)

Vagrant error : Failed to mount folders in Linux guest

This is 2017. Just in case someone faces the same issue.

For bento/centos-6.7, I was getting same error. That was solved by adding plugin vagrant-vbguest (0.13.0). c:> vagrant plugin install vagrant-vbguest

Box url: http://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_centos-7.0_chef-provisionerless.box

This centos-7 version was giving me same error

Error:

==> build: Mounting shared folders...
    build: /vagrant => C:/projects/
Vagrant was unable to mount VirtualBox shared folders. This is usually
because the filesystem "vboxsf" is not available. This filesystem is
made available via the VirtualBox Guest Additions and kernel module.
Please verify that these guest additions are properly installed in the
guest. This is not a bug in Vagrant and is usually caused by a faulty
Vagrant box. For context, the command attempted was:

mount -t vboxsf -o uid=1000,gid=1000 vagrant /vagrant

The error output from the command was:

/sbin/mount.vboxsf: mounting failed with the error: No such device

My Configuration:

C:\projects>vagrant -v
Vagrant 1.9.1

C:\projects> vboxmanage -v
5.0.10r104061

C:\projects>vagrant plugin list
vagrant-cachier (1.2.1)
vagrant-hostmanager (1.8.5)
vagrant-hosts (2.8.0)
vagrant-omnibus (1.5.0)
vagrant-share (1.1.6, system)
vagrant-vbguest (0.13.0)
vagrant-vbox-snapshot (0.0.10)

Since I already have vagrant-vbguest plugin, it tries to update the VBoxGuestAdditions in centos-7 when it sees different version of VBGuestAdditions are installed in Host 5.0.10 and guest 4.3.20.

I even have checked that symbolic link exists.

[root@build VBoxGuestAdditions]# ls -lrt /usr/lib
lrwxrwxrwx.  1 root root   53 Jan 14 12:06 VBoxGuestAdditions -> /opt/VBoxGuestAdditions-5.0.10/lib/VBoxGuestAdditions
[root@build VBoxGuestAdditions]# mount -t vboxsf -o uid=1000,gid=1000 vagrant /vagrant
/sbin/mount.vboxsf: mounting failed with the error: No such device

This did not work as suggested by user3006381

vagrant ssh
sudo yum -y install kernel-devel
sudo yum -y update
exit
vagrant reload --provision

Solution for centos-7: as given by psychok7 worked

Diabled autoupdate. config.vbguest.auto_update = false Then vagrant destroy --force and vagrant up

Result:

javareport: Guest Additions Version: 4.3.20
javareport: VirtualBox Version: 5.0
==> javareport: Setting hostname...
==> javareport: Configuring and enabling network interfaces...
==> javareport: Mounting shared folders...
javareport: /vagrant => C:/projects

C:\project>

How to deal with SettingWithCopyWarning in Pandas

How to deal with SettingWithCopyWarning in Pandas?

This post is meant for readers who,

  1. Would like to understand what this warning means
  2. Would like to understand different ways of suppressing this warning
  3. Would like to understand how to improve their code and follow good practices to avoid this warning in the future.

Setup

np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (3, 5)), columns=list('ABCDE'))
df
   A  B  C  D  E
0  5  0  3  3  7
1  9  3  5  2  4
2  7  6  8  8  1

What is the SettingWithCopyWarning?

To know how to deal with this warning, it is important to understand what it means and why it is raised in the first place.

When filtering DataFrames, it is possible slice/index a frame to return either a view, or a copy, depending on the internal layout and various implementation details. A "view" is, as the term suggests, a view into the original data, so modifying the view may modify the original object. On the other hand, a "copy" is a replication of data from the original, and modifying the copy has no effect on the original.

As mentioned by other answers, the SettingWithCopyWarning was created to flag "chained assignment" operations. Consider df in the setup above. Suppose you would like to select all values in column "B" where values in column "A" is > 5. Pandas allows you to do this in different ways, some more correct than others. For example,

df[df.A > 5]['B']
 
1    3
2    6
Name: B, dtype: int64

And,

df.loc[df.A > 5, 'B']

1    3
2    6
Name: B, dtype: int64

These return the same result, so if you are only reading these values, it makes no difference. So, what is the issue? The problem with chained assignment, is that it is generally difficult to predict whether a view or a copy is returned, so this largely becomes an issue when you are attempting to assign values back. To build on the earlier example, consider how this code is executed by the interpreter:

df.loc[df.A > 5, 'B'] = 4
# becomes
df.__setitem__((df.A > 5, 'B'), 4)

With a single __setitem__ call to df. OTOH, consider this code:

df[df.A > 5]['B'] = 4
# becomes
df.__getitem__(df.A > 5).__setitem__('B", 4)

Now, depending on whether __getitem__ returned a view or a copy, the __setitem__ operation may not work.

In general, you should use loc for label-based assignment, and iloc for integer/positional based assignment, as the spec guarantees that they always operate on the original. Additionally, for setting a single cell, you should use at and iat.

More can be found in the documentation.

Note
All boolean indexing operations done with loc can also be done with iloc. The only difference is that iloc expects either integers/positions for index or a numpy array of boolean values, and integer/position indexes for the columns.

For example,

df.loc[df.A > 5, 'B'] = 4

Can be written nas

df.iloc[(df.A > 5).values, 1] = 4

And,

df.loc[1, 'A'] = 100

Can be written as

df.iloc[1, 0] = 100

And so on.


Just tell me how to suppress the warning!

Consider a simple operation on the "A" column of df. Selecting "A" and dividing by 2 will raise the warning, but the operation will work.

df2 = df[['A']]
df2['A'] /= 2
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/__main__.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

df2
     A
0  2.5
1  4.5
2  3.5

There are a couple ways of directly silencing this warning:

  1. (recommended) Use loc to slice subsets:

     df2 = df.loc[:, ['A']]
     df2['A'] /= 2     # Does not raise 
    
  2. Change pd.options.mode.chained_assignment
    Can be set to None, "warn", or "raise". "warn" is the default. None will suppress the warning entirely, and "raise" will throw a SettingWithCopyError, preventing the operation from going through.

     pd.options.mode.chained_assignment = None
     df2['A'] /= 2
    
  3. Make a deepcopy

     df2 = df[['A']].copy(deep=True)
     df2['A'] /= 2
    

@Peter Cotton in the comments, came up with a nice way of non-intrusively changing the mode (modified from this gist) using a context manager, to set the mode only as long as it is required, and the reset it back to the original state when finished.

class ChainedAssignent:
    def __init__(self, chained=None):
        acceptable = [None, 'warn', 'raise']
        assert chained in acceptable, "chained must be in " + str(acceptable)
        self.swcw = chained

    def __enter__(self):
        self.saved_swcw = pd.options.mode.chained_assignment
        pd.options.mode.chained_assignment = self.swcw
        return self

    def __exit__(self, *args):
        pd.options.mode.chained_assignment = self.saved_swcw

The usage is as follows:

# some code here
with ChainedAssignent():
    df2['A'] /= 2
# more code follows

Or, to raise the exception

with ChainedAssignent(chained='raise'):
    df2['A'] /= 2

SettingWithCopyError: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

The "XY Problem": What am I doing wrong?

A lot of the time, users attempt to look for ways of suppressing this exception without fully understanding why it was raised in the first place. This is a good example of an XY problem, where users attempt to solve a problem "Y" that is actually a symptom of a deeper rooted problem "X". Questions will be raised based on common problems that encounter this warning, and solutions will then be presented.

Question 1
I have a DataFrame

df
       A  B  C  D  E
    0  5  0  3  3  7
    1  9  3  5  2  4
    2  7  6  8  8  1

I want to assign values in col "A" > 5 to 1000. My expected output is

      A  B  C  D  E
0     5  0  3  3  7
1  1000  3  5  2  4
2  1000  6  8  8  1

Wrong way to do this:

df.A[df.A > 5] = 1000         # works, because df.A returns a view
df[df.A > 5]['A'] = 1000      # does not work
df.loc[df.A  5]['A'] = 1000   # does not work

Right way using loc:

df.loc[df.A > 5, 'A'] = 1000

Question 21
I am trying to set the value in cell (1, 'D') to 12345. My expected output is

   A  B  C      D  E
0  5  0  3      3  7
1  9  3  5  12345  4
2  7  6  8      8  1

I have tried different ways of accessing this cell, such as df['D'][1]. What is the best way to do this?

1. This question isn't specifically related to the warning, but it is good to understand how to do this particular operation correctly so as to avoid situations where the warning could potentially arise in future.

You can use any of the following methods to do this.

df.loc[1, 'D'] = 12345
df.iloc[1, 3] = 12345
df.at[1, 'D'] = 12345
df.iat[1, 3] = 12345

Question 3
I am trying to subset values based on some condition. I have a DataFrame

   A  B  C  D  E
1  9  3  5  2  4
2  7  6  8  8  1

I would like to assign values in "D" to 123 such that "C" == 5. I tried

df2.loc[df2.C == 5, 'D'] = 123

Which seems fine but I am still getting the SettingWithCopyWarning! How do I fix this?

This is actually probably because of code higher up in your pipeline. Did you create df2 from something larger, like

df2 = df[df.A > 5]

? In this case, boolean indexing will return a view, so df2 will reference the original. What you'd need to do is assign df2 to a copy:

df2 = df[df.A > 5].copy()
# Or,
# df2 = df.loc[df.A > 5, :]

Question 4
I'm trying to drop column "C" in-place from

   A  B  C  D  E
1  9  3  5  2  4
2  7  6  8  8  1

But using

df2.drop('C', axis=1, inplace=True)

Throws SettingWithCopyWarning. Why is this happening?

This is because df2 must have been created as a view from some other slicing operation, such as

df2 = df[df.A > 5]

The solution here is to either make a copy() of df, or use loc, as before.

Can not deserialize instance of java.lang.String out of START_OBJECT token

This way I solved my problem. Hope it helps others. In my case I created a class, a field, their getter & setter and then provide the object instead of string.

Use this

public static class EncryptedData {
    private String encryptedData;

    public String getEncryptedData() {
        return encryptedData;
    }

    public void setEncryptedData(String encryptedData) {
        this.encryptedData = encryptedData;
    }
}

@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
    try {
        Path path = Paths.get(PUBLIC_KEY);
        byte[] bytes = Files.readAllBytes(path);
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
        PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);

        Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
        cipher.init(Cipher.PRIVATE_KEY, privateKey);
        String decryptedData = new String(cipher.doFinal(encryptedData.getEncryptedData().getBytes()));
        String[] dataArray = decryptedData.split("|");


        Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
        updateIp.invoke(null, dataArray[0], dataArray[1]);

    } catch (Exception e) {
        LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
    }

    return null;

Instead of this

@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
    try {
        Path path = Paths.get(PUBLIC_KEY);
        byte[] bytes = Files.readAllBytes(path);
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
        PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);

        Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
        cipher.init(Cipher.PRIVATE_KEY, privateKey);
        String decryptedData = new String(cipher.doFinal(encryptedData.getBytes()));
        String[] dataArray = decryptedData.split("|");


        Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
        updateIp.invoke(null, dataArray[0], dataArray[1]);

    } catch (Exception e) {
        LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
    }

    return null;
}

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

Overflow Scroll css is not working in the div

The solution is to add height:100%; to all the parent elements of your .wrapper-div as well. So:

html{
    height: 100%;
}

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

#container{
    width:1000px;
    margin:0 auto;
    height:100%;
}

Multiple IF AND statements excel

Consider that you have multiple "tests", e.g.,

  1. If E2 = 'in play' and F2 = 'closed', output 3
  2. If E2 = 'in play' and F2 = 'suspended', output 2
  3. Etc.

What you really need to do is put successive tests in the False argument. You're presently trying to separate each test by a comma, and that won't work.

Your first three tests can all be joined in one expression like:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))))

Remembering that each successive test needs to be the nested FALSE argument of the preceding test, you can do this:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-Play",F2="Null"),-1,IF(AND(E2="completed",F2="closed"),2,IF(AND(E2="suspended",F2="Null"),3,-2))))

Eclipse will not start and I haven't changed anything

If you deleted all data in .metadata directory. There is a quick way to import all your projects again. Try this:

File --> Import --> General: Select Existing projects into workspace --> Select root directory: Browse to old workspace folder (the SAME with the current workspace folder is OK) --> Finish.

get enum name from enum value

If you want something more efficient in runtime condition, you can have a map that contains every possible choice of the enum by their value. But it'll be juste slower at initialisation of the JVM.

import java.util.HashMap;
import java.util.Map;

/**
 * Example of enum with a getter that need a value in parameter, and that return the Choice/Instance 
 * of the enum which has the same value.
 * The value of each choice can be random.
 */
public enum MyEnum {
    /** a random choice */
    Choice1(4),
    /** a nother one */
    Choice2(2),
    /** another one again */
    Choice3(9);
    /** a map that contains every choices of the enum ordered by their value. */
    private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
    static {
        // populating the map
        for (MyEnum myEnum : values()) {
            MY_MAP.put(myEnum.getValue(), myEnum);
        }
    }
    /** the value of the choice */
    private int value;

    /**
     * constructor
     * @param value the value
     */
    private MyEnum(int value) {
        this.value = value;
    }

    /**
     * getter of the value
     * @return int
     */
    public int getValue() {
        return value;
    }

    /**
     * Return one of the choice of the enum by its value.
     * May return null if there is no choice for this value.
     * @param value value
     * @return MyEnum
     */
    public static MyEnum getByValue(int value) {
        return MY_MAP.get(value);
    }

    /**
     * {@inheritDoc}
     * @see java.lang.Enum#toString()
     */
    public String toString() {
        return name() + "=" + value;
    }

    /**
     * Exemple of how to use this class.
     * @param args args
     */
    public static void main(String[] args) {
        MyEnum enum1 = MyEnum.Choice1;
        System.out.println("enum1==>" + String.valueOf(enum1));
        MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
        System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
        MyEnum enum3Unknown = MyEnum.getByValue(4);
        System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
    }
}

Unable to open debugger port in IntelliJ

Your Service/ Application might already be running. In Search enter Services and you will get list of services. Stop yours and then try again.

How to suspend/resume a process in Windows?

PsSuspend command line utility from SysInternals suite. It suspends / resumes a process by its id.

What causes signal 'SIGILL'?

It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.

Disable XML validation in Eclipse

You have two options:

  1. Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

  2. Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

Right-click on the project and select Validate to make the errors disappear.

How to initialize an array of objects in Java

thePlayers[i] = new Player(i); I just deleted the i inside Player(i); and it worked.

so the code line should be:

thePlayers[i] = new Player9();

How would I run an async Task<T> method synchronously?

Try following code it works for me:

public async void TaskSearchOnTaskList (SearchModel searchModel)
{
    try
    {
        List<EventsTasksModel> taskSearchList = await Task.Run(
            () => MakeasyncSearchRequest(searchModel),
            cancelTaskSearchToken.Token);

        if (cancelTaskSearchToken.IsCancellationRequested
                || string.IsNullOrEmpty(rid_agendaview_search_eventsbox.Text))
        {
            return;
        }

        if (taskSearchList == null || taskSearchList[0].result == Constants.ZERO)
        {
            RunOnUiThread(() => {
                textViewNoMembers.Visibility = ViewStates.Visible;                  
                taskListView.Visibility = ViewStates.Gone;
            });

            taskSearchRecureList = null;

            return;
        }
        else
        {
            taskSearchRecureList = TaskFooterServiceLayer
                                       .GetRecurringEvent(taskSearchList);

            this.SetOnAdapter(taskSearchRecureList);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("ActivityTaskFooter -> TaskSearchOnTaskList:" + ex.Message);
    }
}

The difference between fork(), vfork(), exec() and clone()

  • execve() replaces the current executable image with another one loaded from an executable file.
  • fork() creates a child process.
  • vfork() is a historical optimized version of fork(), meant to be used when execve() is called directly after fork(). It turned out to work well in non-MMU systems (where fork() cannot work in an efficient manner) and when fork()ing processes with a huge memory footprint to run some small program (think Java's Runtime.exec()). POSIX has standardized the posix_spawn() to replace these latter two more modern uses of vfork().
  • posix_spawn() does the equivalent of a fork()/execve(), and also allows some fd juggling in between. It's supposed to replace fork()/execve(), mainly for non-MMU platforms.
  • pthread_create() creates a new thread.
  • clone() is a Linux-specific call, which can be used to implement anything from fork() to pthread_create(). It gives a lot of control. Inspired on rfork().
  • rfork() is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.

Automatic confirmation of deletion in powershell

You just need to add a /A behind the line.

Example:

get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname} /a

Remote debugging Tomcat with Eclipse

Can you check if this works?

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

catalina.sh jpda start

Nested jQuery.each() - continue/break

The problem here is that while you can return false from within the .each callback, the .each function itself returns the jQuery object. So you have to return a false at both levels to stop the iteration of the loop. Also since there is not way to know if the inner .each found a match or not, we will have to use a shared variable using a closure that gets updated.

Each inner iteration of words refers to the same notFound variable, so we just need to update it when a match is found, and then return it. The outer closure already has a reference to it, so it can break out when needed.

$(sentences).each(function() {
    var s = this;
    var notFound = true;

    $(words).each(function() {
        return (notFound = (s.indexOf(this) == -1));
    });

    return notFound;
});

You can try your example here.

Why must wait() always be in synchronized block

This basically has to do with the hardware architecture (i.e. RAM and caches).

If you don't use synchronized together with wait() or notify(), another thread could enter the same block instead of waiting for the monitor to enter it. Moreover, when e.g. accessing an array without a synchronized block, another thread may not see the changement to it...actually another thread will not see any changements to it when it already has a copy of the array in the x-level cache (a.k.a. 1st/2nd/3rd-level caches) of the thread handling CPU core.

But synchronized blocks are only one side of the medal: If you actually access an object within a synchronized context from a non-synchronized context, the object still won't be synchronized even within a synchronized block, because it holds an own copy of the object in its cache. I wrote about this issues here: https://stackoverflow.com/a/21462631 and When a lock holds a non-final object, can the object's reference still be changed by another thread?

Furthermore, I'm convinced that the x-level caches are responsible for most non-reproducible runtime errors. That's because the developers usually don't learn the low-level stuff, like how CPU's work or how the memory hierarchy affects the running of applications: http://en.wikipedia.org/wiki/Memory_hierarchy

It remains a riddle why programming classes don't start with memory hierarchy and CPU architecture first. "Hello world" won't help here. ;)

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

How to detect page zoom level in all modern browsers?

You can use the Visual Viewport API:

window.visualViewport.scale;

It is standard and works both on desktop and mobile: browser support.

Max parallel http connections in a browser?

Firefox stores that number in this setting (you find it in about:config): network.http.max-connections-per-server

For the max connections, Firefox stores that in this setting: network.http.max-connections

Remote debugging a Java application

This is how you should setup Eclipse Debugger for remote debugging:

Eclipse Settings:

1.Click the Run Button
2.Select the Debug Configurations
3.Select the “Remote Java Application”
4.New Configuration

  • Name : GatewayPortalProject
  • Project : GatewayPortal-portlet
  • Connection Type: Socket Attach
  • Connection Properties: i) localhost ii) 8787

For JBoss:

1.Change the /path/toJboss/jboss-eap-6.1/bin/standalone.conf in your vm as follows: Uncomment the following line by removing the #:

JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n"

For Tomcat :

In catalina.bat file :

Step 1:

CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

Step 2:

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

Step 3: Run Tomcat from command prompt like below:

catalina.sh jpda start

Then you need to set breakpoints in the Java classes you desire to debug.

Ignore 'Security Warning' running script from command line

This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .

Summary Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...).

How do I suspend painting for a control and its children?

I usually use a little modified version of ngLink's answer.

public class MyControl : Control
{
    private int suspendCounter = 0;

    private void SuspendDrawing()
    {
        if(suspendCounter == 0) 
            SendMessage(this.Handle, WM_SETREDRAW, false, 0);
        suspendCounter++;
    }

    private void ResumeDrawing()
    {
        suspendCounter--; 
        if(suspendCounter == 0) 
        {
            SendMessage(this.Handle, WM_SETREDRAW, true, 0);
            this.Refresh();
        }
    }
}

This allows suspend/resume calls to be nested. You must make sure to match each SuspendDrawing with a ResumeDrawing. Hence, it wouldn't probably be a good idea to make them public.

Highlight a word with jQuery

$(function () {
    $("#txtSearch").keyup(function (event) {
        var txt = $("#txtSearch").val()
        if (txt.length > 3) {
            $("span.hilightable").each(function (i, v) {
                v.innerHTML = v.innerText.replace(txt, "<hilight>" + txt + "</hilight>");
            });

        }
    });
});

Jfiddle here

Lock, mutex, semaphore... what's the difference?

A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes.

A mutex is the same as a lock but it can be system wide (shared by multiple processes).

A semaphore does the same as a mutex but allows x number of threads to enter, this can be used for example to limit the number of cpu, io or ram intensive tasks running at the same time.

For a more detailed post about the differences between mutex and semaphore read here.

You also have read/write locks that allows either unlimited number of readers or 1 writer at any given time.

Alter user defined type in SQL Server

I ran into this issue with custom types in stored procedures, and solved it with the script below. I didn't fully understand the scripts above, and I follow the rule of "if you don't know what it does, don't do it".

In a nutshell, I rename the old type, and create a new one with the original type name. Then, I tell SQL Server to refresh its details about each stored procedure using the custom type. You have to do this, as everything is still "compiled" with reference to the old type, even with the rename. In this case, the type I needed to change was "PrizeType". I hope this helps. I'm looking for feedback, too, so I learn :)

Note that you may need to go to Programmability > Types > [Appropriate User Type] and delete the object. I found that DROP TYPE doesn't appear to always drop the type even after using the statement.

/* Rename the UDDT you want to replace to another name */ 
exec sp_rename 'PrizeType', 'PrizeTypeOld', 'USERDATATYPE';

/* Add the updated UDDT with the new definition */ 
CREATE TYPE [dbo].[PrizeType] AS TABLE(
    [Type] [nvarchar](50) NOT NULL,
    [Description] [nvarchar](max) NOT NULL,
    [ImageUrl] [varchar](max) NULL
);

/* We need to force stored procedures to refresh with the new type... let's take care of that. */
/* Get a cursor over a list of all the stored procedures that may use this and refresh them */
declare sprocs cursor
  local static read_only forward_only
for
    select specific_name from information_schema.routines where routine_type = 'PROCEDURE'

declare @sprocName varchar(max)

open sprocs
fetch next from sprocs into @sprocName
while @@fetch_status = 0
begin
    print 'Updating ' + @sprocName;
    exec sp_refreshsqlmodule @sprocName
    fetch next from sprocs into @sprocName
end
close sprocs
deallocate sprocs

/* Drop the old type, now that everything's been re-assigned; must do this last */
drop type PrizeTypeOld;

Print array elements on separate lines in Bash?

Another useful variant is pipe to tr:

echo "${my_array[@]}" | tr ' ' '\n'

This looks simple and compact

Twitter Bootstrap inline input with dropdown

Search for the "datalist" tag.

<input list="texto_pronto" name="input_normal">
<datalist id="texto_pronto">
    <option value="texto A">
    <option value="texto B">
</datalist>

Animated GIF in IE stopping

Very, very late to answer this one, but I've just discovered that using a background-image that is encoded as a base64 URI in the CSS, rather than held as a separate image, continues to animate in IE8.

nil detection in Go

You can also check like struct_var == (struct{}). This does not allow you to compare to nil but it does check if it is initialized or not. Be careful while using this method. If your struct can have zero values for all of its fields you won't have great time.

package main

import "fmt"

type A struct {
    Name string
}

func main() {
    a := A{"Hello"}
    var b A

    if a == (A{}) {
        fmt.Println("A is empty") // Does not print
    } 

    if b == (A{}) {
        fmt.Println("B is empty") // Prints
    } 
}

http://play.golang.org/p/RXcE06chxE

How to increase number of threads in tomcat thread pool?

Sounds like you should stay with the defaults ;-)

Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.

See here how to configure...

Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html

Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html

Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html

Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

How to grep recursively, but only in files with certain extensions?

Should write "-exec grep " for each "-o -name "

find . -name '*.h' -exec grep -Hn "CP_Image" {} \; -o -name '*.cpp' -exec grep -Hn "CP_Image" {} \;

Or group them by ( )

find . \( -name '*.h' -o -name '*.cpp' \) -exec grep -Hn "CP_Image" {} \;

option '-Hn' show the file name and line.

How do I compute derivative using Numpy?

NumPy does not provide general functionality to compute derivatives. It can handles the simple special case of polynomials however:

>>> p = numpy.poly1d([1, 0, 1])
>>> print p
   2
1 x + 1
>>> q = p.deriv()
>>> print q
2 x
>>> q(5)
10

If you want to compute the derivative numerically, you can get away with using central difference quotients for the vast majority of applications. For the derivative in a single point, the formula would be something like

x = 5.0
eps = numpy.sqrt(numpy.finfo(float).eps) * (1.0 + x)
print (p(x + eps) - p(x - eps)) / (2.0 * eps * x)

if you have an array x of abscissae with a corresponding array y of function values, you can comput approximations of derivatives with

numpy.diff(y) / numpy.diff(x)

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

How to grep for contents after pattern?

Or use regex assertions: grep -oP '(?<=potato: ).*' file.txt

XPath with multiple conditions

Try:
//category[@name='Sport' and ./author/text()='James Small']

How to make PyCharm always show line numbers

Version 2.6 and above:
PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> General -> Appearance -> Show line numbers checkbox

enter image description here

Version 2.5 and below:
Settings -> Editor -> General -> Appearance -> Show line numbers checkbox

What is meant by the term "hook" in programming?

Simple said:

A hook is a means of executing custom code (function) either before, after, or instead of existing code. For example, a function may be written to "hook" into the login process in order to execute a Captcha function before continuing on to the normal login process.

Unicode character in PHP string

PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}

Or with an anonymous function expression instead of create_function:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
        return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
    }, $str);
}

Its usage:

$str = unicodeString("\u1000");

How to disable submit button once it has been clicked?

tested on IE11, FF53, GC58 :

onclick="var e=this;setTimeout(function(){e.disabled=true;},0);return true;"

Select from one table matching criteria in another?

You should make tags their own table with a linking table.

items:
id    object
1     lamp  
2     table   
3     stool  
4     bench 

tags:
id     tag
1      furniture
2      chair

items_tags:
item_id tag_id
1       1
2       1
3       1
4       1
3       2
4       2

How do I disable and re-enable a button in with javascript?

<script>
function checkusers()
{
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;
}
</script>

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

Set value for particular cell in pandas DataFrame using index

I too was searching for this topic and I put together a way to iterate through a DataFrame and update it with lookup values from a second DataFrame. Here is my code.

src_df = pd.read_sql_query(src_sql,src_connection)
for index1, row1 in src_df.iterrows():
    for index, row in vertical_df.iterrows():
        src_df.set_value(index=index1,col=u'etl_load_key',value=etl_load_key)
        if (row1[u'src_id'] == row['SRC_ID']) is True:
            src_df.set_value(index=index1,col=u'vertical',value=row['VERTICAL'])

What is the ellipsis (...) for in this method signature?

It means that the method accepts a variable number of arguments ("varargs") of type JID. Within the method, recipientJids is presented.

This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.

It also enables idioms such as sprintf from C; see String.format(), for example.

Removing Data From ElasticSearch

If you ever need to delete all the indexes, this may come in handy:

curl -X DELETE 'http://localhost:9200/_all'

Powershell:

Invoke-WebRequest -method DELETE http://localhost:9200/_all

proper way to logout from a session in PHP

Personally, I do the following:

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();

That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy).

Chart won't update in Excel (2007)

I struggled with this problem, too. Finally solved it by recalculating the sheet that has the chart data AFTER the custom function has recalculated. So, in Sheet 1, I have a cell that contains

=ComputeScore()

In the VBA module, the function is defined as Volatile, to ensure that ComputeScore() runs after any updates to the spreadsheet.

Function ComputeScore() As Double
    Application.Volatile True
    . . . do some stuff to get a total . . .
    ComputeScore = theTotal
End Function

Then, in the VBA of Sheet 1, this:

Private Sub Worksheet_Calculate()
    'Recalculate the charts data page to force the charts to update.
    'Otherwise, they don't update until the next change to a sheet, and so
    'chart data is always one update behind the user's data changes.
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlManual
    Sheets("Charts Data").Calculate
    Application.Calculation = xlAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

So, the sheet named Charts Data, which references the custom function cell of Sheet 1, will do a recalculation AFTER the ComputeScore() function has updated the cell of Sheet 1, since Worksheet_Calculate() fires after the ComputeScore() recalc. This additional round of calculation of the chart data causes the chart to update now, rather than later or not at all. The setting of EnableEvents and xlManual keeps infinite recalc loops and other event problems from occurring.

What are the differences between C, C# and C++ in terms of real-world applications?

C is the bare-bones, simple, clean language that makes you do everything yourself. It doesn't hold your hand, it doesn't stop you from shooting yourself in the foot. But it has everything you need to do what you want.

C++ is C with classes added, and then a whole bunch of other things, and then some more stuff. It doesn't hold your hand, but it'll let you hold your own hand, with add-on GC, or RAII and smart-pointers. If there's something you want to accomplish, chances are there's a way to abuse the template system to give you a relatively easy syntax for it. (moreso with C++0x). This complexity also gives you the power to accidentally create a dozen instances of yourself and shoot them all in the foot.

C# is Microsoft's stab at improving on C++ and Java. Tons of syntactical features, but no where near the complexity of C++. It runs in a full managed environment, so memory management is done for you. It does let you "get dirty" and use unsafe code if you need to, but it's not the default, and you have to do some work to shoot yourself.

How to convert a string or integer to binary in Ruby?

If you are looking for a Ruby class/method I used this, and I have also included the tests:

class Binary
  def self.binary_to_decimal(binary)
    binary_array = binary.to_s.chars.map(&:to_i)
    total = 0

    binary_array.each_with_index do |n, i|
      total += 2 ** (binary_array.length-i-1) * n
    end
    total
   end
end

class BinaryTest < Test::Unit::TestCase
  def test_1
   test1 = Binary.binary_to_decimal(0001)
   assert_equal 1, test1
  end

 def test_8
    test8 = Binary.binary_to_decimal(1000)
    assert_equal 8, test8
 end

 def test_15
    test15 = Binary.binary_to_decimal(1111)
    assert_equal 15, test15
 end

 def test_12341
    test12341 = Binary.binary_to_decimal(11000000110101)
    assert_equal 12341, test12341
 end
end

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

How to make my font bold using css?

You'd use font-weight: bold.

Do you want to make the entire document bold? Or just parts of it?

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

Using malloc for allocation of multi-dimensional arrays with different row lengths

The other approach would be to allocate one contiguous chunk of memory comprising header block for pointers to rows as well as body block to store actual data in rows. Then just mark up memory by assigning addresses of memory in body to the pointers in header on per-row basis. It would look like follows:

int** 2dAlloc(int rows, int* columns) {    
    int header = rows * sizeof(int*);

    int body = 0;
    for(int i=0; i<rows; body+=columnSizes[i++]) {  
    }
    body*=sizeof(int);

    int** rowptr = (int**)malloc(header + body);

    int* buf  = (int*)(rowptr + rows);
    rowptr[0] = buf;
    int k;
    for(k = 1; k < rows; ++k) {
        rowptr[k] = rowptr[k-1] + columns[k-1];
    }
    return rowptr;
}

int main() {
    // specifying column amount on per-row basis
    int columns[] = {1,2,3};
    int rows = sizeof(columns)/sizeof(int);
    int** matrix = 2dAlloc(rows, &columns);

    // using allocated array
    for(int i = 0; i<rows; ++i) {
        for(int j = 0; j<columns[i]; ++j) {
            cout<<matrix[i][j]<<", ";
        }   
            cout<<endl;
    }

    // now it is time to get rid of allocated 
    // memory in only one call to "free"
    free matrix;
}

The advantage of this approach is elegant freeing of memory and ability to use array-like notation to access elements of the resulting 2D array.

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

For my case commenting out mirrorlist and uncomenting entries with baseurl din't work. I noticed the problem was with the https iniside the .repofedora files. I solved it by going in /etc/yum.repository.d and replacing all https with http in different .repo files. That worked!!

Maven – Always download sources and javadocs

In Netbeans, you can instruct Maven to check javadoc on every project open :

Tools | Options | Java icon | Maven tab | Dependencies category | Check Javadoc drop down set to Every Project Open.

Close and reopen Netbeans and you will see Maven download javadocs in the status bar.

CSS styling in Django forms

Taken from my answer to: How to markup form fields with <div class='field_type'> in Django

class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented

-- EDIT 2 ---
Added a newer way to specify widget and attrs for a ModelForm.

How to get integer values from a string in Python?

Here's your one-liner, without using any regular expressions, which can get expensive at times:

>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))

returns:

'123453120'

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1

Resource from src/main/resources not found after building with maven

You can replace the src/main/resources/ directly by classpath:

So for your example you will replace this line:

new BufferedReader(new FileReader(new File("src/main/resources/config.txt")));

By this line:

new BufferedReader(new FileReader(new File("classpath:config.txt")));

How to catch curl errors in PHP

Since you are interested in catching network related errors and HTTP errors, the following provides a better approach:

function curl_error_test($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $responseBody = curl_exec($ch);
    /*
     * if curl_exec failed then
     * $responseBody is false
     * curl_errno() returns non-zero number
     * curl_error() returns non-empty string
     * which one to use is up too you
     */
    if ($responseBody === false) {
        return "CURL Error: " . curl_error($ch);
    }

    $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    /*
     * 4xx status codes are client errors
     * 5xx status codes are server errors
     */
    if ($responseCode >= 400) {
        return "HTTP Error: " . $responseCode;
    }

    return "No CURL or HTTP Error";
}

Tests:

curl_error_test("http://expamle.com");          // CURL Error: Could not resolve host: expamle.com
curl_error_test("http://example.com/whatever"); // HTTP Error: 404
curl_error_test("http://example.com");          // No CURL or HTTP Error

Code for Greatest Common Divisor in Python

I had to do something like this for a homework assignment using while loops. Not the most efficient way, but if you don't want to use a function this works:

num1 = 20
num1_list = []
num2 = 40
num2_list = []
x = 1
y = 1
while x <= num1:
    if num1 % x == 0:
        num1_list.append(x)
    x += 1
while y <= num2:
    if num2 % y == 0:
        num2_list.append(y)
    y += 1
xy = list(set(num1_list).intersection(num2_list))
print(xy[-1])

How to check if directory exists in %PATH%?

This will look for an exact but case-insensitive match, so mind any trailing backslashes etc.:

for %P in ("%path:;=";"%") do @if /i %P=="PATH_TO_CHECK" echo %P exists in PATH

or, in a batch file (e.g. checkpath.bat) which takes an argument:

@for %%P in ("%path:;=";"%") do @if /i %%P=="%~1" echo %%P exists in PATH

In the latter form, one could call e.g. checkpath "%ProgramFiles%" to see if the specified path already exists in PATH.

Please note that this implementation assumes no semicolons or quotes are present inside a single path item.

Split string on the first white space occurrence

In ES6 you can also

let [first, ...second] = str.split(" ")
second = second.join(" ")

SeekBar and media player in android

To create a 'connection' between SeekBar and MediaPlayer you need first to get your current recording max duration and set it to your seek bar.

mSeekBar.setMax(mFileDuration/1000); // where mFileDuration is mMediaPlayer.getDuration();

After you initialise your MediaPlayer and for example press play button, you should create handler and post runnable so you can update your SeekBar (in the UI thread itself) with the current position of your MediaPlayer like this :

private Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {

    @Override
    public void run() {
        if(mMediaPlayer != null){
            int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
            mSeekBar.setProgress(mCurrentPosition);
        }
        mHandler.postDelayed(this, 1000);
    }
});

and update that value every second.

If you need to update the MediaPlayer's position while user drag your SeekBar you should add OnSeekBarChangeListener to your SeekBar and do it there :

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {                
                if(mMediaPlayer != null && fromUser){
                    mMediaPlayer.seekTo(progress * 1000);
                }
            }
    });

And that should do the trick! : )

EDIT: One thing which I've noticed in your code, don't do :

public MainActivity() {
    mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
    mFileName += "/audiorecordtest.3gp";
}

make all initialisations in your onCreate(); , do not create constructors of your Activity.

Mockito: Inject real objects into private @Autowired fields

I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection

EDIT:

@InjectionMap
 private Map<String, Object> injectionMap = new HashMap<>();

 @BeforeEach
 public void beforeEach() throws Exception {
  injectionMap.put("securityEnabled", Boolean.TRUE);
 }

 @AfterEach
 public void afterEach() throws Exception {
  injectionMap.clear();
 }

Using {% url ??? %} in django templates

The url template tag will pass the parameter as a string and not as a function reference to reverse(). The simplest way to get this working is adding a name to the view:

url(r'^/logout/' , logout_view, name='logout_view')

Python 3 sort a dict by its values

You can sort by values in reverse order (largest to smallest) using a dictionary comprehension:

{k: d[k] for k in sorted(d, key=d.get, reverse=True)}
# {'b': 4, 'a': 3, 'c': 2, 'd': 1}

If you want to sort by values in ascending order (smallest to largest)

{k: d[k] for k in sorted(d, key=d.get)}
# {'d': 1, 'c': 2, 'a': 3, 'b': 4}

If you want to sort by the keys in ascending order

{k: d[k] for k in sorted(d)}
# {'a': 3, 'b': 4, 'c': 2, 'd': 1}

This works on CPython 3.6+ and any implementation of Python 3.7+ because dictionaries keep insertion order.

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

There is probably another table with a foreign key referencing the primary key you are trying to change.

To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section.

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

.any() and .all() are great for the extreme cases, but not when you're looking for a specific number of null values. Here's an extremely simple way to do what I believe you're asking. It's pretty verbose, but functional.

import pandas as pd
import numpy as np

# Some test data frame
df = pd.DataFrame({'num_legs':          [2, 4,      np.nan, 0, np.nan],
                   'num_wings':         [2, 0,      np.nan, 0, 9],
                   'num_specimen_seen': [10, np.nan, 1,     8, np.nan]})

# Helper : Gets NaNs for some row
def row_nan_sums(df):
    sums = []
    for row in df.values:
        sum = 0
        for el in row:
            if el != el: # np.nan is never equal to itself. This is "hacky", but complete.
                sum+=1
        sums.append(sum)
    return sums

# Returns a list of indices for rows with k+ NaNs
def query_k_plus_sums(df, k):
    sums = row_nan_sums(df)
    indices = []
    i = 0
    for sum in sums:
        if (sum >= k):
            indices.append(i)
        i += 1
    return indices

# test
print(df)
print(query_k_plus_sums(df, 2))

Output

   num_legs  num_wings  num_specimen_seen
0       2.0        2.0               10.0
1       4.0        0.0                NaN
2       NaN        NaN                1.0
3       0.0        0.0                8.0
4       NaN        9.0                NaN
[2, 4]

Then, if you're like me and want to clear those rows out, you just write this:

# drop the rows from the data frame
df.drop(query_k_plus_sums(df, 2),inplace=True)
# Reshuffle up data (if you don't do this, the indices won't reset)
df = df.sample(frac=1).reset_index(drop=True)
# print data frame
print(df)

Output:

   num_legs  num_wings  num_specimen_seen
0       4.0        0.0                NaN
1       0.0        0.0                8.0
2       2.0        2.0               10.0

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Font awesome use SVG icons. So, you can resize it for your requirment.

just use CSS class for that,

    .large-icon{
       font-size:10em;
       //or
      font-size:200%;
      //or
      font-size:50px;
    }

How to print number with commas as thousands separators?

I'm using python 2.5 so I don't have access to the built-in formatting.

I looked at the Django code intcomma (intcomma_recurs in code below) and realized it's inefficient, because it's recursive and also compiling the regex on every run is not a good thing either. This is not necessary an 'issue' as django isn't really THAT focused on this kind of low-level performance. Also, I was expecting a factor of 10 difference in performance, but it's only 3 times slower.

Out of curiosity I implemented a few versions of intcomma to see what the performance advantages are when using regex. My test data concludes a slight advantage for this task, but surprisingly not much at all.

I also was pleased to see what I suspected: using the reverse xrange approach is unnecessary in the no-regex case, but it does make the code look slightly better at the cost of ~10% performance.

Also, I assume what you're passing in is a string and looks somewhat like a number. Results undetermined otherwise.

from __future__ import with_statement
from contextlib import contextmanager
import re,time

re_first_num = re.compile(r"\d")
def intcomma_noregex(value):
    end_offset, start_digit, period = len(value),re_first_num.search(value).start(),value.rfind('.')
    if period == -1:
        period=end_offset
    segments,_from_index,leftover = [],0,(period-start_digit) % 3
    for _index in xrange(start_digit+3 if not leftover else start_digit+leftover,period,3):
        segments.append(value[_from_index:_index])
        _from_index=_index
    if not segments:
        return value
    segments.append(value[_from_index:])
    return ','.join(segments)

def intcomma_noregex_reversed(value):
    end_offset, start_digit, period = len(value),re_first_num.search(value).start(),value.rfind('.')
    if period == -1:
        period=end_offset
    _from_index,segments = end_offset,[]
    for _index in xrange(period-3,start_digit,-3):
        segments.append(value[_index:_from_index])
        _from_index=_index
    if not segments:
        return value
    segments.append(value[:_from_index])
    return ','.join(reversed(segments))

re_3digits = re.compile(r'(?<=\d)\d{3}(?!\d)')
def intcomma(value):
    segments,last_endoffset=[],len(value)
    while last_endoffset > 3:
        digit_group = re_3digits.search(value,0,last_endoffset)
        if not digit_group:
            break
        segments.append(value[digit_group.start():last_endoffset])
        last_endoffset=digit_group.start()
    if not segments:
        return value
    if last_endoffset:
        segments.append(value[:last_endoffset])
    return ','.join(reversed(segments))

def intcomma_recurs(value):
    """
    Converts an integer to a string containing commas every three digits.
    For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
    """
    new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', str(value))
    if value == new:
        return new
    else:
        return intcomma(new)

@contextmanager
def timed(save_time_func):
    begin=time.time()
    try:
        yield
    finally:
        save_time_func(time.time()-begin)

def testset_xsimple(func):
    func('5')

def testset_simple(func):
    func('567')

def testset_onecomma(func):
    func('567890')

def testset_complex(func):
    func('-1234567.024')

def testset_average(func):
    func('-1234567.024')
    func('567')
    func('5674')

if __name__ == '__main__':
    print 'Test results:'
    for test_data in ('5','567','1234','1234.56','-253892.045'):
        for func in (intcomma,intcomma_noregex,intcomma_noregex_reversed,intcomma_recurs):
            print func.__name__,test_data,func(test_data)
    times=[]
    def overhead(x):
        pass
    for test_run in xrange(1,4):
        for func in (intcomma,intcomma_noregex,intcomma_noregex_reversed,intcomma_recurs,overhead):
            for testset in (testset_xsimple,testset_simple,testset_onecomma,testset_complex,testset_average):
                for x in xrange(1000): # prime the test
                    testset(func)
                with timed(lambda x:times.append(((test_run,func,testset),x))):
                    for x in xrange(50000):
                        testset(func)
    for (test_run,func,testset),_delta in times:
        print test_run,func.__name__,testset.__name__,_delta

And here are the test results:

intcomma 5 5
intcomma_noregex 5 5
intcomma_noregex_reversed 5 5
intcomma_recurs 5 5
intcomma 567 567
intcomma_noregex 567 567
intcomma_noregex_reversed 567 567
intcomma_recurs 567 567
intcomma 1234 1,234
intcomma_noregex 1234 1,234
intcomma_noregex_reversed 1234 1,234
intcomma_recurs 1234 1,234
intcomma 1234.56 1,234.56
intcomma_noregex 1234.56 1,234.56
intcomma_noregex_reversed 1234.56 1,234.56
intcomma_recurs 1234.56 1,234.56
intcomma -253892.045 -253,892.045
intcomma_noregex -253892.045 -253,892.045
intcomma_noregex_reversed -253892.045 -253,892.045
intcomma_recurs -253892.045 -253,892.045
1 intcomma testset_xsimple 0.0410001277924
1 intcomma testset_simple 0.0369999408722
1 intcomma testset_onecomma 0.213000059128
1 intcomma testset_complex 0.296000003815
1 intcomma testset_average 0.503000020981
1 intcomma_noregex testset_xsimple 0.134000062943
1 intcomma_noregex testset_simple 0.134999990463
1 intcomma_noregex testset_onecomma 0.190999984741
1 intcomma_noregex testset_complex 0.209000110626
1 intcomma_noregex testset_average 0.513000011444
1 intcomma_noregex_reversed testset_xsimple 0.124000072479
1 intcomma_noregex_reversed testset_simple 0.12700009346
1 intcomma_noregex_reversed testset_onecomma 0.230000019073
1 intcomma_noregex_reversed testset_complex 0.236999988556
1 intcomma_noregex_reversed testset_average 0.56299996376
1 intcomma_recurs testset_xsimple 0.348000049591
1 intcomma_recurs testset_simple 0.34600019455
1 intcomma_recurs testset_onecomma 0.625
1 intcomma_recurs testset_complex 0.773999929428
1 intcomma_recurs testset_average 1.6890001297
1 overhead testset_xsimple 0.0179998874664
1 overhead testset_simple 0.0190000534058
1 overhead testset_onecomma 0.0190000534058
1 overhead testset_complex 0.0190000534058
1 overhead testset_average 0.0309998989105
2 intcomma testset_xsimple 0.0360000133514
2 intcomma testset_simple 0.0369999408722
2 intcomma testset_onecomma 0.207999944687
2 intcomma testset_complex 0.302000045776
2 intcomma testset_average 0.523000001907
2 intcomma_noregex testset_xsimple 0.139999866486
2 intcomma_noregex testset_simple 0.141000032425
2 intcomma_noregex testset_onecomma 0.203999996185
2 intcomma_noregex testset_complex 0.200999975204
2 intcomma_noregex testset_average 0.523000001907
2 intcomma_noregex_reversed testset_xsimple 0.130000114441
2 intcomma_noregex_reversed testset_simple 0.129999876022
2 intcomma_noregex_reversed testset_onecomma 0.236000061035
2 intcomma_noregex_reversed testset_complex 0.241999864578
2 intcomma_noregex_reversed testset_average 0.582999944687
2 intcomma_recurs testset_xsimple 0.351000070572
2 intcomma_recurs testset_simple 0.352999925613
2 intcomma_recurs testset_onecomma 0.648999929428
2 intcomma_recurs testset_complex 0.808000087738
2 intcomma_recurs testset_average 1.81900000572
2 overhead testset_xsimple 0.0189998149872
2 overhead testset_simple 0.0189998149872
2 overhead testset_onecomma 0.0190000534058
2 overhead testset_complex 0.0179998874664
2 overhead testset_average 0.0299999713898
3 intcomma testset_xsimple 0.0360000133514
3 intcomma testset_simple 0.0360000133514
3 intcomma testset_onecomma 0.210000038147
3 intcomma testset_complex 0.305999994278
3 intcomma testset_average 0.493000030518
3 intcomma_noregex testset_xsimple 0.131999969482
3 intcomma_noregex testset_simple 0.136000156403
3 intcomma_noregex testset_onecomma 0.192999839783
3 intcomma_noregex testset_complex 0.202000141144
3 intcomma_noregex testset_average 0.509999990463
3 intcomma_noregex_reversed testset_xsimple 0.125999927521
3 intcomma_noregex_reversed testset_simple 0.126999855042
3 intcomma_noregex_reversed testset_onecomma 0.235999822617
3 intcomma_noregex_reversed testset_complex 0.243000030518
3 intcomma_noregex_reversed testset_average 0.56200003624
3 intcomma_recurs testset_xsimple 0.337000131607
3 intcomma_recurs testset_simple 0.342000007629
3 intcomma_recurs testset_onecomma 0.609999895096
3 intcomma_recurs testset_complex 0.75
3 intcomma_recurs testset_average 1.68300008774
3 overhead testset_xsimple 0.0189998149872
3 overhead testset_simple 0.018000125885
3 overhead testset_onecomma 0.018000125885
3 overhead testset_complex 0.0179998874664
3 overhead testset_average 0.0299999713898

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I had the same problem in Flask.

When I added:

__init__.py

to tests folder, problem disappeared :)

Probably application couldn't recognize folder tests as module

C#: Assign same value to multiple variables in single statement

Your example would be:

int num1 = 1;
int num2 = 1;

num1 = num2 = 5;

Encoding an image file with base64

The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.

encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))

Get operating system info

If you want to get all those information, you might want to read this:
http://php.net/manual/en/function.get-browser.php

You can run the sample code and you'll see how it works:

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

The above example will output something similar to:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

How do I convert strings in a Pandas data frame to a 'date' data type?

It may be the case that dates need to be converted to a different frequency. In this case, I would suggest setting an index by dates.

#set an index by dates
df.set_index(['time'], drop=True, inplace=True)

After this, you can more easily convert to the type of date format you will need most. Below, I sequentially convert to a number of date formats, ultimately ending up with a set of daily dates at the beginning of the month.

#Convert to daily dates
df.index = pd.DatetimeIndex(data=df.index)

#Convert to monthly dates
df.index = df.index.to_period(freq='M')

#Convert to strings
df.index = df.index.strftime('%Y-%m')

#Convert to daily dates
df.index = pd.DatetimeIndex(data=df.index)

For brevity, I don't show that I run the following code after each line above:

print(df.index)
print(df.index.dtype)
print(type(df.index))

This gives me the following output:

Index(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='object', name='time')
object
<class 'pandas.core.indexes.base.Index'>

DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='datetime64[ns]', name='time', freq=None)
datetime64[ns]
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>

PeriodIndex(['2013-01', '2013-01', '2013-01'], dtype='period[M]', name='time', freq='M')
period[M]
<class 'pandas.core.indexes.period.PeriodIndex'>

Index(['2013-01', '2013-01', '2013-01'], dtype='object')
object
<class 'pandas.core.indexes.base.Index'>

DatetimeIndex(['2013-01-01', '2013-01-01', '2013-01-01'], dtype='datetime64[ns]', freq=None)
datetime64[ns]
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>

How to send a PUT/DELETE request in jQuery?

Seems to be possible with JQuery's ajax function by specifying

type: "put" or type: "delete"

and is not not supported by all browsers, but most of them.

Check out this question for more info on compatibility:

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

DataGrid get selected rows' column values

I believe the reason there's no straightforward property to access the selected row of a WPF DataGrid is because a DataGrid's selection mode can be set to either the row-level or the cell-level. Therefore, the selection-related properties and events are all written against cell-level selection - you'll always have selected cells regardless of the grid's selection mode, but you aren't guaranteed to have a selected row.

I don't know precisely what you're trying to achieve by handling the CellEditEnding event, but to get the values of all selected cells when you select a row, take a look at handling the SelectedCellsChanged event, instead. Especially note the remarks in that article:

You can handle the SelectedCellsChanged event to be notified when the collection of selected cells is changed. If the selection includes full rows, the Selector.SelectionChanged event is also raised.

You can retrieve the AddedCells and RemovedCells from the SelectedCellsChangedEventArgs in the event handler.

Hope that helps put you on the right track. :)

How to count down in for loop?

The range function in python has the syntax:

range(start, end, step)

It has the same syntax as python lists where the start is inclusive but the end is exclusive.

So if you want to count from 5 to 1, you would use range(5,0,-1) and if you wanted to count from last to posn you would use range(last, posn - 1, -1).

How to implement the Softmax function in Python

They're both correct, but yours is preferred from the point of view of numerical stability.

You start with

e ^ (x - max(x)) / sum(e^(x - max(x))

By using the fact that a^(b - c) = (a^b)/(a^c) we have

= e ^ x / (e ^ max(x) * sum(e ^ x / e ^ max(x)))

= e ^ x / sum(e ^ x)

Which is what the other answer says. You could replace max(x) with any variable and it would cancel out.

replace \n and \r\n with <br /> in java

It works for me.

public class Program
{
    public static void main(String[] args) {
        String str = "This is a string.\nThis is a long string.";
        str = str.replaceAll("(\r\n|\n)", "<br />");
        System.out.println(str);
    }
}

Result:

This is a string.<br />This is a long string.

Your problem is somewhere else.

m2eclipse not finding maven dependencies, artifacts not found

I had this issue for dependencies that were created in other projects. Downloaded thirdparty dependencies showed up fine in the build path, but not a library that I had created.

SOLUTION: In the project that is not building correctly, right-click on the project and choose Properties, and then Maven. Uncheck the box labeled "Resolve dependencies from Workspace projects", hit Apply, and then OK. Right-click again on your project and do a Maven->Update Snapshots (or Update Dependencies) and your errors should go away when your project rebuilds (automatically if you have auto-build enabled).

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

Round number to nearest integer

Some thing like this should also work

import numpy as np    

def proper_round(a):
    '''
    given any real number 'a' returns an integer closest to 'a'
    '''
    a_ceil = np.ceil(a)
    a_floor = np.floor(a)
    if np.abs(a_ceil - a) < np.abs(a_floor - a):
        return int(a_ceil)
    else:
        return int(a_floor)

Logging request/response messages when using HttpClient

See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

json_decode to array

Please try this

<?php
$json_string = 'http://www.domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>

User Get-ADUser to list all properties and export to .csv

@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.

The below examples are based on a domain in the range of 20,000 account objects.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds           : 16
Milliseconds      : 208

measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds           : 3
Milliseconds      : 496

In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).

Note that if I include the where clause per your suggestion to prune to the actually desired results, it's even more expensive.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds           : 17
Milliseconds      : 876

Indexed attributes seem to have similar performance (I tried just returning displayName).

Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).

measure-command {$userlist | get-aduser -Properties *}
...
Seconds           : 12
Milliseconds      : 75

I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01

When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).

Set line spacing

Try the line-height property.

For example, 12px font-size and 4px distant from the bottom and upper lines:

line-height: 20px; /* 4px +12px + 4px */

Or with em units

line-height: 1.7em; /* 1em = 12px in this case. 20/12 == 1.666666  */

Ripple effect on Android Lollipop CardView

I managed to get the ripple effect on the cardview by :

<android.support.v7.widget.CardView 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:clickable="true" 
    android:foreground="@drawable/custom_bg"/>

and for the custom_bg that you can see in above code, you have to define a xml file for both lollipop(in drawable-v21 package) and pre-lollipop(in drawable package) devices. for custom_bg in drawable-v21 package the code is:

<ripple 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight">
<item
    android:id="@android:id/mask"
    android:drawable="@android:color/white"/>
</ripple>

for custom_bg in the drawable package, code is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true">
    <shape>
        <solid android:color="@color/colorHighlight"></solid>
    </shape>
</item>
<item>
    <shape>
        <solid android:color="@color/navigation_drawer_background"></solid>
    </shape>
</item>
</selector>

so on pre-lollipop devices you will have a solid click effect and on lollipop devices you will have a ripple effect on the cardview.

OpenCV NoneType object has no attribute shape

I have also met this issue and wasted a lot of time debugging it.

First, make sure that the path you provide is valid, i.e., there is an image in that path.

Next, you should be aware that Opencv doesn't support image paths which contain unicode characters (see ref). If your image path contains Unicode characters, you can use the following code to read the image:

import numpy as np
import cv2

# img is in BGR format if the underlying image is a color image
img = cv2.imdecode(np.fromfile(im_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)

Array Length in Java

First of all, length is a property, so it would be arr.length instead of arr.length().

And it will return 10, the declared size. The elements that you do not declare explicitely are initialized with 0.

convert a JavaScript string variable to decimal/money

This works:

var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Here's a pure HTML+CSS solution.

HTML:

<div class="image-radio">
  <input type="radio" value="true" checked="checked" name="ice_cream" id="ice_cream_vanilla">
  <label for="ice_cream_vanilla">Vanilla</label>
  <input type="radio" value="true" name="ice_cream" id="ice_cream_chocolate">
  <label for="ice_cream_chocolate">Chocolate</label>
</div>

SCSS:

  // use an image instead of the native radio widget
.image-radio {   
  input[type=radio] {
    display: none;
  }
  input[type=radio] + label {
    background: asset-url('icons/choice-unchecked.svg') no-repeat left;
    padding-left: 2rem;
  }
  input[type=radio]:checked + label {
    background: asset-url('icons/choice-checked.svg') no-repeat left;
  }
}

iPhone 6 and 6 Plus Media Queries

This works for me for the iphone 6

/*iPhone 6 Portrait*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait) { 

}

/*iPhone 6 landscape*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : landscape) { 

}

/*iPhone 6+ Portrait*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : portrait) { 

}

/*iPhone 6+ landscape*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : landscape) { 

}

/*iPhone 6 and iPhone 6+ portrait and landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px){ 
}

/*iPhone 6 and iPhone 6+ portrait*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : portrait){ 

}

/*iPhone 6 and iPhone 6+ landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : landscape){ 

}

installing vmware tools: location of GCC binary?

Found the answer. What I did was was first

sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y

and tried it but it didn't work so I continued and did

sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`

after doing these two steps and trying again, it worked.

Create ArrayList from array

the lambda expression that generates a list of type ArrayList<Element>
(1) without an unchecked cast
(2) without creating a second list (with eg. asList())

ArrayList<Element> list = Stream.of( array ).collect( Collectors.toCollection( ArrayList::new ) );

Multiple HttpPost method in Web API controller

I think the question has already been answered. I was also looking for something a webApi controller that has same signatured mehtods but different names. I was trying to implement the Calculator as WebApi. Calculator has 4 methods with the same signature but different names.

public class CalculatorController : ApiController
{
    [HttpGet]
    [ActionName("Add")]
    public string Add(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Add = {0}", num1 + num2);
    }

    [HttpGet]
    [ActionName("Sub")]
    public string Sub(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Subtract result = {0}", num1 - num2);
    }

    [HttpGet]
    [ActionName("Mul")]
    public string Mul(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Multiplication result = {0}", num1 * num2);
    }

    [HttpGet]
    [ActionName("Div")]
    public string Div(int num1 = 1, int num2 = 1, int timeDelay = 1)
    {
        Thread.Sleep(1000 * timeDelay);
        return string.Format("Division result = {0}", num1 / num2);
    }
}

and in the WebApiConfig file you already have

 config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional });

Just set the authentication / authorisation on IIS and you are done!

Hope this helps!

PHP: Return all dates between two dates in an array

Here's a way of doing this using Carbon https://github.com/briannesbitt/Carbon:

public function buildDateRangeArray($first, $last)
{
    while ($first <= $last) {
        $dates[] = $first->toDateString();

        $first->addDay();
    }

    return $dates;
}

This, of course, can be tweaked to not use Carbon. The $first and $last parameters passed to the function are Carbon instances.

Java, looping through result set

The problem with your code is :

     String  show[]= {rs4.getString(1)};
     String actuate[]={rs4.getString(2)};

This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.

Here is one more way to solve this :

    StringBuilder sids = new StringBuilder ();
    StringBuilder lids = new StringBuilder ();

    while (rs4.next()) {
        sids.append(rs4.getString(1)).append(" ");
        lids.append(rs4.getString(2)).append(" ");
    }

    String show[] = sids.toString().split(" "); 
    String actuate[] = lids.toString().split(" ");

These arrays will have all the required element.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

How to normalize a histogram in MATLAB?

There is an excellent three part guide for Histogram Adjustments in MATLAB (broken original link, archive.org link), the first part is on Histogram Stretching.

IsNumeric function in c#

Try following code snippet.

double myVal = 0;
String myVar = "Not Numeric Type";

if (Double.TryParse(myVar , out myNum)) {
  // it is a number
} else {
  // it is not a number
}

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

Python [Errno 98] Address already in use

If you use a TCPServer, UDPServer or their subclasses in the SocketServer module, you can set this class variable (before instanciating a server):

SocketServer.TCPServer.allow_reuse_address = True

(via SocketServer.ThreadingTCPServer - Cannot bind to address after program restart )

This causes the init (constructor) to:

 if self.allow_reuse_address:
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

How to make a local variable (inside a function) global

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.

How does tuple comparison work in Python?

The python 2.5 documentation explains it well.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

Unfortunately that page seems to have disappeared in the documentation for more recent versions.

When to use AtomicReference in Java?

Here's a very simple use case and has nothing to do with thread safety.

To share an object between lambda invocations, the AtomicReference is an option:

public void doSomethingUsingLambdas() {

    AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();

    soSomethingThatTakesALambda(() -> {
        yourObjectRef.set(youObject);
    });

    soSomethingElseThatTakesALambda(() -> {
        YourObject yourObject = yourObjectRef.get();
    });
}

I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference is an option.

In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.

JSON character encoding

If the suggested solutions above didn't solve your issue (as for me), this could also help:

My problem was that I was returning a json string in my response using Springs @ResponseBody. If you're doing this as well this might help.

Add the following bean to your dispatcher servlet.

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </list>
    </property>
</bean>

(Found here: http://forum.spring.io/forum/spring-projects/web/74209-responsebody-and-utf-8)

Does Internet Explorer 8 support HTML 5?

IE8 beta 2 supports two APIs from HTML5: cross-document messaging and non-SQL storage.

IE8 beta 2 doesn’t implement the HTML5 parsing algorithm or the new elements (no <canvas> or <video> support).

There are also bug fixes that align IE8 better with HTML5.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

A quick answer, that doesn't require you to edit any configuration files (and works on other operating systems as well as Windows), is to just find the directory that you are allowed to save to using:

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name    | Value                 |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set (0.06 sec)

And then make sure you use that directory in your SELECT statement's INTO OUTFILE clause:

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Original answer

I've had the same problem since upgrading from MySQL 5.6.25 to 5.6.26.

In my case (on Windows), looking at the MySQL56 Windows service shows me that the options/settings file that is being used when the service starts is C:\ProgramData\MySQL\MySQL Server 5.6\my.ini

On linux the two most common locations are /etc/my.cnf or /etc/mysql/my.cnf.

MySQL56 Service

Opening this file I can see that the secure-file-priv option has been added under the [mysqld] group in this new version of MySQL Server with a default value:

secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.6/Uploads"

You could comment this (if you're in a non-production environment), or experiment with changing the setting (recently I had to set secure-file-priv = "" in order to disable the default). Don't forget to restart the service after making changes.

Alternatively, you could try saving your output into the permitted folder (the location may vary depending on your installation):

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

It's more common to have comma seperate values using FIELDS TERMINATED BY ','. See below for an example (also showing a Linux path):

SELECT *
FROM table
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    ESCAPED BY ''
    LINES TERMINATED BY '\n';

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

The FULLY WORKING SOLUTION for both Android or React-native users facing this issue just add this android:usesCleartextTraffic="true" in AndroidManifest.xml file like this:

android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
    android:name="org.apache.http.legacy"
    android:required="false" />

in between <application>.. </application> tag like this:

<application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:ignore="GoogleAppIndexingWarning">
        <uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"/>
 </application>

How to set focus on an input field after rendering?

I have same problem but I have some animation too, so my colleague suggest to use window.requestAnimationFrame

this is ref attribute of my element:

ref={(input) => {input && window.requestAnimationFrame(()=>{input.focus()})}}

How to execute powershell commands from a batch file?

Type in cmd.exe Powershell -Help and see the examples.

Selenium using Python - Geckodriver executable needs to be in PATH

I see the discussions still talk about the old way of setting up geckodriver by downloading the binary and configuring the path manually.

This can be done automatically using webdriver-manager

pip install webdriver-manager

Now the above code in the question will work simply with the below change,

from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

How to set environment variables in Jenkins?

Normally you can configure Environment variables in Global properties in Configure System.

However for dynamic variables with shell substitution, you may want to create a script file in Jenkins HOME dir and execute it during the build. The SSH access is required. For example.

  1. Log-in as Jenkins: sudo su - jenkins or sudo su - jenkins -s /bin/bash
  2. Create a shell script, e.g.:

    echo 'export VM_NAME="$JOB_NAME"' > ~/load_env.sh
    echo "export AOEU=$(echo aoeu)" >> ~/load_env.sh
    chmod 750 ~/load_env.sh
    
  3. In Jenkins Build (Execute shell), invoke the script and its variables before anything else, e.g.

    source ~/load_env.sh
    

Efficient way to remove keys with empty strings from a dict

I read all replies in this thread and some referred also to this thread: Remove empty dicts in nested dictionary with recursive function

I originally used solution here and it worked great:

Attempt 1: Too Hot (not performant or future-proof):

def scrub_dict(d):
    if type(d) is dict:
        return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
    else:
        return d

But some performance and compatibility concerns were raised in Python 2.7 world:

  1. use isinstance instead of type
  2. unroll the list comp into for loop for efficiency
  3. use python3 safe items instead of iteritems

Attempt 2: Too Cold (Lacks Memoization):

def scrub_dict(d):
    new_dict = {}
    for k, v in d.items():
        if isinstance(v,dict):
            v = scrub_dict(v)
        if not v in (u'', None, {}):
            new_dict[k] = v
    return new_dict

DOH! This is not recursive and not at all memoizant.

Attempt 3: Just Right (so far):

def scrub_dict(d):
    new_dict = {}
    for k, v in d.items():
        if isinstance(v,dict):
            v = scrub_dict(v)
        if not v in (u'', None, {}):
            new_dict[k] = v
    return new_dict

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active> with <Active>true</Active>, like so:

cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -

If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.

What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">
    <xsl:for-each select="XML">
        <xsl:for-each select="Active">
            <xsl:value-of select=" replace(current(), 'True','true')"/>
        </xsl:for-each>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Implementing INotifyPropertyChanged - does a better way exist?

I suggest to use ReactiveProperty. This is the shortest method except Fody.

public class Data : INotifyPropertyChanged
{
    // boiler-plate
    ...
    // props
    private string name;
    public string Name
    {
        get { return name; }
        set { SetField(ref name, value, "Name"); }
    }
}

instead

public class Data
{
    // Don't need boiler-plate and INotifyPropertyChanged

    // props
    public ReactiveProperty<string> Name { get; } = new ReactiveProperty<string>();
}

(DOCS)

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

It is very likely that the pickled file is empty.

It is surprisingly easy to overwrite a pickle file if you're copying and pasting code.

For example the following writes a pickle file:

pickle.dump(df,open('df.p','wb'))

And if you copied this code to reopen it, but forgot to change 'wb' to 'rb' then you would overwrite the file:

df=pickle.load(open('df.p','wb'))

The correct syntax is

df=pickle.load(open('df.p','rb'))

Apache won't follow symlinks (403 Forbidden)

In addition to changing the permissions as the other answers have indicated, I had to restart apache for it to take effect:

sudo service apache2 restart

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

C error: undefined reference to function, but it IS defined

I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create, not having point.c will cause the compilation to fail.

I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:

gcc point.c testpoint.c

As others have pointed out, you also need to remove one of your main functions, since you can only have one.

How to set initial value and auto increment in MySQL?

You could also set it in the create table statement.

`CREATE TABLE(...) AUTO_INCREMENT=1000`

Splitting String and put it on int array

Let's consider that you have input as "1,2,3,4".

That means the length of the input is 7. So now you write the size = 7/2 = 3.5. But as size is an int, it will be rounded off to 3. In short, you are losing 1 value.

If you rewrite the code as below it should work:

String input;
int length, count, size;
Scanner keyboard = new Scanner(System.in);
input = keyboard.next();
length = input.length();

String strarray[] = input.split(",");
int intarray[] = new int[strarray.length];

for (count = 0; count < intarray.length ; count++) {
    intarray[count] = Integer.parseInt(strarray[count]);
}

for (int s : intarray) {
    System.out.println(s);
}

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

When already given posts answer the question, I made a small change by adding the column name on which the max() function is applied for better code readability.

df.groupby('A', as_index=False)['B'].max()

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

Python: SyntaxError: keyword can't be an expression

It's python source parser failure on sum.up=False named argument as sum.up is not valid argument name (you can't use dots -- only alphanumerics and underscores in argument names).

What is the JavaScript version of sleep()?

An old question from 2009. Now in 2015 a new solution is possible with generators defined in ECMAscript 2015 aka ES6. It was approved in June, but it was implemented in Firefox and Chrome before. Now a sleep function can be made non-busy, non-blocking and nested inside loops and sub-functions without freezing the browser. Only pure JavaScript is needed, no libraries or frameworks.

The program below shows how sleep() and runSleepyTask() can be made. The sleep() function is only a yield statement. It is so simple that it is actually easier to write the yield statement directly in stead of calling sleep(), but then there would be no sleep-word :-) The yield returns a time value to the next() method inside wakeup() and waits. The actual "sleeping" is done in wakeup() using the good old setTimeout(). At callback the the next() method triggers the yield statement to continue, and the "magic" of yield is that all the local variables and the whole call-stack around it is still intact.

Functions that use sleep() or yield must be defined as generators. Easy done by adding an asterix to the keyword function*. To execute a generator is a bit trickier. When invoked with the keyword new the generator returns an object that has the next() method, but the body of the generator is not executed (the keyword new is optional and makes no difference). The next() method triggers execution of the generator body until it encounters a yield. The wrapper function runSleepyTask() starts up the ping-pong: next() waits for a yield, and yield waits a next().

Another way to invoke a generator is with keyword yield*, here it works like a simple function call, but it also includes the ability to yield back to next().

This is all demonstrated by the example drawTree(). It draws a tree with leaves on a rotating 3D scene. A tree is drawn as a trunk with 3 parts at the top in different directions. Each part is then drawn as another but smaller tree by calling drawTree() recursively after a short sleep. A very small tree is drawn as only a leaf.

Each leaf has its own life in a separate task started with runSleepyTask(). It is born, grows, sits, fades, falls and dies in growLeaf(). The speed is controlled with sleep(). This demonstrates how easy multitasking can be done.

_x000D_
_x000D_
function* sleep(milliseconds) {yield milliseconds};_x000D_
_x000D_
function runSleepyTask(task) {_x000D_
    (function wakeup() {_x000D_
        var result = task.next();_x000D_
        if (!result.done) setTimeout(wakeup, result.value);_x000D_
    })()_x000D_
}_x000D_
//////////////// written by Ole Middelboe  /////////////////////////////_x000D_
_x000D_
pen3D =setup3D();_x000D_
var taskObject = new drawTree(pen3D.center, 5);_x000D_
runSleepyTask(taskObject);_x000D_
_x000D_
function* drawTree(root3D, size) {_x000D_
    if (size < 2) runSleepyTask(new growLeaf(root3D))_x000D_
    else {_x000D_
        pen3D.drawTrunk(root3D, size);_x000D_
        for (var p of [1, 3, 5]) {_x000D_
            var part3D = new pen3D.Thing;_x000D_
            root3D.add(part3D);_x000D_
            part3D.move(size).turn(p).tilt(1-p/20);_x000D_
            yield* sleep(50);_x000D_
            yield* drawTree(part3D, (0.7+p/40)*size);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
function* growLeaf(stem3D) {_x000D_
    var leaf3D = pen3D.drawLeaf(stem3D);_x000D_
    for (var s=0;s++<15;) {yield* sleep(100); leaf3D.scale.multiplyScalar(1.1)}_x000D_
    yield* sleep( 1000 + 9000*Math.random() );_x000D_
    for (var c=0;c++<30;) {yield* sleep(200); leaf3D.skin.color.setRGB(c/30, 1-c/40, 0)}_x000D_
    for (var m=0;m++<90;) {yield* sleep( 50); leaf3D.turn(0.4).tilt(0.3).move(2)}_x000D_
    leaf3D.visible = false;_x000D_
}_x000D_
///////////////////////////////////////////////////////////////////////_x000D_
_x000D_
function setup3D() {_x000D_
    var scene, camera, renderer, diretionalLight, pen3D;_x000D_
_x000D_
    scene = new THREE.Scene();_x000D_
    camera = new THREE.PerspectiveCamera(75, _x000D_
        window.innerWidth / window.innerHeight, 0.1, 1000);_x000D_
    camera.position.set(0, 15, 20);_x000D_
    renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });_x000D_
    renderer.setSize(window.innerWidth, window.innerHeight);_x000D_
    document.body.appendChild(renderer.domElement);_x000D_
    _x000D_
    directionalLight = new THREE.DirectionalLight(0xffffaa, 0.7);_x000D_
    directionalLight.position.set(-1, 2, 1);_x000D_
    scene.add(directionalLight);_x000D_
    scene.add(new THREE.AmbientLight(0x9999ff));_x000D_
      _x000D_
    (function render() {_x000D_
        requestAnimationFrame(render);_x000D_
        // renderer.setSize( window.innerWidth, window.innerHeight );_x000D_
        scene.rotateY(10/60/60);_x000D_
        renderer.render(scene, camera);_x000D_
    })();_x000D_
    _x000D_
    window.addEventListener(_x000D_
        'resize',_x000D_
        function(){_x000D_
            renderer.setSize( window.innerWidth, window.innerHeight );_x000D_
            camera.aspect = window.innerWidth / window.innerHeight;_x000D_
            camera.updateProjectionMatrix();_x000D_
       }, _x000D_
       false_x000D_
    );_x000D_
    _x000D_
    pen3D = {_x000D_
        drawTrunk: function(root, size) {_x000D_
            // root.skin = skin(0.5, 0.3, 0.2);_x000D_
            root.add(new THREE.Mesh(new THREE.CylinderGeometry(size/12, size/10, size, 16), _x000D_
                root.skin).translateY(size/2));_x000D_
            root.add(new THREE.Mesh(new THREE.SphereGeometry(size/12, 16), _x000D_
                root.skin).translateY(size));_x000D_
            return root;_x000D_
        },_x000D_
        _x000D_
        drawLeaf: function(stem) {_x000D_
            stem.skin.color.setRGB(0, 1, 0);_x000D_
            stem.add(new THREE.Mesh(new THREE.CylinderGeometry(0, 0.02, 0.6), _x000D_
                stem.skin) .rotateX(0.3).translateY(0.3));_x000D_
            stem.add(new THREE.Mesh(new THREE.CircleGeometry(0.2), _x000D_
                stem.skin) .rotateX(0.3).translateY(0.4));_x000D_
            return stem;_x000D_
        },_x000D_
        _x000D_
        Thing: function() {_x000D_
            THREE.Object3D.call(this);_x000D_
            this.skin = new THREE.MeshLambertMaterial({_x000D_
                color: new THREE.Color(0.5, 0.3, 0.2),_x000D_
                vertexColors: THREE.FaceColors,_x000D_
                side: THREE.DoubleSide_x000D_
            })_x000D_
        }_x000D_
    };_x000D_
_x000D_
    pen3D.Thing.prototype = Object.create(THREE.Object3D.prototype);_x000D_
    pen3D.Thing.prototype.tilt = pen3D.Thing.prototype.rotateX;_x000D_
    pen3D.Thing.prototype.turn = pen3D.Thing.prototype.rotateY;_x000D_
    pen3D.Thing.prototype.move = pen3D.Thing.prototype.translateY;_x000D_
    _x000D_
    pen3D.center = new pen3D.Thing;_x000D_
    scene.add(pen3D.center);_x000D_
    _x000D_
    return pen3D;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js"></script>
_x000D_
_x000D_
_x000D_

The 3D stuff is hidden inside setup3D() and is only included to make it less boring than console.log(). Angels are measured in radians by the way.

Tested to work in Firefox and Chrome. Not implemented in Internet Explore and iOS (iPads). Try to run it yourself.

After another pass of the answers I found, that Gabriel Ratener made a similar answer a year ago: https://stackoverflow.com/a/24401317/5032384

How to get the selected date value while using Bootstrap Datepicker?

this works with me for inline datepicker (and the other)

$('#startdate').data('datepicker').date

Is there a CSS parent selector?

This is the most discussed aspect of the Selectors Level 4 specification. With this, a selector will be able to style an element according to its child by using an exclamation mark after the given selector (!).

For example:

body! a:hover{
   background: red;
}

will set a red background-color if the user hovers over any anchor.

But we have to wait for browsers' implementation :(

How to get Python requests to trust a self signed SSL certificate?

Case where multiple certificates are needed was solved as follows: Concatenate the multiple root pem files, myCert-A-Root.pem and myCert-B-Root.pem, to a file. Then set the requests REQUESTS_CA_BUNDLE var to that file in my ./.bash_profile.

$ cp myCert-A-Root.pem ca_roots.pem
$ cat myCert-B-Root.pem >> ca_roots.pem
$ echo "export REQUESTS_CA_BUNDLE=~/PATH_TO/CA_CHAIN/ca_roots.pem" >> ~/.bash_profile ; source ~/.bash_profile

HTML radio buttons allowing multiple selections

They all need to have the same name attribute.

The radio buttons are grouped by the name attribute. Here's an example:

<fieldset>
    <legend>Please select one of the following</legend>
    <input type="radio" name="action" id="track" value="track" /><label for="track">Track Submission</label><br />
    <input type="radio" name="action" id="event" value="event"  /><label for="event">Events and Artist booking</label><br />
    <input type="radio" name="action" id="message" value="message" /><label for="message">Message us</label><br />
</fieldset>

Random shuffling of an array

Look at the Collections class, specifically shuffle(...).

Expand a random range from 1–5 to 1–7

rand5() => [1-5]

rand5()%2 => [0-2]

rand5() + rand5()%2 => [1-7]

rand7() {
     return rand5()+rand5()%2;
}

Fit Image in ImageButton in Android

You can make your ImageButton widget as I did. In my case, I needed a widget with a fixed icon size. Let's start from custom attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ImageButtonFixedIconSize">
        <attr name="imageButton_icon" format="reference" />
        <attr name="imageButton_iconWidth" format="dimension" />
        <attr name="imageButton_iconHeight" format="dimension" />
    </declare-styleable>
</resources>

Widget class is quite simple (the key point is padding calculations in onLayout method):

class ImageButtonFixedIconSize
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.imageButtonStyle
) : ImageButton(context, attrs, defStyleAttr) {

    private lateinit var icon: Drawable

    @Px
    private var iconWidth: Int = 0
    @Px
    private var iconHeight: Int = 0

    init {
        scaleType = ScaleType.FIT_XY
        attrs?.let { retrieveAttributes(it) }
    }

    /**
     *
     */
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        val width = right - left
        val height = bottom - top

        val horizontalPadding = if(width > iconWidth) (width - iconWidth) / 2 else 0
        val verticalPadding = if(height > iconHeight) (height - iconHeight) / 2 else 0

        setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)

        setImageDrawable(icon)

        super.onLayout(changed, left, top, right, bottom)
    }

    /**
     *
     */
    private fun retrieveAttributes(attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonFixedIconSize)

        icon = typedArray.getDrawable(R.styleable.ImageButtonFixedIconSize_imageButton_icon)!!

        iconWidth = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconWidth, 0f).toInt()
        iconHeight = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconHeight, 0f).toInt()

        typedArray.recycle()
    }
}

And at last you should use your widget like this:

<com.syleiman.gingermoney.ui.common.controls.ImageButtonFixedIconSize
    android:layout_width="90dp"
    android:layout_height="63dp"

    app:imageButton_icon="@drawable/ic_backspace"
    app:imageButton_iconWidth="20dp"
    app:imageButton_iconHeight="15dp"

    android:id="@+id/backspaceButton"
    tools:ignore="ContentDescription"
    />

How to master AngularJS?

The video AngularJS Fundamentals In 60-ish Minutes provides a very good introduction and overview.

I would also highly recomend the AngularJS book from O'Reilly, mentioned by @Atropo.

In SQL how to compare date values?

In standard SQL syntax, you would use:

WHERE mydate <= DATE '2008-11-20'

That is, the keyword DATE should precede the string. In some DBMS, however, you don't need to be that explicit; the system will convert the DATE column into a string, or the string into a DATE value, automatically. There are nominally some interesting implications if the DATE is converted into a string - if you happen to have dates in the first millennium (0001-01-01 .. 0999-12-31) and the leading zero(es) are omitted by the formatting system.

Guid is all 0's (zeros)?

Try doing:

Guid foo = Guid.NewGuid();

Open existing file, append a single line

The technically best way is probably this here:

private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
    if (string.IsNullOrWhiteSpace(path)) 
        throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");

    if (!File.Exists(path)) 
        throw new FileNotFoundException("File not found.", nameof(path));

    using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
    using (var writer = new StreamWriter(file))
    {
        await writer.WriteLineAsync(line);
        await writer.FlushAsync();
    }
}

move column in pandas dataframe

I use Pokémon database as an example, the columns for my data base are

['Name', '#', 'Type 1', 'Type 2', 'Total', 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', 'Generation', 'Legendary']

Here is the code:


import pandas as pd
    df = pd.read_html('https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6')[0] 
    cols = df.columns.to_list()
    cos_end= ["Name", "Total", "HP", "Defense"]

    for i, j in enumerate(cos_end, start=(len(cols)-len(cos_end))):
        cols.insert(i, cols.pop(cols.index(j)))
        print(cols)
        
    df = df.reindex(columns=cols)

    print(df)

Does JavaScript have a built in stringbuilder class?

If you have to write code for Internet Explorer make sure you chose an implementation, which uses array joins. Concatenating strings with the + or += operator are extremely slow on IE. This is especially true for IE6. On modern browsers += is usually just as fast as array joins.

When I have to do lots of string concatenations I usually fill an array and don't use a string builder class:

var html = [];
html.push(
  "<html>",
  "<body>",
  "bla bla bla",
  "</body>",
  "</html>"
);
return html.join("");

Note that the push methods accepts multiple arguments.

iPhone - Get Position of UIView within entire UIWindow

For me this code worked best:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}

Changing button color programmatically

I have finally found a working code - try this:

document.getElementById("button").style.background='#000000';

Progress Bar with HTML and CSS

http://jsfiddle.net/cwZSW/1406/

_x000D_
_x000D_
#progress {_x000D_
    background: #333;_x000D_
    border-radius: 13px;_x000D_
    height: 20px;_x000D_
    width: 300px;_x000D_
    padding: 3px;_x000D_
}_x000D_
_x000D_
#progress:after {_x000D_
    content: '';_x000D_
    display: block;_x000D_
    background: orange;_x000D_
    width: 50%;_x000D_
    height: 100%;_x000D_
    border-radius: 9px;_x000D_
}
_x000D_
<div id="progress"></div>
_x000D_
_x000D_
_x000D_

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

Extract part of a regex match

The currently top-voted answer by Krzysztof Krason fails with <title>a</title><title>b</title>. Also, it ignores title tags crossing line boundaries, e.g., for line-length reasons. Finally, it fails with <title >a</title> (which is valid HTML: White space inside XML/HTML tags).

I therefore propose the following improvement:

import re

def search_title(html):
    m = re.search(r"<title\s*>(.*?)</title\s*>", html, re.IGNORECASE | re.DOTALL)
    return m.group(1) if m else None

Test cases:

print(search_title("<title   >with spaces in tags</title >"))
print(search_title("<title\n>with newline in tags</title\n>"))
print(search_title("<title>first of two titles</title><title>second title</title>"))
print(search_title("<title>with newline\n in title</title\n>"))

Output:

with spaces in tags
with newline in tags
first of two titles
with newline
  in title

Ultimately, I go along with others recommending an HTML parser - not only, but also to handle non-standard use of HTML tags.

Using a scanner to accept String input and storing in a String Array

//go through this code I have made several changes in it//

import java.util.Scanner;

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

//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);

//while name field is empty display prompt etc.
while (i<11)
{
    i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}


while (i<12)
{
    i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}

}   
}

How to execute Ant build in command line

Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME to this directory, then pre-pend to the System PATHvariable, %ANT_HOME%\bin. This way, you don't have to put in the whole directory name.

Assuming you did the above, try this:

C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build

This will do several things:

  • It will eliminate the possibility that the problem is with Eclipe's version of Ant.
  • It is way easier to type
  • Since you're executing the build.xml in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.

The -d will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999, and run cls first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.

Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build target. Here it is:

<target depends="build-subprojects,build-project" name="build"/>

The build target does nothing itself. However, it depends upon two other targets, so these will be called first:

The first target is build-subprojects:

<target name="build-subprojects"/>

This does nothing at all. It doesn't even have a dependency.

The next target specified is build-project does have code:

<target depends="init" name="build-project">

This target does contain tasks, and some dependent targets. Before build-project executes, it will first run the init target:

<target name="init">
    <mkdir dir="bin"/>
    <copy includeemptydirs="false" todir="bin">
        <fileset dir="src">
            <exclude name="**/*.java"/>
        </fileset>
    </copy>
</target>

This target creates a directory called bin, then copies all files under the src tree with the suffix *.java over to the bin directory. The includeemptydirs mean that directories without non-java code will not be created.

Ant uses a scheme to do minimal work. For example, if the bin directory is created, the <mkdir/> task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src directory tree, the <copy/> task won't run. However, the init target will still be executed.

Next, we go back to our previous build-project target:

<target depends="init" name="build-project">
    <echo message="${ant.project.name}: ${ant.file}"/>
    <javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
        <src path="src"/>
        <classpath refid="iControlSilk4J.classpath"/>
    </javac>
</target>

Look at this line:

<echo message="${ant.project.name}: ${ant.file}"/>

That should have always executed. Did your output print:

[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

Maybe you didn't realize that was from your build.

After that, it runs the <javac/> task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java files have previously been compiled, the <javac/> task won't execute.

And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean task, and then build:

C:\Silk4J\Automation\iControlSilk4J> ant -d clean build

However, Ant usually prints the target being executed. You should have seen this:

init:

build-subprojects:

build-projects:

    [echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

build:

Build Successful

Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.

  • If the bin directory already exists, <mkdir/> isn't going to execute.
  • If there are no non-Java files in src, or they have already been copied into bin, the <copy/> task won't execute.
  • If there are no Java file in your src directory, or they have already been compiled, the <java/> task won't run.

If you look at the output from the -d debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.

See if that helps.

The remote end hung up unexpectedly while git cloning

I got solution after using below command:

git repack -a -f -d --window=250 --depth=250

How to track untracked content?

http://progit.org/book/ch6-6.html

I think you should read this to learn a little about submodule. It's well-written, and it doesn't take much time to read it.

Add a "sort" to a =QUERY statement in Google Spreadsheets

Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")

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

The size_t type is defined as the unsigned integral type of the sizeof operator. In the real world, you will often see int defined as 32 bits (for backward compatibility) but size_t defined as 64 bits (so you can declare arrays and structures more than 4 GiB in size) on 64-bit platforms. If a long int is also 64-bits, this is called the LP64 convention; if long int is 32 bits but long long int and pointers are 64 bits, that’s LLP64. You also might get the reverse, a program that uses 64-bit instructions for speed, but 32-bit pointers to save memory. Also, int is signed and size_t is unsigned.

There were historically a number of other platforms where addresses were wider or shorter than the native size of int. In fact, in the ’70s and early ’80s, this was more common than not: all the popular 8-bit microcomputers had 8-bit registers and 16-bit addresses, and the transition between 16 and 32 bits also produced many machines that had addresses wider than their registers. I occasionally still see questions here about Borland Turbo C for MS-DOS, whose Huge memory mode had 20-bit addresses stored in 32 bits on a 16-bit CPU (but which could support the 32-bit instruction set of the 80386); the Motorola 68000 had a 16-bit ALU with 32-bit registers and addresses; there were IBM mainframes with 15-bit, 24-bit or 31-bit addresses. You also still see different ALU and address-bus sizes in embedded systems.

Any time int is smaller than size_t, and you try to store the size or offset of a very large file or object in an unsigned int, there is the possibility that it could overflow and cause a bug. With an int, there is also the possibility of getting a negative number. If an int or unsigned int is wider, the program will run correctly but waste memory.

You should generally use the correct type for the purpose if you want portability. A lot of people will recommend that you use signed math instead of unsigned (to avoid nasty, subtle bugs like 1U < -3). For that purpose, the standard library defines ptrdiff_t in <stddef.h> as the signed type of the result of subtracting a pointer from another.

That said, a workaround might be to bounds-check all addresses and offsets against INT_MAX and either 0 or INT_MIN as appropriate, and turn on the compiler warnings about comparing signed and unsigned quantities in case you miss any. You should always, always, always be checking your array accesses for overflow in C anyway.

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

How can I change CSS display none or block property using jQuery?

In case you want to hide and show an element, depending on whether it is already visible or not, you can use toggle instead of .hide() and .show()

$('elem').toggle();

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

First go to Wamp->Apache->Service->Test Port 80

If its being user by Microsoft HTTPAPI / 2.0

Then the solution is to manually stop the service named web deployment agent service

If you have Microsoft Sql Server installed, even though the IIS service is disabled, it keeps a web service named httpapi2.0 running.

keypress, ctrl+c (or some combo like that)

Try the Jquery Hotkeys plugin instead - it'll do everything you require.

jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.

This plugin is based off of the plugin by Tzury Bar Yochay: jQuery.hotkeys

The syntax is as follows:

$(expression).bind(types, keys, handler); $(expression).unbind(types, handler);

$(document).bind('keydown', 'ctrl+a', fn);

// e.g. replace '$' sign with 'EUR'
// $('input.foo').bind('keyup', '$', function(){   
//      this.value = this.value.replace('$', 'EUR'); });

Is quitting an application frowned upon?

Blog post When to Include an Exit Button in Android Apps (Hint: Never) explains it far, far better than I can. I wish every Android developer has read it already.

Excerpts:

In my experience what [the users] really want is: An unambiguous way to guarantee that an app will stop consuming resources (battery, CPU cycles, data transfer, etc.).

Many users perceive that an exit button implements this requirement and ask for it to be added. Developers, looking to please their users, obligingly add one. Shortly thereafter they both fail.

  • In most cases the exit button simply calls Activity.finish(). This is exactly equivalent to hitting the back button. Exactly. Services keep running and polling keeps happening. Users may think they've killed the app but they haven't, and soon they'll be even more annoyed.
  • Exit behavior is now ambiguous. Should your exit button just close the Activity, or should it also stop all associated Services, Receivers, and Alarms? What should Back do? What happens if they hit Home instead? What happens if your app has a widget? Should the exit button stop that from updating too?

The solution is to make the back button behave as you'd expect the exit button to. Better yet, simply stop consuming resources whenever the app isn't visible.

Go ahead and read the complete article.

How to get PHP $_GET array?

You could make id a series of comma-seperated values, like this:

index.php?id=1,2,3&name=john

Then, within your PHP code, explode it into an array:

$values = explode(",", $_GET["id"]);
print count($values) . " values passed.";

This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:

index.php?id[]=1&id[]=2&id[]=3&name=john

But that clearly would be much more verbose.

What's the u prefix in a Python string?

I came here because I had funny-char-syndrome on my requests output. I thought response.text would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.

Turns out response.encoding was empty somehow and so response did not know how to properly decode the content and just treated it as ASCII (I guess).

My solution was to get the raw bytes with 'response.content' and manually apply decode('utf_8') to it. The result was schöne Umlaute.

The correctly decoded

für

vs. the improperly decoded

fAzr

How do I call Objective-C code from Swift?

After you created a Bridging header, go to Build Setting => Search for "Objective-C Bridging Header".

Just below you will find the ""Objective-C Generated Interface Header Name" file.

Import that file in your view controller.

Example: In my case: "Dauble-Swift.h"

eEter image description here

What exactly is LLVM?

A good summary of LLVM is this:

enter image description here

At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.

At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.

Using command line arguments in VBscript

Set args = Wscript.Arguments

For Each arg In args
  Wscript.Echo arg
Next

From a command prompt, run the script like this:

CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"

Will give results like this:

1
2
A
B
Arg with spaces

String or binary data would be truncated. The statement has been terminated

The maximal length of the target column is shorter than the value you try to insert.

Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions.

Edit:

Try to set a length on your nvarchar inserts thats the same or shorter than whats defined in your table.

With CSS, how do I make an image span the full width of the page as a background image?

Background images, ideally, are always done with CSS. All other images are done with html. This will span the whole background of your site.

body {
  background: url('../images/cat.ong');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

Cannot import XSSF in Apache POI

I needed the following files for my implementation:

  • poi-ooxml-schemas-3.14.20160307.jar
  • commons-codec-1.10.jar (this was in "lib" folder of the zip file you get from apache)
  • curvesapi-1.03.jar (in "ooxml-lib" folder)
  • poi-3.14-20160307.jar
  • poi-ooxml-3.14-20160307.jar
  • xmlbeans-2.6.0.jar (in "ooxml-lib" folder)

(though honestly, I'm not completely sure they are all necessary...) It's a little confusing because they are packaged that way. I needed to place them manually in my own "lib" folder and then add the references...

Maven always seems to download more than I need, so I always place libaries/dlls and things like that manually.

How to print colored text to the terminal?

The answer is Colorama for all cross-platform coloring in Python.

It supports Python 3.5+ as well as Python 2.7.

And as of January 2021 it is maintained.

Example screenshot: example screenshot

What is the difference between Serializable and Externalizable in Java?

When considering options for improving performance, don't forget custom serialization. You can let Java do what it does well, or at least good enough, for free, and provide custom support for what it does badly. This is usually a lot less code than full Externalizable support.

How do I use StringUtils in Java?

java.lang does not contain a class called StringUtils. Several third-party libs do, such as Apache Commons Lang or the Spring framework. Make sure you have the relevant jar in your project classpath and import the correct class.

Is it possible to run one logrotate check manually?

The way to run all of logrotate is:

logrotate -f /etc/logrotate.conf

that will run the primary logrotate file, which includes the other logrotate configurations as well

How to pass all arguments passed to my bash script to a function of mine?

Here's a simple script:

#!/bin/bash

args=("$@")

echo Number of arguments: $#
echo 1st argument: ${args[0]}
echo 2nd argument: ${args[1]}

$# is the number of arguments received by the script. I find easier to access them using an array: the args=("$@") line puts all the arguments in the args array. To access them use ${args[index]}.

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

Determining the last row in a single column

Update 2021 - Considers also empty cells

The accepted answer as well as most of the answers (if not all of them) have one common limitation which might not be the case for the owner of the question (they have contiguous data) but for future readers.

  • Namely, if the selected column contains empty cells in between, the accepted answer would give the wrong result.

For example, consider this very simple scenario:

enter image description here

the accepted solution would give 4 while the correct answer is 6.

Solution:

Find the index of first non-empty value starting from the end of the array by using the reverse method.

const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1')
const lrow = sh.getLastRow();
const Avals = sh.getRange("A1:A"+lrow).getValues();
const Alast  = lrow - Avals.reverse().findIndex(c=>c[0]!='');

Conditional Count on a field

You could join the table against itself:

select
   t.jobId, t.jobName,
   count(p1.jobId) as Priority1,
   count(p2.jobId) as Priority2,
   count(p3.jobId) as Priority3,
   count(p4.jobId) as Priority4,
   count(p5.jobId) as Priority5
from
   theTable t
   left join theTable p1 on p1.jobId = t.jobId and p1.jobName = t.jobName and p1.Priority = 1
   left join theTable p2 on p2.jobId = t.jobId and p2.jobName = t.jobName and p2.Priority = 2
   left join theTable p3 on p3.jobId = t.jobId and p3.jobName = t.jobName and p3.Priority = 3
   left join theTable p4 on p4.jobId = t.jobId and p4.jobName = t.jobName and p4.Priority = 4
   left join theTable p5 on p5.jobId = t.jobId and p5.jobName = t.jobName and p5.Priority = 5
group by
   t.jobId, t.jobName

Or you could use case inside a sum:

select
   jobId, jobName,
   sum(case Priority when 1 then 1 else 0 end) as Priority1,
   sum(case Priority when 2 then 1 else 0 end) as Priority2,
   sum(case Priority when 3 then 1 else 0 end) as Priority3,
   sum(case Priority when 4 then 1 else 0 end) as Priority4,
   sum(case Priority when 5 then 1 else 0 end) as Priority5
from
   theTable
group by
   jobId, jobName

Force "git push" to overwrite remote files

Another option (to avoid any forced push which can be problematic for other contributors) is to:

  • put your new commits in a dedicated branch
  • reset your master on origin/master
  • merge your dedicated branch to master, always keeping commits from the dedicated branch (meaning creating new revisions on top of master which will mirror your dedicated branch).
    See "git command for making one branch like another" for strategies to simulate a git merge --strategy=theirs.

That way, you can push master to remote without having to force anything.

How to use PrintWriter and File classes in Java?

If you want to use PrintWrite then try this code

public class PrintWriter {
    public static void main(String[] args) throws IOException {

        java.io.PrintWriter pw=new java.io.PrintWriter("file.txt");
        pw.println("hello world");
        pw.flush();
        pw.close();

    }

}

How do I create a ListView with rounded corners in Android?

to make border u have to make another xml file with property of solid and corners in the drawable folder and calls it in background

iPhone viewWillAppear not firing

I just had the same issue. In my application I have 2 navigation controllers and pushing the same view controller in each of them worked in one case and not in the other. I mean that when pushing the exact same view controller in the first UINavigationController, viewWillAppear was called but not when pushed in the second navigation controller.

Then I came across this post UINavigationController should call viewWillAppear/viewWillDisappear methods

And realized that my second navigation controller did redefine viewWillAppear. Screening the code showed that I was not calling

[super viewWillAppear:animated];

I added it and it worked !

The documentation says:

If you override this method, you must call super at some point in your implementation.

Could not load file or assembly 'System.Data.SQLite'

Manual load related System.Data.SQLite assembly can resolve this.

Changed gatapia's Code as below:

    public static void LoadSQLLiteAssembly()
    {
        Uri dir = new Uri(Assembly.GetExecutingAssembly().CodeBase);
        FileInfo fi = new FileInfo(dir.AbsolutePath);
        string appropriateFile = Path.Combine(fi.Directory.FullName, GetAppropriateSQLLiteAssembly());
        Assembly.LoadFrom(appropriateFile);
    }

    private static string GetAppropriateSQLLiteAssembly()
    {
        string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
        string arch = ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? "32" : "64");
        return "System.Data.SQLite.x" + arch + ".DLL";
    }

Java SecurityException: signer information does not match

This can occur with the cglib-instrumented proxies because CGLIB uses his own signer information instead of the signer information of the application target class.

How to send an email with Gmail as provider using Python?

Here is a Gmail API example. Although more complicated, this is the only method I found that works in 2019. This example was taken and modified from:

https://developers.google.com/gmail/api/guides/sending

You'll need create a project with Google's API interfaces through their website. Next you'll need to enable the GMAIL API for your app. Create credentials and then download those creds, save it as credentials.json.

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

from email.mime.text import MIMEText
import base64

#pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send']

def create_message(sender, to, subject, msg):
    message = MIMEText(msg)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    # Base 64 encode
    b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
    b64_string = b64_bytes.decode()
    return {'raw': b64_string}
    #return {'raw': base64.urlsafe_b64encode(message.as_string())}

def send_message(service, user_id, message):
    #try:
    message = (service.users().messages().send(userId=user_id, body=message).execute())
    print( 'Message Id: %s' % message['id'] )
    return message
    #except errors.HttpError, error:print( 'An error occurred: %s' % error )

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Example read operation
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
    for label in labels:
        print(label['name'])

    # Example write
    msg = create_message("[email protected]", "[email protected]", "Subject", "Msg")
    send_message( service, 'me', msg)

if __name__ == '__main__':
    main()

Pick any kind of file via an Intent in Android

If you want to know this, it exists an open source library called aFileDialog that it is an small and easy to use which provides a file picker.

The difference with another file chooser's libraries for Android is that aFileDialog gives you the option to open the file chooser as a Dialog and as an Activity.

It also lets you to select folders, create files, filter files using regular expressions and show confirmation dialogs.

How do I convert a double into a string in C++?

The problem with lexical_cast is the inability to define precision. Normally if you are converting a double to a string, it is because you want to print it out. If the precision is too much or too little, it would affect your output.

Easiest way to split a string on newlines in .NET?

using System.IO;

string textToSplit;

if (textToSplit != null)
{
    List<string> lines = new List<string>();
    using (StringReader reader = new StringReader(textToSplit))
    {
        for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
        {
            lines.Add(line);
        }
    }
}

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

The error is because difference in datatypes of y_pred and y_true. y_true might be dataframe and y_pred is arraylist. If you convert both to arrays, then issue will get resolved.

Django: OperationalError No Such Table

I got through the same error when I went on to the admin panel. You ought to run this instead-: python manage.py migrate --run-syncdb. Don't forget to include migrate, I ran:

python manage.py make migrations and then python manage.py migrate

Still when the error persisted I tried it with the above suggested command.

Error 500: Premature end of script headers

Error can be caused by various issues. for more info check suexec or fcgi logs. For example if suexec has wrong user and permssion it can cause the error to occur to solve try

chgrp WEBGROUP /usr/local/apache2/bin/suexec
chmod 4750 /usr/local/apache2/bin/suexec

Send raw ZPL to Zebra printer via USB

I spent 8 hours to do that. It is simple...

You shoud have a code like that:

private const int GENERIC_WRITE = 0x40000000;

//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;

Change that variable content from 3 (open file already exist) to 1 (create a new file). It'll work at Windows 7 and XP.

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

Number of processors/cores in command line

If you need an os independent method, works across Windows and Linux. Use python

$ python -c 'import multiprocessing as m; print m.cpu_count()'
16

How do I show a console output/window in a forms application?

Why not just leave it as a Window Forms app, and create a simple form to mimic the Console. The form can be made to look just like the black-screened Console, and have it respond directly to key press. Then, in the program.cs file, you decide whether you need to Run the main form or the ConsoleForm. For example, I use this approach to capture the command line arguments in the program.cs file. I create the ConsoleForm, initially hide it, then pass the command line strings to an AddCommand function in it, which displays the allowed commands. Finally, if the user gave the -h or -? command, I call the .Show on the ConsoleForm and when the user hits any key on it, I shut down the program. If the user doesn't give the -? command, I close the hidden ConsoleForm and Run the main form.

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

@import vs #import - iOS 7

It currently only works for the built in system frameworks. If you use #import like apple still do importing the UIKit framework in the app delegate it is replaced (if modules is on and its recognised as a system framework) and the compiler will remap it to be a module import and not an import of the header files anyway. So leaving the #import will be just the same as its converted to a module import where possible anyway

Best solution to protect PHP code without encryption

They distribute their software under a proprietary license. The law protects their rights and prevents their customers from redistributing the source, though there is no actual difficulty doing so.

But as you might be well aware, copyright infringement (piracy) of software products is a pretty common phenomenon.

Forward declaration of a typedef in C++

I replaced the typedef (using to be specific) with inheritance and constructor inheritance (?).

Original

using CallStack = std::array<StackFrame, MAX_CALLSTACK_DEPTH>;

Replaced

struct CallStack // Not a typedef to allow forward declaration.
  : public std::array<StackFrame, MAX_CALLSTACK_DEPTH>
{
  typedef std::array<StackFrame, MAX_CALLSTACK_DEPTH> Base;
  using Base::Base;
};

This way I was able to forward declare CallStack with:

class CallStack;

Routing HTTP Error 404.0 0x80070002

The solution suggested

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    
  </modules>
</system.webServer>

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.

Full-screen responsive background image

This worked for me, so posting this.

.my-container {
  position: relative;
  background: #696969;
  overflow: hidden;
}
.my-container:before {
  content: ' ';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  opacity: 0.6;
  background-image: url('https://images.pexels.com/photos/1084542/pexels-photo-1084542.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
  background-repeat: no-repeat;
  background-position: 50% 0;
  -ms-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  background-size: cover;
}

Sort array of objects by single key with date value

For completeness here is a possible short generic implementation of sortBy:

function sortBy(list, keyFunc) {
  return list.sort((a,b) => keyFunc(a) - keyFunc(b));
}

sortBy([{"key": 2}, {"key": 1}], o => o["key"])

Note that this uses the arrays sort method that sorts in place. for a copy you can use arr.concat() or arr.slice(0) or similar method to create a copy.

Taking screenshot on Emulator from Android Studio

Long Press on Power button, then you will have the option for the screenshot. Power Button Emulator

Option for screenshot in emulator

Can I use a min-height for table, tr or td?

Tables and table cells don't use the min-height property, setting their height will be the min-height as tables will expand if the content stretches them.

Best tool for inspecting PDF files?

Besides the GUI-based tools mentioned in the other answers, there are a few command line tools which can transform the original PDF source code into a different representation which lets you inspect the (now modified file) with a text editor. All of the tools below work on Linux, Mac OS X, other Unix systems or Windows.

qpdf (my favorite)

Use qpdf to uncompress (most) object's streams and also dissect ObjStm objects into individual indirect objects:

qpdf --qdf --object-streams=disable orig.pdf uncompressed-qpdf.pdf

qpdf describes itself as a tool that does "structural, content-preserving transformations on PDF files".

Then just open + inspect the uncompressed-qpdf.pdf file in your favorite text editor. Most of the previously compressed (and hence, binary) bytes will now be plain text.

mutool

There is also the mutool command line tool which comes bundled with the MuPDF PDF viewer (which is a sister product to Ghostscript, made by the same company, Artifex). The following command does also uncompress streams and makes them more easy to inspect through a text editor:

mutool clean -d orig.pdf uncompressed-mutool.pdf

podofouncompress

PoDoFo is an FreeSoftware/OpenSource library to work with the PDF format and it includes a few command line tools, including podofouncompress. Use it like this to uncompress PDF streams:

podofouncompress orig.pdf uncompressed-podofo.pdf

peepdf.py

PeePDF is a Python-based tool which helps you to explore PDF files. Its original purpose was for research and dissection of PDF-based malware, but I find it useful also to investigate the structure of completely benign PDF files.

It can be used interactively to "browse" the objects and streams contained in a PDF.

I'll not give a usage example here, but only a link to its documentation:

pdfid.py and pdf-parser.py

pdfid.py and pdf-parser.py are two PDF tools by Didier Stevens written in Python.

Their background is also to help explore malicious PDFs -- but I also find it useful to analyze the structure and contents of benign PDF files.

Here is an example how I would extract the uncompressed stream of PDF object no. 5 into a *.dump file:

pdf-parser.py -o 5 -f -d obj5.dump my.pdf

Final notes

  1. Please note that some binary parts inside a PDF are not necessarily uncompressible (or decode-able into human readable ASCII code), because they are embedded and used in their native format inside PDFs. Such PDF parts are JPEG images, fonts or ICC color profiles.

  2. If you compare above tools and the command line examples given, you will discover that they do NOT all produce identical outputs. The effort of comparing them for their differences in itself can help you to better understand the nature of the PDF syntax and file format.

Difference between subprocess.Popen and os.system

If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system() with subprocess.Popen():

sts = os.system("mycmd" + " myarg")

...does the same thing as...

sts = Popen("mycmd" + " myarg", shell=True).wait()

The "improved" code looks more complicated, but it's better because once you know subprocess.Popen(), you don't need anything else. subprocess.Popen() replaces several other tools (os.system() is just one of those) that were scattered throughout three other Python modules.

If it helps, think of subprocess.Popen() as a very flexible os.system().

Turning off eslint rule for a specific file

Simply create an empty file .eslintignore in your project root the type the path to the file you want it to be ignore.

Source: https://eslint.org/docs/2.13.1/user-guide/configuring#:~:text=To%20disable%20rule%20warnings%20in,*%2F%20alert('foo')%3B

Line Ignoring Files and Directories

What does the "On Error Resume Next" statement do?

When an error occurs, the execution will continue on the next line without interrupting the script.

Efficient way to insert a number into a sorted array of numbers?

Here are a few thoughts: Firstly, if you're genuinely concerned about the runtime of your code, be sure to know what happens when you call the built-in functions! I don't know up from down in javascript, but a quick google of the splice function returned this, which seems to indicate that you're creating a whole new array each call! I don't know if it actually matters, but it is certainly related to efficiency. I see that Breton, in the comments, has already pointed this out, but it certainly holds for whatever array-manipulating function you choose.

Anyways, onto actually solving the problem.

When I read that you wanted to sort, my first thought is to use insertion sort!. It is handy because it runs in linear time on sorted, or nearly-sorted lists. As your arrays will have only 1 element out of order, that counts as nearly-sorted (except for, well, arrays of size 2 or 3 or whatever, but at that point, c'mon). Now, implementing the sort isn't too too bad, but it is a hassle you may not want to deal with, and again, I don't know a thing about javascript and if it will be easy or hard or whatnot. This removes the need for your lookup function, and you just push (as Breton suggested).

Secondly, your "quicksort-esque" lookup function seems to be a binary search algorithm! It is a very nice algorithm, intuitive and fast, but with one catch: it is notoriously difficult to implement correctly. I won't dare say if yours is correct or not (I hope it is, of course! :)), but be wary if you want to use it.

Anyways, summary: using "push" with insertion sort will work in linear time (assuming the rest of the array is sorted), and avoid any messy binary search algorithm requirements. I don't know if this is the best way (underlying implementation of arrays, maybe a crazy built-in function does it better, who knows), but it seems reasonable to me. :) - Agor.

How can I add new dimensions to a Numpy array?

You can use np.concatenate() specifying which axis to append, using np.newaxis:

import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)

If you are reading from many files:

import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)

AttributeError: can't set attribute in python

namedtuples are immutable, just like standard tuples. You have two choices:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.

The former would look like:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

Export table data from one SQL Server to another

For copying data from source to destination:

use <DestinationDatabase>
select * into <DestinationTable> from <SourceDataBase>.dbo.<SourceTable>

Angular 2 - Redirect to an external URL and open in a new tab

To solve this issue more globally, here is another way using a directive:

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
  selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
  constructor(elementRef: ElementRef) {}

  @HostListener("click", ["$event"])
  onClick(event: MouseEvent) {
    event.preventDefault();

    let url: string = (<any>event.currentTarget).getAttribute("href");

    if (url && url.indexOf("http") === -1) {
      url = `//${url}`;
    }

    window.open(url, "_blank");
  }
}

then it's as simple as using it like this:

<a [href]="url" hrefExternalUrl> Link </a>

and don't forget to declare the directive in your module.

HTML table with fixed headers?

Two divs, one for header, one for data. Make the data div scrollable, and use JavaScript to set the width of the columns in the header to be the same as the widths in the data. I think the data columns widths need to be fixed rather than dynamic.

Python error message io.UnsupportedOperation: not readable

Use a+ to open a file for reading, writing as well as create it if it doesn't exist.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

with open('"File.txt', 'a+') as file:
    print(file.readlines())
    file.write("test")

Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

How can I use SUM() OVER()

Query would be like this:

SELECT ID, AccountID, Quantity, 
       SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT 

       FROM #Empl ORDER BY AccountID

Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.

First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10

so result would appear like attached snapshot.

org.apache.jasper.JasperException: Unable to compile class for JSP:

Please remove the servlet jar from web project,as any how, the application/web server already had.

How can I get the IP address from NIC in Python?

try below code, it works for me in Mac10.10.2:

import subprocess

if __name__ == "__main__":
    result = subprocess.check_output('ifconfig en0 |grep -w inet', shell=True) # you may need to use eth0 instead of en0 here!!!
    print 'output = %s' % result.strip()
    # result = None
    ip = ''
    if result:
        strs = result.split('\n')
        for line in strs:
            # remove \t, space...
            line = line.strip()
            if line.startswith('inet '):
                a = line.find(' ')
                ipStart = a+1
                ipEnd = line.find(' ', ipStart)
                if a != -1 and ipEnd != -1:
                    ip = line[ipStart:ipEnd]
                    break
    print 'ip = %s' % ip

Problems after upgrading to Xcode 10: Build input file cannot be found

I know that this is an old subject, but I found the issue with xcode 12.3 and was related to an error while doing the CopyPlist of the main.Storyboard during compilation.

Actually, changing the build settings to "Legacy Build Setting" worked, but it is deprecated, so I discarded it because is a short term solution.

Check this:

enter image description here

With that setting, worked for me. Before I had "Copy plist".

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

Can I clear cell contents without changing styling?

You should use the ClearContents method if you want to clear the content but preserve the formatting.

Worksheets("Sheet1").Range("A1:G37").ClearContents

How can I make the browser wait to display the page until it's fully loaded?

Also make sure the server buffers the page and does not immediately (while building) stream it to the client browser.

Since you have not specified your technology stack:

  • PHP: look into ob_start
  • ASP.NET: make sure Response.BufferOutput = True (it is by default)