Programs & Examples On #Invocationtargetexception

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Android Room - simple select query - Cannot access database on the main thread

The error message,

Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.

Is quite descriptive and accurate. The question is how should you avoid accessing the database on the main thread. That is a huge topic, but to get started, read about AsyncTask (click here)

-----EDIT----------

I see you are having problems when you run a unit test. You have a couple of choices to fix this:

  1. Run the test directly on the development machine rather than on an Android device (or emulator). This works for tests that are database-centric and don't really care whether they are running on a device.

  2. Use the annotation @RunWith(AndroidJUnit4.class) to run the test on the android device, but not in an activity with a UI. More details about this can be found in this tutorial

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

Run hive in debug mode

hive -hiveconf hive.root.logger=DEBUG,console

and then execute

show tables

can find the actual problem

READ_EXTERNAL_STORAGE permission for Android

http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html

Try changing the line contentResolver.query

//change it to the columns you need
String[] columns = new String[]{MediaStore.Audio.AudioColumns.DATA}; 
Cursor cursor = contentResolver.query(uri, columns, null, null, null);

public static final String MEDIA_CONTENT_CONTROL

Not for use by third-party applications due to privacy of media consumption

http://developer.android.com/reference/android/Manifest.permission.html#MEDIA_CONTENT_CONTROL

try to remove the <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/> first and try again?

Error inflating class android.support.design.widget.NavigationView

Just for who still get to this issue. I got to the same problem but all the solutions here is not work for me.

Just take alook on NavigationView class with cue from logcat, i found the issue come form this line of code:

itemTextColor = this.createDefaultColorStateList(16842806);

So, it seem related to itemTextColor as Aenur56 mentioned. So i tried with Aenur56's solution but it doesn't work.

Take a look on the line of code above, i notice that there is ColorStateList. So i create one then set for itemTextColor then it work.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#00FF00" android:state_checked="true" />
    <item android:color="#000000" />
</selector>

Hope it help!

Error inflating class android.support.v7.widget.Toolbar?

I have fixed this problem by modifying app build.gradle file.

For Gradle Plugin 2.0+

 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
    }  
 }  

For Gradle Plugin 1.5

 android {  
   defaultConfig {  

     generatedDensities = []  
  }  

  aaptOptions {  
    additionalParameters "--no-version-vectors"  
  }  
 } 

Launching Spring application Address already in use

This only worked for me by setting additional properties and using available arbitrary port numbers, like this:

  • YML

/src/main/resources/application.yml

server:
  port: 18181
management:
  port: 9191
tomcat:
  jvmroute: 5478
  ajp:
    port: 4512
    redirectPort: 1236
  • Properties

/src/main/resources/application.properties

server.port=18181
management.port=9191
tomcat.jvmroute=5478
tomcat.ajp.port=4512
tomcat.ajp.redirectPort=1236     

IOException: read failed, socket might closed - Bluetooth on Android 4.3

Even i had the same problem ,finally understand my issue , i was trying to connect from (out of range) Bluetooth coverage range.

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

If you look at the chain of exceptions, the problem is

Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property salt in class backend.Account

The problem is that the method Account.setSalt() works fine when you create an instance but not when you retrieve an instance from the database. This is because you don't want to create a new salt each time you load an Account.

To fix this, create a method setSalt(long) with visibility private and Hibernate will be able to set the value (just a note, I think it works with Private, but you might need to make it package or protected).

Can't access Eclipse marketplace

Here's the solution,

If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,

1. GO TO

Window-> Preferences -> General -> Network Connection.

2. Change the Settings

Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS

If your active provider is already set to Manual, try restoring the default (native)


That's all, restart Eclipse and you are good to go!


How to log as much information as possible for a Java Exception?

It should be quite simple if you are using LogBack or SLF4J. I do it as below

//imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//Initialize logger
Logger logger = LoggerFactory.getLogger(<classname>.class);
try {
   //try something
} catch(Exception e){
   //Actual logging of error
   logger.error("some message", e);
}

What could cause java.lang.reflect.InvocationTargetException?

That InvocationTargetException is probably wrapping up your ArrayIndexOutOfBoundsException. There is no telling upfront when using reflection what that method can throw -- so rather than using a throws Exception approach, all the exceptions are being caught and wrapped up in InvocationTargetException.

Disabling contextual LOB creation as createClob() method threw error

Just add below line in application.properties

spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults: false

Java: Casting Object to Array type

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0];

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

tar: file changed as we read it

It worked for me by adding a simple sleep timeout of 20 sec. This might happen if your source directory is still writing. Hence put a sleep so that the backup would finish and then tar should work fine. This also helped me in getting the right exit status.

sleep 20
tar -czf ${DB}.${DATE}.tgz ./${DB}.${DATE}

What does Docker add to lxc-tools (the userspace LXC tools)?

From the Docker FAQ:

Docker is not a replacement for lxc. "lxc" refers to capabilities of the linux kernel (specifically namespaces and control groups) which allow sandboxing processes from one another, and controlling their resource allocations.

On top of this low-level foundation of kernel features, Docker offers a high-level tool with several powerful functionalities:

  • Portable deployment across machines. Docker defines a format for bundling an application and all its dependencies into a single object which can be transferred to any docker-enabled machine, and executed there with the guarantee that the execution environment exposed to the application will be the same. Lxc implements process sandboxing, which is an important pre-requisite for portable deployment, but that alone is not enough for portable deployment. If you sent me a copy of your application installed in a custom lxc configuration, it would almost certainly not run on my machine the way it does on yours, because it is tied to your machine's specific configuration: networking, storage, logging, distro, etc. Docker defines an abstraction for these machine-specific settings, so that the exact same docker container can run - unchanged - on many different machines, with many different configurations.

  • Application-centric. Docker is optimized for the deployment of applications, as opposed to machines. This is reflected in its API, user interface, design philosophy and documentation. By contrast, the lxc helper scripts focus on containers as lightweight machines - basically servers that boot faster and need less ram. We think there's more to containers than just that.

  • Automatic build. Docker includes a tool for developers to automatically assemble a container from their source code, with full control over application dependencies, build tools, packaging etc. They are free to use make, maven, chef, puppet, salt, debian packages, rpms, source tarballs, or any combination of the above, regardless of the configuration of the machines.

  • Versioning. Docker includes git-like capabilities for tracking successive versions of a container, inspecting the diff between versions, committing new versions, rolling back etc. The history also includes how a container was assembled and by whom, so you get full traceability from the production server all the way back to the upstream developer. Docker also implements incremental uploads and downloads, similar to "git pull", so new versions of a container can be transferred by only sending diffs.

  • Component re-use. Any container can be used as an "base image" to create more specialized components. This can be done manually or as part of an automated build. For example you can prepare the ideal python environment, and use it as a base for 10 different applications. Your ideal postgresql setup can be re-used for all your future projects. And so on.

  • Sharing. Docker has access to a public registry (https://registry.hub.docker.com/) where thousands of people have uploaded useful containers: anything from redis, couchdb, postgres to irc bouncers to rails app servers to hadoop to base images for various distros. The registry also includes an official "standard library" of useful containers maintained by the docker team. The registry itself is open-source, so anyone can deploy their own registry to store and transfer private containers, for internal server deployments for example.

  • Tool ecosystem. Docker defines an API for automating and customizing the creation and deployment of containers. There are a huge number of tools integrating with docker to extend its capabilities. PaaS-like deployment (Dokku, Deis, Flynn), multi-node orchestration (maestro, salt, mesos, openstack nova), management dashboards (docker-ui, openstack horizon, shipyard), configuration management (chef, puppet), continuous integration (jenkins, strider, travis), etc. Docker is rapidly establishing itself as the standard for container-based tooling.

I hope this helps!

Can't get Gulp to run: cannot find module 'gulp-util'

This will solve all gulp problem

sudo npm install gulp && sudo npm install --save del && sudo gulp build

Calling a function of a module by using its name (a string)

Given a string, with a complete python path to a function, this is how I went about getting the result of said function:

import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()

How to deselect all selected rows in a DataGridView control?

To deselect all rows and cells in a DataGridView, you can use the ClearSelection method:

myDataGridView.ClearSelection()

If you don't want even the first row/cell to appear selected, you can set the CurrentCell property to Nothing/null, which will temporarily hide the focus rectangle until the control receives focus again:

myDataGridView.CurrentCell = Nothing

To determine when the user has clicked on a blank part of the DataGridView, you're going to have to handle its MouseUp event. In that event, you can HitTest the click location and watch for this to indicate HitTestInfo.Nowhere. For example:

Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
    ''# See if the left mouse button was clicked
    If e.Button = MouseButtons.Left Then
        ''# Check the HitTest information for this click location
        If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
            myDataGridView.ClearSelection()
            myDataGridView.CurrentCell = Nothing
        End If
    End If
End Sub

Of course, you could also subclass the existing DataGridView control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp method similar to the way shown above. I also like to provide a public DeselectAll method for convenience that both calls the ClearSelection method and sets the CurrentCell property to Nothing.

(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)

CSS Animation onClick

You just use the :active pseudo-class. This is set when you click on any element.

.classname:active {
    /* animation css */
}

Spring Boot: How can I set the logging level with application.properties?

You can try setting the log level to DEBUG it will show everything while starting the application

logging.level.root=DEBUG

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A, Ctrl + \ - Exit screen and terminate all programs in this screen. It is helpful, for example, if you need to close a tty connection.

  • Ctrl + D, D or - Ctrl + A, Ctrl + D - "minimize" screen and screen -r to restore it.

Rename a file using Java

As far as I know, renaming a file will not append its contents to that of an existing file with the target name.

About renaming a file in Java, see the documentation for the renameTo() method in class File.

How to set a DateTime variable in SQL Server 2008?

The CONVERT function helps.Check this:

declare @erro_event_timestamp as Timestamp;
set @erro_event_timestamp = CONVERT(Timestamp,  '2020-07-06 05:19:44.380',  121);

The magic number 121 I found here: https://www.w3schools.com/SQL/func_sqlserver_convert.asp

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

I got

No 'Access-Control-Allow-Origin' header is present

and the problem was with the URL I was providing. I was providing the URL without a route, e.g., https://misty-valley-1234.herokuapp.com/.

When I added a path it worked, e.g., https://misty-valley-1234.herokuapp.com/messages. With GET requests it worked either way but with POST responses it only worked with the added path.

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

How to pass a type as a method parameter in Java

Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.

How many types do you plan to deal with?

UPDATE:

If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):

package generics;

public interface XmlGenerator<T>
{
   String getXml(T value);
}

And the concrete implementation XmlGeneratorImpl:

    package generics;

public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
    private Class<T> valueType;
    private static final int DEFAULT_CAPACITY = 1024;

    public static void main(String [] args)
    {
        Integer x = 42;
        String y = "foobar";

        XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
        XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);

        System.out.println("integer: " + intXmlGenerator.getXml(x));
        System.out.println("string : " + stringXmlGenerator.getXml(y));
    }

    public XmlGeneratorImpl(Class<T> clazz)
    {
        this.valueType = clazz;
    }

    public String getXml(T value)
    {
        StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);

        appendTag(builder);
        builder.append(value);
        appendTag(builder, false);

        return builder.toString();
    }

    private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }

    private void appendTag(StringBuilder builder, boolean isClosing)
    {
        String valueTypeName = valueType.getName();
        builder.append("<").append(valueTypeName);
        if (isClosing)
        {
            builder.append("/");
        }
        builder.append(">");
    }
}

If I run this, I get the following result:

integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>

I don't know if this is what you had in mind.

What is the difference between const and readonly in C#?

Const and readonly are similar, but they are not exactly the same. A const field is a compile-time constant, meaning that that value can be computed at compile-time. A readonly field enables additional scenarios in which some code must be run during construction of the type. After construction, a readonly field cannot be changed.

For instance, const members can be used to define members like:

struct Test
{
    public const double Pi = 3.14;
    public const int Zero = 0;
}

since values like 3.14 and 0 are compile-time constants. However, consider the case where you define a type and want to provide some pre-fab instances of it. E.g., you might want to define a Color class and provide "constants" for common colors like Black, White, etc. It isn't possible to do this with const members, as the right hand sides are not compile-time constants. One could do this with regular static members:

public class Color
{
    public static Color Black = new Color(0, 0, 0);
    public static Color White = new Color(255, 255, 255);
    public static Color Red = new Color(255, 0, 0);
    public static Color Green = new Color(0, 255, 0);
    public static Color Blue = new Color(0, 0, 255);
    private byte red, green, blue;

    public Color(byte r, byte g, byte b) {
        red = r;
        green = g;
        blue = b;
    }
}

but then there is nothing to keep a client of Color from mucking with it, perhaps by swapping the Black and White values. Needless to say, this would cause consternation for other clients of the Color class. The "readonly" feature addresses this scenario. By simply introducing the readonly keyword in the declarations, we preserve the flexible initialization while preventing client code from mucking around.

public class Color
{
    public static readonly Color Black = new Color(0, 0, 0);
    public static readonly Color White = new Color(255, 255, 255);
    public static readonly Color Red = new Color(255, 0, 0);
    public static readonly Color Green = new Color(0, 255, 0);
    public static readonly Color Blue = new Color(0, 0, 255);
    private byte red, green, blue;

    public Color(byte r, byte g, byte b) {
        red = r;
        green = g;
        blue = b;
    }
}

It is interesting to note that const members are always static, whereas a readonly member can be either static or not, just like a regular field.

It is possible to use a single keyword for these two purposes, but this leads to either versioning problems or performance problems. Assume for a moment that we used a single keyword for this (const) and a developer wrote:

public class A
{
    public static const C = 0;
}

and a different developer wrote code that relied on A:

public class B
{
    static void Main() {
        Console.WriteLine(A.C);
    }
}

Now, can the code that is generated rely on the fact that A.C is a compile-time constant? I.e., can the use of A.C simply be replaced by the value 0? If you say "yes" to this, then that means that the developer of A cannot change the way that A.C is initialized -- this ties the hands of the developer of A without permission. If you say "no" to this question then an important optimization is missed. Perhaps the author of A is positive that A.C will always be zero. The use of both const and readonly allows the developer of A to specify the intent. This makes for better versioning behavior and also better performance.

Launching Google Maps Directions via an intent on Android

Try this one updated intent google map address location find out

 Uri gmmIntentUri1 = Uri.parse("geo:0,0?q=" + Uri.encode(address));
    Intent mapIntent1 = new Intent(Intent.ACTION_VIEW, gmmIntentUri1);
    mapIntent1.setPackage("com.google.android.apps.maps");
    startActivity(mapIntent1);

Add a link to an image in a css style sheet

You could do something like

<a href="http://home.com"><img src="images/logo.png" alt="" id="logo"></a>

in HTML

What are the best PHP input sanitizing functions?

This is 1 of the way I am currently practicing,

  1. Implant csrf, and salt tempt token along with the request to be made by user, and validate them all together from the request. Refer Here
  2. ensure not too much relying on the client side cookies and make sure to practice using server side sessions
  3. when any parsing data, ensure to accept only the data type and transfer method (such as POST and GET)
  4. Make sure to use SSL for ur webApp/App
  5. Make sure to also generate time base session request to restrict spam request intentionally.
  6. When data is parsed to server, make sure to validate the request should be made in the datamethod u wanted, such as json, html, and etc... and then proceed
  7. escape all illegal attributes from the input using escape type... such as realescapestring.
  8. after that verify onlyclean format of data type u want from user.
    Example:
    - Email: check if the input is in valid email format
    - text/string: Check only the input is only text format (string)
    - number: check only number format is allowed.
    - etc. Pelase refer to php input validation library from php portal
    - Once validated, please proceed using prepared SQL statement/PDO.
    - Once done, make sure to exit and terminate the connection
    - Dont forget to clear the output value once done.

Thats all I believe is sufficient enough for basic sec. It should prevent all major attack from hacker.

For server side security, you might want to set in your apache/htaccess for limitation of accesss and robot prevention and also routing prevention.. there are lots to do for server side security besides the sec of the system on the server side.

You can learn and get a copy of the sec from the htaccess apache sec level (common rpactices)

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

How to get a list of programs running with nohup

When I started with $ nohup storm dev-zookeper ,

METHOD1 : using jobs,

prayagupd@prayagupd:/home/vmfest# jobs -l
[1]+ 11129 Running                 nohup ~/bin/storm/bin/storm dev-zookeeper &

METHOD2 : using ps command.

$ ps xw
PID  TTY      STAT   TIME COMMAND
1031 tty1     Ss+    0:00 /sbin/getty -8 38400 tty1
10582 ?        S      0:01 [kworker/0:0]
10826 ?        Sl     0:18 java -server -Dstorm.options= -Dstorm.home=/root/bin/storm -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dsto
10853 ?        Ss     0:00 sshd: vmfest [priv] 

TTY column with ? => nohup running programs.

Description

  • TTY column = the terminal associated with the process
  • STAT column = state of a process
    • S = interruptible sleep (waiting for an event to complete)
    • l = is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)

Reference

$ man ps # then search /PROCESS STATE CODES

Hunk #1 FAILED at 1. What's that mean?

Follow the instructions here, it solved my problem.

you have to run the command like as follow; patch -p0 --dry-run < path/to/your/patchFile/yourPatch.patch

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

Java, reading a file from current directory?

None of the above answer works for me. Here is what works for me.

Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:

URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Programmatically generate video or animated GIF in Python?

from PIL import Image
import glob  #use it if you want to read all of the certain file type in the directory
imgs=[]
for i in range(596,691): 
    imgs.append("snap"+str(i)+'.png')
    print("scanned the image identified with",i)  

starting and ending value+1 of the index that identifies different file names

imgs = glob.glob("*.png") #do this if you want to read all files ending with .png

my files were: snap596.png, snap597.png ...... snap690.png

frames = []
for i in imgs:
    new_frame = Image.open(i)
    frames.append(new_frame)

Save into a GIF file that loops forever

frames[0].save('fire3_PIL.gif', format='GIF',
    append_images=frames[1:],
    save_all=True,
    duration=300, loop=0)

I found flickering issue with imageio and this method fixed it.

Asynchronous Function Call in PHP

Nowadays, it's better to use queues than threads (for those who don't use Laravel there are tons of other implementations out there like this).

The basic idea is, your original PHP script puts tasks or jobs into a queue. Then you have queue job workers running elsewhere, taking jobs out of the queue and starts processing them independently of the original PHP.

The advantages are:

  1. Scalability - you can just add worker nodes to keep up with demand. In this way, tasks are run in parallel.
  2. Reliability - modern queue managers such as RabbitMQ, ZeroMQ, Redis, etc, are made to be extremely reliable.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

If you are using XAMPP rather than WAMP, the path you go to is:

C:\xampp\phpMyAdmin\config.inc.php

How to rename JSON key

If anyone needs to do this dynamically:

const keys = Object.keys(jsonObject);

keys.forEach((key) => {

      // CREATE A NEW KEY HERE
      var newKey = key.replace(' ', '_');

      jsonObject[newKey] = jsonObject[key];
      delete jsonObject[key];
   });

jsonObject will now have the new keys.

IMPORTANT:

If your key is not changed by the replace function, it will just take it out of the array. You may want to put some if statements in there.

What GRANT USAGE ON SCHEMA exactly do?

GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

The rights tests are done in order:

Do you have `USAGE` on the schema? 
    No:  Reject access. 
    Yes: Do you also have the appropriate rights on the table? 
        No:  Reject access. 
        Yes: Check column privileges.

Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

The phrase:

(assuming that the objects' own privilege requirements are also met)

Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

You need to set both permissions for people to actually be able to view the file.

Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

jQuery equivalent to Prototype array.last()

If u use the prototype on arrays like:

Array.prototype.last = function() {return this[this.length-1];}

using forloops will do this.

var a = [0,1,2];
out --> 0
out --> 1
out --> 2
out --> last

How to make inactive content inside a div?

Without using an overlay, you can use pointer-events: none on the div in CSS, but this does not work in IE or Opera.

div.disabled
{
  pointer-events: none;

  /* for "disabled" effect */
  opacity: 0.5;
  background: #CCC;
}

Reference

How to overwrite the output directory in spark

since df.save(path, source, mode) is deprecated, (http://spark.apache.org/docs/1.5.0/api/scala/index.html#org.apache.spark.sql.DataFrame)

use df.write.format(source).mode("overwrite").save(path)
where df.write is DataFrameWriter

'source' can be ("com.databricks.spark.avro" | "parquet" | "json")

Insert data using Entity Framework model

I'm using EF6, and I find something strange,

Suppose Customer has constructor with parameter ,

if I use new Customer(id, "name"), and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name") );
    db.SaveChanges();
 }

It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,

But if I add the curly brackets, use new Customer(id, "name"){} and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name"){} );
    db.SaveChanges();
 }

the data will then actually BE Inserted,

seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.

How to filter rows containing a string pattern from a Pandas dataframe

>>> mask = df['ids'].str.contains('ball')    
>>> mask
0     True
1     True
2    False
3     True
Name: ids, dtype: bool

>>> df[mask]
     ids  vals
0  aball     1
1  bball     2
3  fball     4

How do I remove a comma off the end of a string?

This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:

if (substr($string, -1, 1) == ',')
{
  $string = substr($string, 0, -1);
}

If you want to remove all commas from the end of a line use the simpler:

$string = rtrim($string, ',');

The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:

$string = rtrim($string, ", \t\n");

How to add image background to btn-default twitter-bootstrap button?

Instead of using input type button you can use button and insert the image inside the button content.

<button class="btn btn-default">
     <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>

The problem with doing this only with CSS is that you cannot set linear-gradient to the background you must use solid color.

.sign-in-facebook {
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }
  .sign-in-facebook:hover {
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }

_x000D_
_x000D_
body {_x000D_
  padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
  <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
_x000D_
_x000D_

Styling Password Fields in CSS

I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.

@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
  INPUT[type="password"]{
  font-family:Verdana,sans-serif;
  height:28px;
  font-size:19px;
  width:223px;
  padding:5px;
  }
} /* END WEBKIT */

Difference between "process.stdout.write" and "console.log" in node.js?

Another important difference in this context would with process.stdout.clearLine() and process.stdout.cursorTo(0).

This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log() it doesn't work because it also append \n to the text. Just try out this example:

var waitInterval = 500;
var totalTime = 5000;
var currentInterval = 0;

function showPercentage(percentage){
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    console.log(`Processing ${percentage}%...` ); //replace this line with process.stdout.write(`Processing ${percentage}%...`);
}

var interval = setInterval(function(){
 currentInterval += waitInterval;
 showPercentage((currentInterval/totalTime) * 100);
}, waitInterval);

setTimeout(function(){
 clearInterval(interval); 
}, totalTime);

How do you performance test JavaScript code?

You could use this: http://getfirebug.com/js.html. It has a profiler for JavaScript.

Get property value from C# dynamic object by string (reflection?)

Did you see ExpandoObject class?

Directly from MSDN description: "Represents an object whose members can be dynamically added and removed at run time."

With it you can write code like this:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");

Check if table exists and if it doesn't exist, create it in SQL Server 2008

If I am not wrong, this should work:

    if not exists (Select 1 from tableName)
create table ...

Converting to upper and lower case in Java

WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.

Using Spring 3 autowire in a standalone Java application

I case you are running SpringBoot:

I just had the same problem, that I could not Autowire one of my services from the static main method.

See below an approach in case you are relying on SpringApplication.run:

@SpringBootApplication
public class PricingOnlineApplication {

    @Autowired
    OrchestratorService orchestratorService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
        PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);

        application.start();
    }

    private void start() {
        orchestratorService.performPricingRequest(null);
    }

}

I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)

How to display the current time and date in C#

For time:

label1.Text = DateTime.Now.ToString("HH:mm:ss"); //result 22:11:45

or

label1.Text = DateTime.Now.ToString("hh:mm:ss tt"); //result 11:11:45 PM

For date:

label1.Text = DateTime.Now.ToShortDateString(); //30.5.2012

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with

$my_url = urlencode("my url");

and then calling

file_get_contents($my_url);

and see if you have better luck.

jQuery move to anchor location on page load

Put this right before the closing Body tag at the bottom of the page.

<script>
    if (location.hash) {
        location.href = location.hash;
    }
</script>

jQuery is actually not required.

Accessing MVC's model property from Javascript

try this: (you missed the single quotes)

var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';

How to get current route

for new router >= RC.3

Best and a simple way to do this is!

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  // to print only path eg:"/login"
}

How do I check whether input string contains any spaces?

string name = "Paul Creasey";
if (name.contains(" ")) {

}

How to use the switch statement in R functions?

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
  if (is.na(val)) {
    val <- "NULL"
    break
  }
  if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
    val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
    break
  }
  if (inherits(val, "Date")) {
    val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
    break
  }
  if (is.numeric(val)) break
  val <- paste0("'", gsub("'", "''", val), "'")
  break
}

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

I had similar issues with Eclipse Kepler v3.8 I had tomcat v8.5.37 installed. I couldn't see Apache v8.5 as an option. By skimming through StackOverflow I found Apache v9.0 is available on Eclipse Neon. Cool thing is you don't have to change your eclipse version. In your current Eclipse. Download WTP(Web Tools Package) by following the steps:

Step 1: Help >>> Install New Software. Copy this link in the Work with: http://download.eclipse.org/webtools/repository/neon

Step 2: Select JST Server Adapters and JST Server Adapters Extensions from the first package you see. Install those.

Step 3: Windows >>> Preferences >>> Server >>> Runtime Environments >>> Add..

You'll see Apache v9.0 there! It works!

Python - Using regex to find multiple matches and print them out

Instead of using re.search use re.findall it will return you all matches in a List. Or you could also use re.finditer (which i like most to use) it will return an Iterator Object and you can just use it to iterate over all found matches.

line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
    print match.group(1)

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

Calculating a directory's size using Python?

A little late to the party but in one line provided that you have glob2 and humanize installed. Note that in Python 3, the default iglob has a recursive mode. How to modify the code for Python 3 is left as a trivial exercise for the reader.

>>> import os
>>> from humanize import naturalsize
>>> from glob2 import iglob
>>> naturalsize(sum(os.path.getsize(x) for x in iglob('/var/**'))))
'546.2 MB'

How to clear/delete the contents of a Tkinter Text widget?

A lot of answers ask you to use END, but if that's not working for you, try:

text.delete("1.0", "end-1c")

String to LocalDate

DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

How to go from Blob to ArrayBuffer

Just to complement Mr @potatosalad answer.

You don't actually need to access the function scope to get the result on the onload callback, you can freely do the following on the event parameter:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Why this is better? Because then we may use arrow function without losing the context

var fileReader = new FileReader();
fileReader.onload = (event) => {
    this.externalScopeVariable = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Palindrome check in Javascript

The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.

Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.

isPalindrome():

Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.

for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.

Here's the code:

/**
 * TODO: If func counts out, let it return 0
 *  * Assume !isPalindrome (invert logic)
 */
function isPalindrome(S){
    var s = S
      , len = s.length
      , mid = len/2;
      , i = 0, j = len-1;

    while(i<mid){
        var l = s.charAt(i);
        while(j>=mid){
            var r = s.charAt(j);
            if(l === r){
                console.log('@while *', i, l, '...', j, r);
                --j;
                break;
            }
            console.log('@while !', i, l, '...', j, r);
            return 0;
        }
        ++i;
    }
    return 1;
}

var nooe = solution('neveroddoreven');  // even char length
var kayak = solution('kayak');  // odd char length
var kayaks = solution('kayaks');

console.log('@isPalindrome', nooe, kayak, kayaks);

Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.

How to compare files from two different branches?

The best way to do it is by using git diff in the following way: git diff <source_branch> <target_branch> -- file_path

It will check the difference between files in those branches. Take a look at this article for more information about git commands and how they work.

Iterate over object keys in node.js

I'm new to node.js (about 2 weeks), but I've just created a module that recursively reports to the console the contents of an object. It will list all or search for a specific item and then drill down by a given depth if need be.

Perhaps you can customize this to fit your needs. Keep It Simple! Why complicate?...

'use strict';

//console.log("START: AFutils");

// Recusive console output report of an Object
// Use this as AFutils.reportObject(req, "", 1, 3); // To list all items in req object by 3 levels
// Use this as AFutils.reportObject(req, "headers", 1, 10); // To find "headers" item and then list by 10 levels
// yes, I'm OLD School!  I like to see the scope start AND end!!!  :-P
exports.reportObject = function(obj, key, level, deep) 
{
    if (!obj)
    { 
        return;
    }

    var nextLevel = level + 1;

    var keys, typer, prop;
    if(key != "")
    {   // requested field
        keys = key.split(']').join('').split('[');
    }
    else
    {   // do for all
        keys = Object.keys(obj);
    }
    var len = keys.length;
    var add = "";
    for(var j = 1; j < level; j++)
    {
        // I would normally do {add = add.substr(0, level)} of a precreated multi-tab [add] string here, but Sublime keeps replacing with spaces, even with the ["translate_tabs_to_spaces": false] setting!!! (angry)
        add += "\t";
    }

    for (var i = 0; i < len; i++) 
    {
        prop = obj[keys[i]];
        if(!prop)
        {
            // Don't show / waste of space in console window...
            //console.log(add + level + ": UNDEFINED [" + keys[i] + "]");
        }
        else
        {
            typer = typeof(prop);
            if(typer == "function")
            {
                // Don't bother showing fundtion code...
                console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
            }
            else
            if(typer == "object")
            {
                console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
                if(nextLevel <= deep)
                {
                    // drop the key search mechanism if first level item has been found...
                    this.reportObject(prop, "", nextLevel, deep); // Recurse into
                }
            }
            else
            {
                // Basic report
                console.log(add + level + ": [" + keys[i] + "] = {" + typer + "} = " + prop + ".");
            }
        }
    }
    return ;
};

//console.log("END: AFutils");

How to autoplay HTML5 mp4 video on Android?

In Android 4.4 and above you can remove the need for a user gesture so long as the HTML5 Video component lives in your own WebView

webview.setWebChromeClient(new WebChromeClient());
webview.getSettings().setMediaPlaybackRequiresUserGesture(false);

To get the video to autoplay, you'd still need to add autoplay to the video element:

<video id='video' controls autoplay>
  <source src='http://192.xxx.xxx.xx/XXXXVM01.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
</video>

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

Managing jQuery plugin dependency in webpack

I got things working nicely while exposing $ and jQuery as global variables with Webpack 3.8.1 and the following.

Install jQuery as a project dependency. You can omit @3.2.1 to install the latest version or specify another version.

npm install --save [email protected]

Install expose-loader as a development dependency if not installed already.

npm install expose-loader --save-dev

Configure Webpack to load and expose jQuery for us.

// webpack.config.js
const webpack = require('webpack')

module.exports = {
  entry: [
    // entry bits
  ],
  output: {
    // output bits
  },
  module: {
    rules: [
      // any other rules
      {
        // Exposes jQuery for use outside Webpack build
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: 'jQuery'
        },{
          loader: 'expose-loader',
          options: '$'
        }]
      }
    ]
  },
  plugins: [
    // Provides jQuery for other JS bundled with Webpack
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ]
}

How to convert Windows end of line in Unix end of line (CR/LF to LF)

There should be a program called dos2unix that will fix line endings for you. If it's not already on your Linux box, it should be available via the package manager.

Reading file using fscanf() in C

First of all, you're testing fp twice. so printf("Error Reading File\n"); never gets executed.

Then, the output of fscanf should be equal to 2 since you're reading two values.

Can I install Python 3.x and 2.x on the same Windows computer?

I'm using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:

:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*

Name them pythonX.Y.bat and put them somewhere in your PATH. Copy the file for the preferred minor version (i.e. the latest) to pythonX.bat. (E.g. copy python2.6.bat python2.bat.) Then you can use python2 file.py from anywhere.

However, this doesn't help or even affect the Windows file association situation. For that you'll need a launcher program that reads the #! line, and then associate that with .py and .pyw files.

The input is not a valid Base-64 string as it contains a non-base 64 character

As Alex Filipovici mentioned the issue was a wrong encoding. The file I read in was UTF-8-BOM and threw the above error on Convert.FromBase64String(). Changing to UTF-8 did work without problems.

How do I get a python program to do nothing?

You can use continue

if condition:
    continue
else:
    #do something

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

compile function -

  1. is called before the controller and link function.
  2. In compile function, you have the original template DOM so you can make changes on original DOM before AngularJS creates an instance of it and before a scope is created
  3. ng-repeat is perfect example - original syntax is template element, the repeated elements in HTML are instances
  4. There can be multiple element instances and only one template element
  5. Scope is not available yet
  6. Compile function can return function and object
  7. returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.
  8. returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

syntax

function compile(tElement, tAttrs, transclude) { ... }

controller

  1. called after the compile function
  2. scope is available here
  3. can be accessed by other directives (see require attribute)

pre - link

  1. The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

  2. You can update the dom in the controller using angular.element but this is not recommended as the element is provided in the link function

  3. Pre-link function is used to implement logic that runs when angular js has already compiled the child elements but before any of the child element's post link have been called

post-link

  1. directive that only has link function, angular treats the function as a post link

  2. post will be executed after compile, controller and pre-link funciton, so that's why this is considered the safest and default place to add your directive logic

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

Multi-dimensional associative arrays in JavaScript

    var myObj = [];
    myObj['Base'] = [];
    myObj['Base']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',  AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
    myObj['Base']['Base.panel.panel_top']  = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };

    myObj['SC1'] = [];
    myObj['SC1']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',  AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
    myObj['SC1']['Base.panel.panel_top']  = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };


    console.log(myObj);

    if ('Base' in myObj) {
      console.log('Base found');

      if ('Base.panel.panel_base' in myObj['Base'])  {
        console.log('Base.panel.panel_base found'); 


      console.log('old value: ' + myObj['Base']['Base.panel.panel_base'].Context);  
      myObj['Base']['Base.panel.panel_base'] = 'new Value';
      console.log('new value: ' + myObj['Base']['Base.panel.panel_base']);
      }
    }

Output:

  • Base found
  • Base.panel.panel_base found
  • old value: Base
  • new value: new Value

The array operation works. There is no problem.

Iteration:

     Object.keys(myObj['Base']).forEach(function(key, index) {            
        var value = objcons['Base'][key];                   
      }, myObj);

Checking if a list is empty with LINQ

List<T> li = new List<T>();
(li.First().DefaultValue.HasValue) ? string.Format("{0:yyyy/MM/dd}", sender.First().DefaultValue.Value) : string.Empty;

How to export iTerm2 Profiles

I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2.

See https://apple.stackexchange.com/a/111559

prevent refresh of page when button inside form clicked

<form method="POST">
    <button name="data" onclick="getData()">Click</button>
</form>

instead of using button tag, use input tag. Like this,

<form method="POST">
    <input type = "button" name="data" onclick="getData()" value="Click">
</form>

add a string prefix to each value in a string column using Pandas

df['col'] = 'str' + df['col'].astype(str)

Example:

>>> df = pd.DataFrame({'col':['a',0]})
>>> df
  col
0   a
1   0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
    col
0  stra
1  str0

Returning http status code from Web Api controller

If you need to return an IHttpActionResult and want to return the error code plus a message, use:

return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, "Error message here"));

Console output in a Qt GUI app?

Oh you can Output a message when using QT += gui and CONFIG += console.

You need printf("foo bar") but cout << "foo bar" doesn't works

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

Using an integer as a key in an associative array in JavaScript

You can just use an object:

var test = {}
test[2300] = 'Some string';

How to rename a file using Python

Use os.rename. But you have to pass full path of both files to the function. If I have a file a.txt on my desktop so I will do and also I have to give full of renamed file too.

os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')

Prevent wrapping of span or div

It works with just this:

.slideContainer {
    white-space: nowrap;
}
.slide { 
    display: inline-block;
    width: 600px;
    white-space: normal;
}

I did originally have float : left; and that prevented it from working correctly.

Thanks for posting this solution.

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

Purpose of Unions in C and C++

In C it was a nice way to implement something like an variant.

enum possibleTypes{
  eInt,
  eDouble,
  eChar
}


struct Value{

    union Value {
      int iVal_;
      double dval;
      char cVal;
    } value_;
    possibleTypes discriminator_;
} 

switch(val.discriminator_)
{
  case eInt: val.value_.iVal_; break;

In times of litlle memory this structure is using less memory than a struct that has all the member.

By the way C provides

    typedef struct {
      unsigned int mantissa_low:32;      //mantissa
      unsigned int mantissa_high:20;
      unsigned int exponent:11;         //exponent
      unsigned int sign:1;
    } realVal;

to access bit values.

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

if you are using dynamic ip just grant access to 192.168.2.% so now you dont have to worry about granting access to your ip address every time.

Could not load file or assembly Exception from HRESULT: 0x80131040

Check if the project having HRESULT: 0x80131040 error is being used/referenced by any project. If yes, kindly check if these project have similar .dll being referenced and the version is the same. If they're are not of same version number, then it is causing the said error.

ASP.NET Background image

If you want to set image as background for whole page, use this:

body
{
    background-image: url('Image URL');
}

How to get the first day of the current week and month?

You can use the java.time package (since Java8 and late) to get start/end of day/week/month.
The util class example below:

import org.junit.Test;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public class DateUtil {
    private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");

    public static LocalDateTime startOfDay() {
        return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
    }

    public static LocalDateTime endOfDay() {
        return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
    }

    public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
    }

    //note that week starts with Monday
    public static LocalDateTime startOfWeek() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MIN)
                .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    }

    //note that week ends with Sunday
    public static LocalDateTime endOfWeek() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MAX)
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
    }

    public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
    }

    public static LocalDateTime startOfMonth() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MIN)
                .with(TemporalAdjusters.firstDayOfMonth());
    }

    public static LocalDateTime endOfMonth() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MAX)
                .with(TemporalAdjusters.lastDayOfMonth());
    }

    public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
    }

    public static long toMills(final LocalDateTime localDateTime) {
        return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
    }

    public static Date toDate(final LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
    }

    public static String toString(final LocalDateTime localDateTime) {
        return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
    }

    @Test
    public void test() {
        //day
        final LocalDateTime now = LocalDateTime.now();
        System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
        System.out.println("Start of day: " + toString(startOfDay()));
        System.out.println("End of day: " + toString(endOfDay()));
        System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
        final LocalDateTime yesterday = now.minusDays(1);
        System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
        final LocalDateTime tomorrow = now.plusDays(1);
        System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
        //week
        System.out.println("Start of week: " + toString(startOfWeek()));
        System.out.println("End of week: " + toString(endOfWeek()));
        System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
        final LocalDateTime previousWeek = now.minusWeeks(1);
        System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
        final LocalDateTime nextWeek = now.plusWeeks(1);
        System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
        //month
        System.out.println("Start of month: " + toString(startOfMonth()));
        System.out.println("End of month: " + toString(endOfMonth()));
        System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
        final LocalDateTime previousMonth = now.minusMonths(1);
        System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
        final LocalDateTime nextMonth = now.plusMonths(1);
        System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
    }
}

Test output:

Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false

Apache won't start in wamp

It turns out I didn't have Microsoft visual c++ installed, installing it solved the problem for me.

Select data from "show tables" MySQL query

You can't put SHOW statements inside a subquery like in your example. The only statement that can go in a subquery is SELECT.

As other answers have stated, you can query the INFORMATION_SCHEMA directly with SELECT and get a lot more flexibility that way.

MySQL's SHOW statements are internally just queries against the INFORMATION_SCHEMA tables.

User @physicalattraction has posted this comment on most other answers:

This gives you (meta)information about the tables, not the contents of the table, as the OP intended. – physicalattraction

On the contrary, the OP's question does not say that they want to select the data in all the tables. They say they want to select from the result of SHOW TABLES, which is just a list of table names.

If the OP does want to select all data from all tables, then the answer is no, you can't do it with one query. Each query must name its tables explicitly. You can't make a table name be a variable or the result of another part of the same query. Also, all rows of a given query result must have the same columns.

So the only way to select all data from all tables would be to run SHOW TABLES and then for each table named in that result, run another query.

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

How can I get CMake to find my alternative Boost installation?

I ran into a similar problem on a Linux server, where two versions of Boost have been installed. One is the precompiled 1.53.0 version which counts as old in 2018; it's in /usr/include and /usr/lib64. The version I want to use is 1.67.0, as a minimum version of 1.65.1 is required for another C++ library I'm installing; it's in /opt/boost, which has include and lib subdirectories. As suggested in previous answers, I set variables in CMakeLists.txt to specify where to look for Boost 1.67.0 as follows

include_directories(/opt/boost/include/)
include_directories(/opt/boost/lib/)
set(BOOST_ROOT /opt/boost/)
set(BOOST_INCLUDEDIR /opt/boost/include/)
set(BOOST_LIBRARYDIR /opt/boost/lib)
set(Boost_NO_SYSTEM_PATHS TRUE)
set(Boost_NO_BOOST_CMAKE TRUE)

But CMake doesn't honor those changes. Then I found an article online: CMake can use a local Boost, and realized that I need to change the variables in CMakeCache.txt. There I found that the Boost-related variables are still pointing to the default Boost 1.53.0, so no wonder CMake doesn't honor my changes in CMakeLists.txt. Then I set the Boost-related variables in CMakeCache.txt

Boost_DIR:PATH=Boost_DIR-NOTFOUND
Boost_INCLUDE_DIR:PATH=/opt/boost/include/
Boost_LIBRARY_DIR_DEBUG:PATH=/opt/boost/lib
Boost_LIBRARY_DIR_RELEASE:PATH=/opt/boost/lib

I also changed the variables pointing to the non-header, compiled parts of the Boost library to point to the version I want. Then CMake successfully built the library that depends on a recent version of Boost.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

For me, I accidentally included my local database name inside the SQL query, hence the access denied issue came up when I deployed.

I removed the database name from the SQL query and it got fixed.

jQuery vs document.querySelectorAll

In terms of code maintainability, there are several reasons to stick with a widely used library.

One of the main ones is that they are well documented, and have communities such as ... say ... stackexchange, where help with the libraries can be found. With a custom coded library, you have the source code, and maybe a how-to document, unless the coder(s) spent more time documenting the code than writing it, which is vanishingly rare.

Writing your own library might work for you , but the intern sitting at the next desk may have an easier time getting up to speed with something like jQuery.

Call it network effect if you like. This isn't to say that the code will be superior in jQuery; just that the concise nature of the code makes it easier to grasp the overall structure for programmers of all skill levels, if only because there's more functional code visible at once in the file you are viewing. In this sense, 5 lines of code is better than 10.

To sum up, I see the main benefits of jQuery as being concise code, and ubiquity.

Find empty or NaN entry in Pandas Dataframe

Partial solution: for a single string column tmp = df['A1'].fillna(''); isEmpty = tmp=='' gives boolean Series of True where there are empty strings or NaN values.

What is the use of verbose in Keras while validating the model?

By default verbose = 1,

verbose = 1, which includes both progress bar and one line per epoch

verbose = 0, means silent

verbose = 2, one line per epoch i.e. epoch no./total no. of epochs

How to create timer events using C++ 11?

If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.

template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
    CloseThreadpoolTimer(timer);
    std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
    (*callable)();
}

template <typename T>
void call_after(T callable, long long delayInMs)
{
    auto state = std::make_unique<T>(std::move(callable));
    auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
    if (!timer)
    {
        throw std::runtime_error("Timer");
    }

    ULARGE_INTEGER due;
    due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));

    FILETIME ft;
    ft.dwHighDateTime = due.HighPart;
    ft.dwLowDateTime = due.LowPart;

    SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
    state.release();
}

int main()
{
    auto callback = []
    {
        std::cout << "in callback\n";
    };

    call_after(callback, 1000);
    std::cin.get();
}

How to remove all options from a dropdown using jQuery / JavaScript

Other approach for Vanilla JavaScript:

for(var o of document.querySelectorAll('#models > option')) {
  o.remove()
}

PHP substring extraction. Get the string before the first '/' or the whole string

why not use:

function getwhatiwant($s)
{
    $delimiter='/';
    $x=strstr($s,$delimiter,true);
    return ($x?$x:$s);
}

OR:

   function getwhatiwant($s)
   {
       $delimiter='/';
       $t=explode($delimiter, $s);
       return ($t[1]?$t[0]:$s);
   }

Difference between two dates in years, months, days in JavaScript

Time span in full Days, Hours, Minutes, Seconds, Milliseconds:

// Extension for Date
Date.difference = function (dateFrom, dateTo) {
  var diff = { TotalMs: dateTo - dateFrom };
  diff.Days = Math.floor(diff.TotalMs / 86400000);

  var remHrs = diff.TotalMs % 86400000;
  var remMin = remHrs % 3600000;
  var remS   = remMin % 60000;

  diff.Hours        = Math.floor(remHrs / 3600000);
  diff.Minutes      = Math.floor(remMin / 60000);
  diff.Seconds      = Math.floor(remS   / 1000);
  diff.Milliseconds = Math.floor(remS % 1000);
  return diff;
};

// Usage
var a = new Date(2014, 05, 12, 00, 5, 45, 30); //a: Thu Jun 12 2014 00:05:45 GMT+0400 
var b = new Date(2014, 02, 12, 00, 0, 25, 0);  //b: Wed Mar 12 2014 00:00:25 GMT+0400
var diff = Date.difference(b, a);
/* diff: {
  Days: 92
  Hours: 0
  Minutes: 5
  Seconds: 20
  Milliseconds: 30
  TotalMs: 7949120030
} */

Error You must specify a region when running command aws ecs list-container-instances

#1- Run this to configure the region once and for all:

aws configure set region us-east-1 --profile admin
  • Change admin next to the profile if it's different.

  • Change us-east-1 if your region is different.

#2- Run your command again:

aws ecs list-container-instances --cluster default

"Android library projects cannot be launched"?

From Android's Developer Documentation on Managing Projects from Eclipse with ADT:

Setting up a Library Project

Next, set the project's Properties to indicate that it is a library project:

  1. In the Package Explorer, right-click the library project and select Properties.
  2. In the Properties window, select the "Android" properties group at left and locate the Library properties at right.
  3. Select the "is Library" checkbox and click Apply.
  4. Click OK to close the Properties window.

So, open your project properties, un-select the "Is Library" checkbox, and click Apply to make your project a normal Android project (not a library project).

How can I enable CORS on Django REST Framework

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3030',
]

more details: https://github.com/ottoyiu/django-cors-headers/#configuration

read the official documentation can resolve almost all problem

Why "no projects found to import"?

This answer is same as Laura's answer , however, in new eclipse versions you will not be able to see a "create project from existing source" option.

Hence you can do this instead:

  • Goto File > New > Project

  • Select the type of project, click Next

  • Uncheck Use default location

  • Click on Browse to navigate to your source folder, or type in the path to your source

  • Click Finish

Taken from this discussion forum in eclipse.org

Is it possible to refresh a single UITableViewCell in a UITableView?

Once you have the indexPath of your cell, you can do something like:

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates]; 

In Xcode 4.6 and higher:

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates]; 

You can set whatever your like as animation effect, of course.

Beamer: How to show images as step-by-step images

This is a sample code I used to counter the problem.

\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}

How would one write object-oriented code in C?

Yes, you can. People were writing object-oriented C before C++ or Objective-C came on the scene. Both C++ and Objective-C were, in parts, attempts to take some of the OO concepts used in C and formalize them as part of the language.

Here's a really simple program that shows how you can make something that looks-like/is a method call (there are better ways to do this. This is just proof the language supports the concepts):

#include<stdio.h>

struct foobarbaz{
    int one;
    int two;
    int three;
    int (*exampleMethod)(int, int);
};

int addTwoNumbers(int a, int b){
    return a+b;
}

int main()
{
    // Define the function pointer
    int (*pointerToFunction)(int, int) = addTwoNumbers;

    // Let's make sure we can call the pointer
    int test = (*pointerToFunction)(12,12);
    printf ("test: %u \n",  test);

    // Now, define an instance of our struct
    // and add some default values.
    struct foobarbaz fbb;
    fbb.one   = 1;
    fbb.two   = 2;
    fbb.three = 3;

    // Now add a "method"
    fbb.exampleMethod = addTwoNumbers;

    // Try calling the method
    int test2 = fbb.exampleMethod(13,36);
    printf ("test2: %u \n",  test2);

    printf("\nDone\n");
    return 0;
}

Combine two data frames by rows (rbind) when they have different sets of columns

An alternative with data.table:

library(data.table)
df1 = data.frame(a = c(1:5), b = c(6:10))
df2 = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
rbindlist(list(df1, df2), fill = TRUE)

rbind will also work in data.table as long as the objects are converted to data.table objects, so

rbind(setDT(df1), setDT(df2), fill=TRUE)

will also work in this situation. This can be preferable when you have a couple of data.tables and don't want to construct a list.

How to animate button in android?


Class.Java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_with_the_button);

    final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.milkshake);
    Button myButton = (Button) findViewById(R.id.new_game_btn);
    myButton.setAnimation(myAnim);
}

For onClick of the Button

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        v.startAnimation(myAnim);
    }
});

Create the anim folder in res directory

Right click on, res -> New -> Directory

Name the new Directory anim

create a new xml file name it milkshake


milkshake.xml

<?xml version="1.0" encoding="utf-8"?>
    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="100"
        android:fromDegrees="-5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="10"
        android:repeatMode="reverse"
        android:toDegrees="5" />

Using Pairs or 2-tuples in Java

Android Tuple Utils

This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.

How do I use tools:overrideLibrary in a build.gradle file?

Use overrideLibrary when the minSdk is declared in build.gradle instead of in AndroidManifest.xml

If you are using Android Studio:

add <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/> to your manifest, don't forget to include xmlns:tools="http://schemas.android.com/tools" too.

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

Using --disable-web-security switch is quite dangerous! Why disable security at all while you can just allow XMLHttpRequest to access files from other files using --allow-file-access-from-files switch?

Before using these commands be sure to end all running instances of Chrome.

On Windows:

chrome.exe --allow-file-access-from-files

On Mac:

open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files

Discussions of this "feature" of Chrome:

Why doesn't CSS ellipsis work in table cell?

Try using max-width instead of width, the table will still calculate the width automatically.

Works even in ie11 (with ie8 compatibility mode).

_x000D_
_x000D_
td.max-width-50 {_x000D_
  border: 1px solid black;_x000D_
  max-width: 50px;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="max-width-50">Hello Stack Overflow</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hello Stack Overflow</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hello Stack Overflow</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

jsfiddle.

nil detection in Go

I have created some sample code which creates new variables using a variety of ways that I can think of. It looks like the first 3 ways create values, and the last two create references.

package main

import "fmt"

type Config struct {
    host string
    port float64
}

func main() {
    //value
    var c1 Config
    c2 := Config{}
    c3 := *new(Config)

    //reference
    c4 := &Config{}
    c5 := new(Config)

    fmt.Println(&c1 == nil)
    fmt.Println(&c2 == nil)
    fmt.Println(&c3 == nil)
    fmt.Println(c4 == nil)
    fmt.Println(c5 == nil)

    fmt.Println(c1, c2, c3, c4, c5)
}

which outputs:

false
false
false
false
false
{ 0} { 0} { 0} &{ 0} &{ 0}

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The error you're seeing means the data you receive from the remote end isn't valid JSON. JSON (according to the specifiation) is normally UTF-8, but can also be UTF-16 or UTF-32 (in either big- or little-endian.) The exact error you're seeing means some part of the data was not valid UTF-8 (and also wasn't UTF-16 or UTF-32, as those would produce different errors.)

Perhaps you should examine the actual response you receive from the remote end, instead of blindly passing the data to json.loads(). Right now, you're reading all the data from the response into a string and assuming it's JSON. Instead, check the content type of the response. Make sure the webpage is actually claiming to give you JSON and not, for example, an error message that isn't JSON.

(Also, after checking the response use json.load() by passing it the file-like object returned by opener.open(), instead of reading all data into a string and passing that to json.loads().)

Custom exception type

See this example in the MDN.

If you need to define multiple Errors (test the code here!):

function createErrorType(name, initFunction) {
    function E(message) {
        this.message = message;
        if (Error.captureStackTrace)
            Error.captureStackTrace(this, this.constructor);
        else
            this.stack = (new Error()).stack;
        initFunction && initFunction.apply(this, arguments);
    }
    E.prototype = Object.create(Error.prototype);
    E.prototype.name = name;
    E.prototype.constructor = E;
    return E;
}
var InvalidStateError = createErrorType(
    'InvalidStateError',
    function (invalidState, acceptedStates) {
        this.message = 'The state ' + invalidState + ' is invalid. Expected ' + acceptedStates + '.';
    });

var error = new InvalidStateError('foo', 'bar or baz');
function assert(condition) { if (!condition) throw new Error(); }
assert(error.message);
assert(error instanceof InvalidStateError);  
assert(error instanceof Error); 
assert(error.name == 'InvalidStateError');
assert(error.stack);
error.message;

Code is mostly copied from: What's a good way to extend Error in JavaScript?

What is the difference between res.end() and res.send()?

In addition to the excellent answers, I would like to emphasize here when to use res.end() and when to use res.send() this was why I originally landed here and I didn't found a solution.

The answer is really simple

res.end() is used to quickly end the response without sending any data.

An example for this would be starting a process on a server

app.get(/start-service, (req, res) => {
   // Some logic here
   exec('./application'); // dummy code
   res.end();
});

If you would like to send data in your response then you should use res.send() instead

app.get(/start-service, (req, res) => {
   res.send('{"age":22}');
});

Here you can read more

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

Check if your remote branch is available to pull. I had the same issue, finally realized the remote branch was deleted by someone.

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

I was getting the same error even after doing above changes and what i did is

Right click on the project->properties->java compiler->Compiler compliance level->changes it to 1.6

This change is particular for the project. This should hopefully work.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

Generating a WSDL from an XSD file

we can generate wsdl file from xsd but you have to use oracle enterprise pack of eclipse(OEPE). simply create xsd and then right click->new->wsdl...

How do I compare two columns for equality in SQL Server?

I'd go with the CASE WHEN also.

Depending on what you actually want to do, there may be other options though, like using an outer join or whatever, but that doesn't seem to be what you need in this case.

How do I POST XML data with curl

-H "text/xml" isn't a valid header. You need to provide the full header:

-H "Content-Type: text/xml" 

jQuery Datepicker onchange event issue

You can use the datepicker's onSelect event.

$(".date").datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    }
});

Live example:

_x000D_
_x000D_
$(".date")_x000D_
.datepicker({_x000D_
    onSelect: function(dateText) {_x000D_
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
    }_x000D_
})_x000D_
.on("change", function() {_x000D_
    console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
_x000D_
_x000D_

Unfortunately, onSelect fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires onSelect (even if nothing changed), and doesn't fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual change event, or possibly a datepicker-specific one).


If you like, of course, you can make the change event on the input fire:

$(".date").datepicker({
    onSelect: function() {
        $(this).change();
    }
});

That will fire change on the underlying inputfor any handler hooked up via jQuery. But again, it always fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via data) and compare.

Live example:

_x000D_
_x000D_
$(".date")_x000D_
.datepicker({_x000D_
    onSelect: function(dateText) {_x000D_
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
        $(this).change();_x000D_
    }_x000D_
})_x000D_
.on("change", function() {_x000D_
    console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
_x000D_
_x000D_

How to create a hex dump of file containing only the hex characters without spaces in bash?

Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):

hexdump -ve '1/1 "%.2x"'

1/1 means "each format is applied once and takes one byte", and "%.2x" is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.

How to disable sort in DataGridView?

I was looking for a way to disable my already existing DataGridView and came across several answers. Oddly enough, the first few results on google were some very old topics. This being the earliest one of them, I decide to put my answer here.

private void dgvDetails_ColumnStateChanged(object sender, DataGridViewColumnStateChangedEventArgs e)
{
    e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

The description when you click on ColumStateChanged in the properties window is:

"Occurs when a column changes state, such as gaining or loosing focus"

Granted there are many ways to do this but I thought I'd add this one here. Can't say I found it anywhere else but then again I only read the first 5 topics I found.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.

As of Tensorflow version 1.11.0, you need to take this :

init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

Change name of folder when cloning from GitHub?

You can do this.

git clone https://github.com/sferik/sign-in-with-twitter.git signin

refer the manual here

Mailto on submit button

In HTML you can specify a mailto: address in the <form> element's [action] attribute.

<form action="mailto:[email protected]" method="GET">
    <input name="subject" type="text" />
    <textarea name="body"></textarea>
    <input type="submit" value="Send" />
</form>

What this will do is allow the user's email client to create an email prepopulated with the fields in the <form>.

What this will not do is send an email.

Retrieve column names from java.sql.ResultSet

You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:

ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

Remove duplicate rows in MySQL

This will delete the duplicate rows with same values for title, company and site. The first occurrence will be kept and rest all duplicates will be deleted

DELETE t1 FROM tablename t1
INNER JOIN tablename t2 
WHERE 
    t1.id < t2.id AND
    t1.title = t2.title AND
    t1.company=t2.company AND
    t1.site_ID=t2.site_ID;

WooCommerce - get category for product page

$product->get_categories() is deprecated since version 3.0! Use wc_get_product_category_list instead.

https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html

Tooltips with Twitter Bootstrap

Simply mark all the data-toggles...

jQuery(function () {
    jQuery('[data-toggle=tooltip]').tooltip();
});

http://jsfiddle.net/Amged/xUQ6D/19/

You are trying to add a non-nullable field 'new_field' to userprofile without a default

You can't add reference to table that have already data inside.
Change:

user = models.OneToOneField(User)

to:

user = models.OneToOneField(User, default = "")

do:

python manage.py makemigrations
python manage.py migrate

change again:

user = models.OneToOneField(User)

do migration again:

python manage.py makemigrations
python manage.py migrate

How to hide reference counts in VS2013?

The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.

However, if the only way to disable Show References is to disable CodeLens altogether.

Then, I guess I could do just that.

Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'

If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.

In short, uncheck Codelens...

How to overcome "datetime.datetime not JSON serializable"?

If you are using the result in a view be sure to return a proper response. According to the API, jsonify does the following:

Creates a Response with the JSON representation of the given arguments with an application/json mimetype.

To mimic this behavior with json.dumps you have to add a few extra lines of code.

response = make_response(dumps(sample, cls=CustomEncoder))
response.headers['Content-Type'] = 'application/json'
response.headers['mimetype'] = 'application/json'
return response

You should also return a dict to fully replicate jsonify's response. So, the entire file will look like this

from flask import make_response
from json import JSONEncoder, dumps


class CustomEncoder(JSONEncoder):
    def default(self, obj):
        if set(['quantize', 'year']).intersection(dir(obj)):
            return str(obj)
        elif hasattr(obj, 'next'):
            return list(obj)
        return JSONEncoder.default(self, obj)

@app.route('/get_reps/', methods=['GET'])
def get_reps():
    sample = ['some text', <datetime object>, 123]
    response = make_response(dumps({'result': sample}, cls=CustomEncoder))
    response.headers['Content-Type'] = 'application/json'
    response.headers['mimetype'] = 'application/json'
    return response

angular2: how to copy object into another object

Object.assign will only work in single level of object reference.

To do a copy in any depth use as below:

let x = {'a':'a','b':{'c':'c'}};
let y = JSON.parse(JSON.stringify(x));

If want to use any library instead then go with the loadash.js library.

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

Using Secure Desktop to run cmd.exe as system

We can get kernel access through CMD in Windows XP/Vista/7/8.1 easily by attaching a debugger:

REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\osk.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe"
  1. Run CMD as Administrator

  2. Then use this command in Elevated:

     CMD REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\osk.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe"
    
  3. Then run osk (onscreenkeyboard). It still does not run with system Integrity level if you check through process explorer, but if you can use OSK in service session, it will run as NT Authority\SYSTEM

so I had the idea you have to run it on Secure Desktop.

Start any file as Administrator. When UAC prompts appear, just press Win+U and start OSK and it will start CMD instead. Then in the elevated prompt, type whoami and you will get NT Authority\System. After that, you can start Explorer from the system command shell and use the System profile, but you are somewhat limited what you can do on the network through SYSTEM privileges for security reasons. I will add more explanation later as I discovered it a year ago.

A Brief Explanation of how this happens

Running Cmd.exe Under Local System Account Without Using PsExec. This method runs Debugger Trap technique that was discovered earlier, well this technique has its own benefits it can be used to trap some crafty/malicious worm or malware in the debugger and run some other exe instead to stop the spread or damage temporary. here this registry key traps onscreen keyboard in windows native debugger and runs cmd.exe instead but cmd will still run with Logged on users privileges, however if we run cmd in session0 we can get system shell. so we add here another idea we span the cmd on secure desktop remember secure desktop runs in session 0 under system account and we get system shell. So whenever you run anything as elevated, you have to answer the UAC prompt and UAC prompts on dark, non interactive desktop and once you see it you have to press Win+U and then select OSK you will get CMD.exe running under Local system privileges. There are even more ways to get local system access with CMD

jQuery: Check if div with certain class name exists

if ($("#myid1").hasClass("mydivclass")){// Do any thing}

Language Books/Tutorials for popular languages

For Java, I highly recommend Core Java. It's a large tome (or two large tomes), but I've found it to be one of the best references on Java I've read.

UICollectionView auto scroll to cell at IndexPath

You can use GCD to dispatch the scroll into the next iteration of main run loop in viewDidLoad to achieve this behavior. The scroll will be performed before the collection view is showed on screen, so there will be no flashing.

- (void)viewDidLoad {
    dispatch_async (dispatch_get_main_queue (), ^{
        NSIndexPath *indexPath = YOUR_DESIRED_INDEXPATH;
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    });
}

React - clearing an input value after form submit

You are having a controlled component where input value is determined by this.state.city. So once you submit you have to clear your state which will clear your input automatically.

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
      city: ''
    });
}

ASP.NET postback with JavaScript

Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.

__doPostBack(UpdatePanelClientID, '**Some String**');

Plotting a fast Fourier transform in Python

Just as a complement to the answers already given, I would like to point out that often it is important to play with the size of the bins for the FFT. It would make sense to test a bunch of values and pick the one that makes more sense to your application. Often, it is in the same magnitude of the number of samples. This was as assumed by most of the answers given, and produces great and reasonable results. In case one wants to explore that, here is my code version:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

fig = plt.figure(figsize=[14,4])
N = 600           # Number of samplepoints
Fs = 800.0
T = 1.0 / Fs      # N_samps*T (#samples x sample period) is the sample spacing.
N_fft = 80        # Number of bins (chooses granularity)
x = np.linspace(0, N*T, N)     # the interval
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)   # the signal

# removing the mean of the signal
mean_removed = np.ones_like(y)*np.mean(y)
y = y - mean_removed

# Compute the fft.
yf = scipy.fftpack.fft(y,n=N_fft)
xf = np.arange(0,Fs,Fs/N_fft)

##### Plot the fft #####
ax = plt.subplot(121)
pt, = ax.plot(xf,np.abs(yf), lw=2.0, c='b')
p = plt.Rectangle((Fs/2, 0), Fs/2, ax.get_ylim()[1], facecolor="grey", fill=True, alpha=0.75, hatch="/", zorder=3)
ax.add_patch(p)
ax.set_xlim((ax.get_xlim()[0],Fs))
ax.set_title('FFT', fontsize= 16, fontweight="bold")
ax.set_ylabel('FFT magnitude (power)')
ax.set_xlabel('Frequency (Hz)')
plt.legend((p,), ('mirrowed',))
ax.grid()

##### Close up on the graph of fft#######
# This is the same histogram above, but truncated at the max frequence + an offset. 
offset = 1    # just to help the visualization. Nothing important.
ax2 = fig.add_subplot(122)
ax2.plot(xf,np.abs(yf), lw=2.0, c='b')
ax2.set_xticks(xf)
ax2.set_xlim(-1,int(Fs/6)+offset)
ax2.set_title('FFT close-up', fontsize= 16, fontweight="bold")
ax2.set_ylabel('FFT magnitude (power) - log')
ax2.set_xlabel('Frequency (Hz)')
ax2.hold(True)
ax2.grid()

plt.yscale('log')

the output plots: enter image description here

Accessing post variables using Java Servlets

For getting all post parameters there is Map which contains request param name as key and param value as key.

Map params = servReq.getParameterMap();

And to get parameters with known name normal

String userId=servReq.getParameter("user_id");

Use jQuery to change an HTML tag?

Here's an extension that will do it all, on as many elements in as many ways...

Example usage:

keep existing class and attributes:

$('div#change').replaceTag('<span>', true);

or

Discard existing class and attributes:

$('div#change').replaceTag('<span class=newclass>', false);

or even

replace all divs with spans, copy classes and attributes, add extra class name

$('div').replaceTag($('<span>').addClass('wasDiv'), true);

Plugin Source:

$.extend({
    replaceTag: function (currentElem, newTagObj, keepProps) {
        var $currentElem = $(currentElem);
        var i, $newTag = $(newTagObj).clone();
        if (keepProps) {//{{{
            newTag = $newTag[0];
            newTag.className = currentElem.className;
            $.extend(newTag.classList, currentElem.classList);
            $.extend(newTag.attributes, currentElem.attributes);
        }//}}}
        $currentElem.wrapAll($newTag);
        $currentElem.contents().unwrap();
        // return node; (Error spotted by Frank van Luijn)
        return this; // Suggested by ColeLawrence
    }
});

$.fn.extend({
    replaceTag: function (newTagObj, keepProps) {
        // "return" suggested by ColeLawrence
        return this.each(function() {
            jQuery.replaceTag(this, newTagObj, keepProps);
        });
    }
});

Change Git repository directory location.

I use Visual Studio git plugin, and I have some websites running on IIS I wanted to move. A simple way that worked for me:

  1. Close Visual Studio.

  2. Move the code (including git folder, etc)

  3. Click on the solution file from the new location

This refreshes the mapping to the new location, using the existing local git files that were moved. Once i was back in Visual Studio, my Team Explorer window showed the repos in the new location.

How to add scroll bar to the Relative Layout?

Just put yourRelativeLayout inside ScrollView

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  ------- here RelativeLayout ------
</ScrollView>

Get the (last part of) current directory name in C#

You could try:

var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;

How to determine whether an object has a given property in JavaScript

Why not simply:

if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");

Or if you expect a specific type:

if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");

Adb install failure: INSTALL_CANCELED_BY_USER

One more thing: after some updates of MIUI developer mode becomes disabled. I was sure, that is was turned on, but i couldn't start the application. So i reenabled developer mode and everything started to work. I've encountered this problem several times. Hope it helps.

How to create a fixed-size array of objects

Swift 4

You can somewhat think about it as array of object vs. array of references.

  • [SKSpriteNode] must contain actual objects
  • [SKSpriteNode?] can contain either references to objects, or nil

Examples

  1. Creating an array with 64 default SKSpriteNode:

    var sprites = [SKSpriteNode](repeatElement(SKSpriteNode(texture: nil),
                                               count: 64))
    
  2. Creating an array with 64 empty slots (a.k.a optionals):

    var optionalSprites = [SKSpriteNode?](repeatElement(nil,
                                          count: 64))
    
  3. Converting an array of optionals into an array of objects (collapsing [SKSpriteNode?] into [SKSpriteNode]):

    let flatSprites = optionalSprites.flatMap { $0 }
    

    The count of the resulting flatSprites depends on the count of objects in optionalSprites: empty optionals will be ignored, i.e. skipped.

JavaScript function to add X months to a date

I wrote this alternative solution which works fine to me. It is useful when you wish calculate the end of a contract. For example, start=2016-01-15, months=6, end=2016-7-14 (i.e. last day - 1):

<script>
function daysInMonth(year, month)
{
    return new Date(year, month + 1, 0).getDate();
}

function addMonths(date, months)
{
    var target_month = date.getMonth() + months;
    var year = date.getFullYear() + parseInt(target_month / 12);
    var month = target_month % 12;
    var day = date.getDate();
    var last_day = daysInMonth(year, month);
    if (day > last_day)
    {
        day = last_day;
    }
    var new_date = new Date(year, month, day);
    return new_date;
}

var endDate = addMonths(startDate, months);
</script>

Examples:

addMonths(new Date("2016-01-01"), 1); // 2016-01-31
addMonths(new Date("2016-01-01"), 2); // 2016-02-29 (2016 is a leap year)
addMonths(new Date("2016-01-01"), 13); // 2017-01-31
addMonths(new Date("2016-01-01"), 14); // 2017-02-28

set background color: Android

This question is a old one but it can help for others too.

Try this :

    li.setBackgroundColor(getResources().getColor(R.color.blue));

    or

    li.setBackgroundColor(getResources().getColor(android.R.color.red));

    or

    li.setBackgroundColor(Color.rgb(226, 11, 11));


    or
    li.setBackgroundColor(Color.RED)

Extracting substrings in Go

Go strings are not null terminated, and to remove the last char of a string you can simply do:

s = s[:len(s)-1]

How to force IE to reload javascript?

In javascript I think that it is not possible, because modern browsers have a policy on security in javascripts.. and clearing the cache is a very violating one.

You can try to add

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

In your header, but you will have performance loss.

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..

svn : how to create a branch from certain revision of trunk

Check out the help command:

svn help copy

  -r [--revision] arg      : ARG (some commands also take ARG1:ARG2 range)
                             A revision argument can be one of:
                                NUMBER       revision number
                                '{' DATE '}' revision at start of the date
                                'HEAD'       latest in repository
                                'BASE'       base rev of item's working copy
                                'COMMITTED'  last commit at or before BASE
                                'PREV'       revision just before COMMITTED

To actually specify this on the command line using your example:

svn copy -r123 http://svn.example.com/repos/calc/trunk \
    http://svn.example.com/repos/calc/branches/my-calc-branch

Where 123 would be the revision number in trunk you want to copy. As others have noted, you can also use the @ syntax. I prefer the clearer separation of the revision # from the URL, personally.

As noted in the help, you can replace a revision # with certain words as well:

svn copy -rPREV http://svn.example.com/repos/calc/trunk \
    http://svn.example.com/repos/calc/branches/my-calc-branch

Would copy the "revision just before COMMITTED".

Cast IList to List

The other answers all recommend to use AddRange with an IList.

A more elegant solution that avoids the casting is to implement an extension to IList to do the job.

In VB.NET:

<Extension()>
Public Sub AddRange(Of T)(ByRef Exttype As IList(Of T), ElementsToAdd As IEnumerable(Of T))
   For Each ele In ElementsToAdd
      Exttype.Add(ele)
   Next
End Sub

And in C#:

public void AddRange<T>(this ref IList<T> Exttype, IEnumerable<T> ElementsToAdd)
{
    foreach (var ele in ElementsToAdd)
    {
        Exttype.Add(ele);
    }
}

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

You have to use the encoding as latin1 to read this file as there are some special character in this file, use the below code snippet to read the file.

The problem here is the encoding type. When Python can't convert the data to be read, it gives an error.

You can you latin1 or other encoding values.

I say try and test to find the right one for your dataset.

How to fix "unable to write 'random state' " in openssl

The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:

set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024

More explanations: OpenSSL on Windows tries to save the 'random state' file in the following order:

  1. Path taken from RANDFILE environment variable
  2. If HOME environment variable is set then : ${HOME}\.rnd
  3. C:\.rnd

I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.

iOS 7 UIBarButton back button arrow color

In iOS 7, you can put the following line of code inside application:didFinishLaunchingWithOptions: in your AppDelegate.m file:

[[UINavigationBar appearance] setTintColor:myColor];

Set myColor to the color you want the back button to be throughout the entire app. No need to put it in every file.

Alternate table with new not null Column in existing table in SQL

IF NOT EXISTS (SELECT 1
FROM syscolumns sc
JOIN sysobjects so
ON sc.id = so.id
WHERE so.Name = 'Table1'
AND sc.Name = 'Col1')
BEGIN
ALTER TABLE Table1
ADD Col1 INT NOT NULL DEFAULT 0;
END
GO

Google drive limit number of download

This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "

This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.

Maybe using the TOR network may help you do your job.

Disable Transaction Log

What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.

From Microsoft documentation:

In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.

C++11 rvalues and move semantics confusion (return statement)

Not an answer per se, but a guideline. Most of the time there is not much sense in declaring local T&& variable (as you did with std::vector<int>&& rval_ref). You will still have to std::move() them to use in foo(T&&) type methods. There is also the problem that was already mentioned that when you try to return such rval_ref from function you will get the standard reference-to-destroyed-temporary-fiasco.

Most of the time I would go with following pattern:

// Declarations
A a(B&&, C&&);
B b();
C c();

auto ret = a(b(), c());

You don't hold any refs to returned temporary objects, thus you avoid (inexperienced) programmer's error who wish to use a moved object.

auto bRet = b();
auto cRet = c();
auto aRet = a(std::move(b), std::move(c));

// Either these just fail (assert/exception), or you won't get 
// your expected results due to their clean state.
bRet.foo();
cRet.bar();

Obviously there are (although rather rare) cases where a function truly returns a T&& which is a reference to a non-temporary object that you can move into your object.

Regarding RVO: these mechanisms generally work and compiler can nicely avoid copying, but in cases where the return path is not obvious (exceptions, if conditionals determining the named object you will return, and probably couple others) rrefs are your saviors (even if potentially more expensive).

Docker is installed but Docker Compose is not ? why?

I'm installing on a Raspberry Pi 3, on Raspbian OS. The curl method didn't resolve to a valid response. It also said {error: Not Found}, I took a look at the URL https://github.com/docker/compose/releases/download/1.11.2/docker-compose-Linux-armv7l and it was not valid. I guess there was no build there.

This guide https://github.com/hypriot/arm-compose worked for me.

sudo apt-get update
sudo apt-get install -y apt-transport-https
echo "deb https://packagecloud.io/Hypriot/Schatzkiste/debian/ jessie main" | sudo tee /etc/apt/sources.list.d/hypriot.list
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 37BBEE3F7AD95B3F
sudo apt-get update
sudo apt-get install docker-compose

How to check if a date is greater than another in Java?

You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

Try to implement the code yourself.

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

Background thread with QThread in PyQt

In PyQt there are a lot of options for getting asynchronous behavior. For things that need event processing (ie. QtNetwork, etc) you should use the QThread example I provided in my other answer on this thread. But for the vast majority of your threading needs, I think this solution is far superior than the other methods.

The advantage of this is that the QThreadPool schedules your QRunnable instances as tasks. This is similar to the task pattern used in Intel's TBB. It's not quite as elegant as I like but it does pull off excellent asynchronous behavior.

This allows you to utilize most of the threading power of Qt in Python via QRunnable and still take advantage of signals and slots. I use this same code in several applications, some that make hundreds of asynchronous REST calls, some that open files or list directories, and the best part is using this method, Qt task balances the system resources for me.

import time
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt


def async(method, args, uid, readycb, errorcb=None):
    """
    Asynchronously runs a task

    :param func method: the method to run in a thread
    :param object uid: a unique identifier for this task (used for verification)
    :param slot updatecb: the callback when data is receieved cb(uid, data)
    :param slot errorcb: the callback when there is an error cb(uid, errmsg)

    The uid option is useful when the calling code makes multiple async calls
    and the callbacks need some context about what was sent to the async method.
    For example, if you use this method to thread a long running database call
    and the user decides they want to cancel it and start a different one, the
    first one may complete before you have a chance to cancel the task.  In that
    case, the "readycb" will be called with the cancelled task's data.  The uid
    can be used to differentiate those two calls (ie. using the sql query).

    :returns: Request instance
    """
    request = Request(method, args, uid, readycb, errorcb)
    QtCore.QThreadPool.globalInstance().start(request)
    return request


class Request(QtCore.QRunnable):
    """
    A Qt object that represents an asynchronous task

    :param func method: the method to call
    :param list args: list of arguments to pass to method
    :param object uid: a unique identifier (used for verification)
    :param slot readycb: the callback used when data is receieved
    :param slot errorcb: the callback used when there is an error

    The uid param is sent to your error and update callbacks as the
    first argument. It's there to verify the data you're returning

    After created it should be used by invoking:

    .. code-block:: python

       task = Request(...)
       QtCore.QThreadPool.globalInstance().start(task)

    """
    INSTANCES = []
    FINISHED = []
    def __init__(self, method, args, uid, readycb, errorcb=None):
        super(Request, self).__init__()
        self.setAutoDelete(True)
        self.cancelled = False

        self.method = method
        self.args = args
        self.uid = uid
        self.dataReady = readycb
        self.dataError = errorcb

        Request.INSTANCES.append(self)

        # release all of the finished tasks
        Request.FINISHED = []

    def run(self):
        """
        Method automatically called by Qt when the runnable is ready to run.
        This will run in a separate thread.
        """
        # this allows us to "cancel" queued tasks if needed, should be done
        # on shutdown to prevent the app from hanging
        if self.cancelled:
            self.cleanup()
            return

        # runs in a separate thread, for proper async signal/slot behavior
        # the object that emits the signals must be created in this thread.
        # Its not possible to run grabber.moveToThread(QThread.currentThread())
        # so to get this QObject to properly exhibit asynchronous
        # signal and slot behavior it needs to live in the thread that
        # we're running in, creating the object from within this thread
        # is an easy way to do that.
        grabber = Requester()
        grabber.Loaded.connect(self.dataReady, Qt.QueuedConnection)
        if self.dataError is not None:
            grabber.Error.connect(self.dataError, Qt.QueuedConnection)

        try:
            result = self.method(*self.args)
            if self.cancelled:
                # cleanup happens in 'finally' statement
                return
            grabber.Loaded.emit(self.uid, result)
        except Exception as error:
            if self.cancelled:
                # cleanup happens in 'finally' statement
                return
            grabber.Error.emit(self.uid, unicode(error))
        finally:
            # this will run even if one of the above return statements
            # is executed inside of the try/except statement see:
            # https://docs.python.org/2.7/tutorial/errors.html#defining-clean-up-actions
            self.cleanup(grabber)

    def cleanup(self, grabber=None):
        # remove references to any object or method for proper ref counting
        self.method = None
        self.args = None
        self.uid = None
        self.dataReady = None
        self.dataError = None

        if grabber is not None:
            grabber.deleteLater()

        # make sure this python obj gets cleaned up
        self.remove()

    def remove(self):
        try:
            Request.INSTANCES.remove(self)

            # when the next request is created, it will clean this one up
            # this will help us avoid this object being cleaned up
            # when it's still being used
            Request.FINISHED.append(self)
        except ValueError:
            # there might be a race condition on shutdown, when shutdown()
            # is called while the thread is still running and the instance
            # has already been removed from the list
            return

    @staticmethod
    def shutdown():
        for inst in Request.INSTANCES:
            inst.cancelled = True
        Request.INSTANCES = []
        Request.FINISHED = []


class Requester(QtCore.QObject):
    """
    A simple object designed to be used in a separate thread to allow
    for asynchronous data fetching
    """

    #
    # Signals
    #

    Error = QtCore.pyqtSignal(object, unicode)
    """
    Emitted if the fetch fails for any reason

    :param unicode uid: an id to identify this request
    :param unicode error: the error message
    """

    Loaded = QtCore.pyqtSignal(object, object)
    """
    Emitted whenever data comes back successfully

    :param unicode uid: an id to identify this request
    :param list data: the json list returned from the GET
    """

    NetworkConnectionError = QtCore.pyqtSignal(unicode)
    """
    Emitted when the task fails due to a network connection error

    :param unicode message: network connection error message
    """

    def __init__(self, parent=None):
        super(Requester, self).__init__(parent)


class ExampleObject(QtCore.QObject):
    def __init__(self, parent=None):
        super(ExampleObject, self).__init__(parent)
        self.uid = 0
        self.request = None

    def ready_callback(self, uid, result):
        if uid != self.uid:
            return
        print "Data ready from %s: %s" % (uid, result)

    def error_callback(self, uid, error):
        if uid != self.uid:
            return
        print "Data error from %s: %s" % (uid, error)

    def fetch(self):
        if self.request is not None:
            # cancel any pending requests
            self.request.cancelled = True
            self.request = None

        self.uid += 1
        self.request = async(slow_method, ["arg1", "arg2"], self.uid,
                             self.ready_callback,
                             self.error_callback)


def slow_method(arg1, arg2):
    print "Starting slow method"
    time.sleep(1)
    return arg1 + arg2


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)

    obj = ExampleObject()

    dialog = QtGui.QDialog()
    layout = QtGui.QVBoxLayout(dialog)
    button = QtGui.QPushButton("Generate", dialog)
    progress = QtGui.QProgressBar(dialog)
    progress.setRange(0, 0)
    layout.addWidget(button)
    layout.addWidget(progress)
    button.clicked.connect(obj.fetch)
    dialog.show()

    app.exec_()
    app.deleteLater() # avoids some QThread messages in the shell on exit
    # cancel all running tasks avoid QThread/QTimer error messages
    # on exit
    Request.shutdown()

When exiting the application you'll want to make sure you cancel all of the tasks or the application will hang until every scheduled task has completed

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Why is January month 0 in Java Calendar?

It's just part of the horrendous mess which is the Java date/time API. Listing what's wrong with it would take a very long time (and I'm sure I don't know half of the problems). Admittedly working with dates and times is tricky, but aaargh anyway.

Do yourself a favour and use Joda Time instead, or possibly JSR-310.

EDIT: As for the reasons why - as noted in other answers, it could well be due to old C APIs, or just a general feeling of starting everything from 0... except that days start with 1, of course. I doubt whether anyone outside the original implementation team could really state reasons - but again, I'd urge readers not to worry so much about why bad decisions were taken, as to look at the whole gamut of nastiness in java.util.Calendar and find something better.

One point which is in favour of using 0-based indexes is that it makes things like "arrays of names" easier:

// I "know" there are 12 months
String[] monthNames = new String[12]; // and populate...
String name = monthNames[calendar.get(Calendar.MONTH)];

Of course, this fails as soon as you get a calendar with 13 months... but at least the size specified is the number of months you expect.

This isn't a good reason, but it's a reason...

EDIT: As a comment sort of requests some ideas about what I think is wrong with Date/Calendar:

  • Surprising bases (1900 as the year base in Date, admittedly for deprecated constructors; 0 as the month base in both)
  • Mutability - using immutable types makes it much simpler to work with what are really effectively values
  • An insufficient set of types: it's nice to have Date and Calendar as different things, but the separation of "local" vs "zoned" values is missing, as is date/time vs date vs time
  • An API which leads to ugly code with magic constants, instead of clearly named methods
  • An API which is very hard to reason about - all the business about when things are recomputed etc
  • The use of parameterless constructors to default to "now", which leads to hard-to-test code
  • The Date.toString() implementation which always uses the system local time zone (that's confused many Stack Overflow users before now)

Spring Data: "delete by" is supported?

Deprecated answer (Spring Data JPA <=1.6.x):

@Modifying annotation to the rescue. You will need to provide your custom SQL behaviour though.

public interface UserRepository extends JpaRepository<User, Long> {
    @Modifying
    @Query("delete from User u where u.firstName = ?1")
    void deleteUsersByFirstName(String firstName);
}

Update:

In modern versions of Spring Data JPA (>=1.7.x) query derivation for delete, remove and count operations is accessible.

public interface UserRepository extends CrudRepository<User, Long> {

    Long countByFirstName(String firstName);

    Long deleteByFirstName(String firstName);

    List<User> removeByFirstName(String firstName);

}

How to convert datetime format to date format in crystal report using C#?

In case the formatting needs to be done on Crystal Report side.

Simple way.

Crystal Report Design Window->Right click on the date field->format Field->Customize the date format per your need.

Works effectively.

Reminder - \r\n or \n\r?

In any .NET langauge, Environment.NewLine would be preferable.

Why is my Git Submodule HEAD detached from master?

As other people have said, the reason this happens is that the parent repo only contains a reference to (the SHA1 of) a specific commit in the submodule – it doesn't know anything about branches. This is how it should work: the branch that was at that commit may have moved forward (or backwards), and if the parent repo had referenced the branch then it could easily break when that happens.

However, especially if you are actively developing in both the parent repo and the submodule, detached HEAD state can be confusing and potentially dangerous. If you make commits in the submodule while it's in detached HEAD state, these become dangling and you can easily lose your work. (Dangling commits can usually be rescued using git reflog, but it's much better to avoid them in the first place.)

If you're like me, then most of the time if there is a branch in the submodule that points to the commit being checked out, you would rather check out that branch than be in detached HEAD state at the same commit. You can do this by adding the following alias to your gitconfig file:

[alias]
    submodule-checkout-branch = "!f() { git submodule -q foreach 'branch=$(git branch --no-column --format=\"%(refname:short)\" --points-at `git rev-parse HEAD` | grep -v \"HEAD detached\" | head -1); if [[ ! -z $branch && -z `git symbolic-ref --short -q HEAD` ]]; then git checkout -q \"$branch\"; fi'; }; f"

Now, after doing git submodule update you just need to call git submodule-checkout-branch, and any submodule that is checked out at a commit which has a branch pointing to it will check out that branch. If you don't often have multiple local branches all pointing to the same commit, then this will usually do what you want; if not, then at least it will ensure that any commits you do make go onto an actual branch instead of being left dangling.

Furthermore, if you have set up git to automatically update submodules on checkout (using git config --global submodule.recurse true, see this answer), you can make a post-checkout hook that calls this alias automatically:

$ cat .git/hooks/post-checkout 
#!/bin/sh
git submodule-checkout-branch

Then you don't need to call either git submodule update or git submodule-checkout-branch, just doing git checkout will update all submodules to their respective commits and check out the corresponding branches (if they exist).

Servlet for serving static content

Use org.mortbay.jetty.handler.ContextHandler. You don't need additional components like StaticServlet.

At the jetty home,

$ cd contexts

$ cp javadoc.xml static.xml

$ vi static.xml

...

<Configure class="org.mortbay.jetty.handler.ContextHandler">
<Set name="contextPath">/static</Set>
<Set name="resourceBase"><SystemProperty name="jetty.home" default="."/>/static/</Set>
<Set name="handler">
  <New class="org.mortbay.jetty.handler.ResourceHandler">
    <Set name="cacheControl">max-age=3600,public</Set>
  </New>
 </Set>
</Configure>

Set the value of contextPath with your URL prefix, and set the value of resourceBase as the file path of the static content.

It worked for me.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

If you trust the host, either add the valid certificate, specify --no-check-certificate or add:

check_certificate = off

into your ~/.wgetrc.

In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.

How can I select rows with most recent timestamp for each key value?

WITH SensorTimes As (
   SELECT sensorID, MAX(timestamp) "LastReading"
   FROM sensorTable
   GROUP BY sensorID
)
SELECT s.sensorID,s.timestamp,s.sensorField1,s.sensorField2 
FROM sensorTable s
INNER JOIN SensorTimes t on s.sensorID = t.sensorID and s.timestamp = t.LastReading

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

Excel formula to remove space between words in a cell

It is SUBSTITUTE(B1," ",""), not REPLACE(xx;xx;xx).

100% width background image with an 'auto' height

It's 2017, and now you can use object-fit which has decent support. It works in the same way as a div's background-size but on the element itself, and on any element including images.

.your-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

Can't connect to MySQL server error 111

If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.

Simplest JQuery validation rules example

$("#commentForm").validate({
    rules: {
     cname : { required : true, minlength: 2 }
    }
});

Should be something like that, I've just typed this up in the editor here so might be a syntax error or two, but you should be able to follow the pattern and the documentation

Get records of current month

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())

How do I find duplicates across multiple columns?

Given a staging table with 70 columns and only 4 representing duplicates, this code will return the offending columns:

SELECT 
    COUNT(*)
    ,LTRIM(RTRIM(S.TransactionDate)) 
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber)) 
    ,LTRIM(RTRIM(GrossCost)) 
FROM Staging.dbo.Stage S
GROUP BY 
    LTRIM(RTRIM(S.TransactionDate)) 
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber)) 
    ,LTRIM(RTRIM(GrossCost)) 
HAVING COUNT(*) > 1

.

Java Switch Statement - Is "or"/"and" possible?

Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.

For OR, just have 2 cases without the break on the 1st. Eg:

case 'a':
case 'A':
  // do stuff
  break;

How to replace a character by a newline in Vim

Use \r instead of \n.

Substituting by \n inserts a null character into the text. To get a newline, use \r. When searching for a newline, you’d still use \n, however. This asymmetry is due to the fact that \n and \r do slightly different things:

\n matches an end of line (newline), whereas \r matches a carriage return. On the other hand, in substitutions \n inserts a null character whereas \r inserts a newline (more precisely, it’s treated as the input CR). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). xxd shows a hexdump of the resulting file.

echo bar > test
(echo 'Before:'; xxd test) > output.txt
vim test '+s/b/\n/' '+s/a/\r/' +wq
(echo 'After:'; xxd test) >> output.txt
more output.txt
Before:
0000000: 6261 720a                                bar.
After:
0000000: 000a 720a                                ..r.

In other words, \n has inserted the byte 0x00 into the text; \r has inserted the byte 0x0a.

1052: Column 'id' in field list is ambiguous

Already there are lots of answers to your question, You can do it like this also. You can give your table an alias name and use that in the select query like this:

SELECT a.id, b.id, name, section
FROM tbl_names as a 
LEFT JOIN tbl_section as b ON a.id = b.id;

Highest Salary in each department

SELECT
    DeptID,
    Salary
FROM
    EmpDetails
GROUP BY
    DeptID
ORDER BY
    Salary desc

HTML Input - already filled in text

TO give the prefill value in HTML Side as below:

HTML:

<input type="text" id="abc" value="any value">

JQUERY:

$(document).ready(function ()
 {
  $("#abc").val('any value');
 });