Programs & Examples On #Rtcp

**RTP Control Protocol** (RTCP) is a helper protocol for *Real-time Transport Protocol* (RTP).

Create Log File in Powershell

I believe this is the simplest way of putting all what it is on the screen into a file. It is a native PS CmdLet so you don't have to change anything in yout script

Start-Transcript -Path Computer.log

Write-Host "everything will end up in Computer.log"

Stop-Transcript

What is the purpose of the "final" keyword in C++11 for functions?

Nothing to add to the semantic aspects of "final".

But I'd like to add to chris green's comment that "final" might become a very important compiler optimization technique in the not so distant future. Not only in the simple case he mentioned, but also for more complex real-world class hierarchies which can be "closed" by "final", thus allowing compilers to generate more efficient dispatching code than with the usual vtable approach.

One key disadvantage of vtables is that for any such virtual object (assuming 64-bits on a typical Intel CPU) the pointer alone eats up 25% (8 of 64 bytes) of a cache line. In the kind of applications I enjoy to write, this hurts very badly. (And from my experience it is the #1 argument against C++ from a purist performance point of view, i.e. by C programmers.)

In applications which require extreme performance, which is not so unusual for C++, this might indeed become awesome, not requiring to workaround this problem manually in C style or weird Template juggling.

This technique is known as Devirtualization. A term worth remembering. :-)

There is a great recent speech by Andrei Alexandrescu which pretty well explains how you can workaround such situations today and how "final" might be part of solving similar cases "automatically" in the future (discussed with listeners):

http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

Spring Boot how to hide passwords in properties file

UPDATE: I noticed folks down-voting this, so I have to say that although this is not an ideal solution, but this works and acceptable in some use-cases. Cloudfoundry uses Environment variables to inject credentials when a Service is binded to an application. More info https://docs.cloudfoundry.org/devguide/services/application-binding.html

And also if your system is not shared, then for local development this is also acceptable. Of course, the more safe and secure way is explained in Answer by @J-Alex.

Answer:

If you want to hide your passwords then the easiest solution is to use Environment variables in application.properties file or directly in your code.

In application.properties:

mypassword=${password}

Then in your configuration class:

@Autowired
private Environment environment;

[...]//Inside a method
System.out.println(environment.getProperty("mypassword"));

In your configuration class:

@Value("${password}")
private String herokuPath;

[...]//Inside a method
System.out.println(herokuPath);

Note: You might have to restart after setting the environment variable. For windows:

In Windows

Refer this Documentation for more info.

How can I make a "color map" plot in matlab?

Note that both pcolor and "surf + view(2)" do not show the last row and the last column of your 2D data.

On the other hand, using imagesc, you have to be careful with the axes. The surf and the imagesc examples in gevang's answer only (almost -- apart from the last row and column) correspond to each other because the 2D sinc function is symmetric.

To illustrate these 2 points, I produced the figure below with the following code:

[x, y] = meshgrid(1:10,1:5);
z      = x.^3 + y.^3;

subplot(3,1,1)
imagesc(flipud(z)), axis equal tight, colorbar
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc')

subplot(3,1,2)
surf(x,y,z,'EdgeColor','None'), view(2), axis equal tight, colorbar
title('surf with view(2)')

subplot(3,1,3)
imagesc(flipud(z)), axis equal tight, colorbar
axis([0.5 9.5 1.5 5.5])
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc cropped')

colormap jet

surf vs imagesc

As you can see the 10th row and 5th column are missing in the surf plot. (You can also see this in images in the other answers.)

Note how you can use the "set(gca, 'YTick'..." (and Xtick) command to set the x and y tick labels properly if x and y are not 1:1:N.

Also note that imagesc only makes sense if your z data correspond to xs and ys are (each) equally spaced. If not you can use surf (and possibly duplicate the last column and row and one more "(end,end)" value -- although that's a kind of a dirty approach).

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

Try this

Change the order of files it should be like below..

<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/wow.min.js"></script>

Making a triangle shape using xml definitions?

You can use vector drawables.

If your minimum API is lower than 21, Android Studio automatically creates PNG bitmaps for those lower versions at build time (see Vector Asset Studio). If you use the support library, Android even manages "real vectors" down to API 7 (more on that in the update of this post at the bottom).

A red upwards pointing triangle would be:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="100dp"
    android:width="100dp"
    android:viewportHeight="100"
    android:viewportWidth="100" >
    <group
        android:name="triableGroup">
        <path
            android:name="triangle"
            android:fillColor="#FF0000"
            android:pathData="m 50,0 l 50,100 -100,0 z" />
    </group>
</vector>

Add it to your layout and remember to set clipChildren="false" if you rotate the triangle.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false">

    <ImageView
        android:layout_width="130dp"
        android:layout_height="100dp"
        android:rotation="0"
        android:layout_centerInParent="true"
        android:background="@drawable/triangle"/>

</RelativeLayout>

enter image description here

Change the size (width/height) of the triangle by setting the Views layout_width/layout_height attributes. This way you can also get an eqilateral triagle if you do the math correct.

UPDATE 25.11.2017

If you use the support library you can use real vectors (instead if bitmap creation) as far back as API 7. Simply add:

vectorDrawables.useSupportLibrary = true

do your defaultConfig in your module's build.gradle.

Then set the (vector xml) drawable like this:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    app:srcCompat="@drawable/triangle" />

Everything is documented very nicely on the Vector Asset Studio page.

Ever since this feature I've been working entirely without bitmaps in terms of icons. This also reduces APK size quite a bit.

How to Sign an Already Compiled Apk

Automated Process:

Use this tool (uses the new apksigner from Google):

https://github.com/patrickfav/uber-apk-signer

Disclaimer: Im the developer :)

Manual Process:

Step 1: Generate Keystore (only once)

You need to generate a keystore once and use it to sign your unsigned apk. Use the keytool provided by the JDK found in %JAVA_HOME%/bin/

keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app

Step 2 or 4: Zipalign

zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimization step if you want to upload the apk to the Play Store.

zipalign -p 4 my.apk my-aligned.apk

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).

You can verify the alignment with

zipalign -c 4 my-aligned.apk

Step 3: Sign & Verify

Using build-tools 24.0.2 and older

Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name

and can be verified with

jarsigner -verify -verbose my_application.apk

Using build-tools 24.0.3 and newer

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Therefore, Google implemented their own apk signer called apksigner (duh!) The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this

apksigner sign --ks my.keystore my-app.apk --ks-key-alias alias_name

and can be verified with

apksigner verify my-app.apk

The official documentation can be found here.

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

Getting the Username from the HKEY_USERS values

By searching for my userid in the registry, I found

HKEY_CURRENT_USER\Volatile Environment\Username

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

How can I sanitize user input with PHP?

No. You can't generically filter data without any context of what it's for. Sometimes you'd want to take a SQL query as input and sometimes you'd want to take HTML as input.

You need to filter input on a whitelist -- ensure that the data matches some specification of what you expect. Then you need to escape it before you use it, depending on the context in which you are using it.

The process of escaping data for SQL - to prevent SQL injection - is very different from the process of escaping data for (X)HTML, to prevent XSS.

Create a directory if it does not exist and then create the files in that directory as well

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.

Also, I replaced your append calls with concat or + as I saw appropriate.

public void writeFile(String value){
    String PATH = "/remote/dir/server/";
    String directoryName = PATH.concat(this.getClassName());
    String fileName = id + getTimeStamp() + ".txt";

    File directory = new File(directoryName);
    if (! directory.exists()){
        directory.mkdir();
        // If you require it to make the entire directory path including parents,
        // use directory.mkdirs(); here instead.
    }

    File file = new File(directoryName + "/" + fileName);
    try{
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(value);
        bw.close();
    }
    catch (IOException e){
        e.printStackTrace();
        System.exit(-1);
    }
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.

Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.

Regular expression which matches a pattern, or is an empty string

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use

^$|^[^@\s]+@[^@\s]+$

meaning

^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
@         
[^@\s]+
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

.autocomplete is not a function Error

My issue ended up being visual studio catching an unhandled exception and preventing the script from running any further. Because I was running in the IDE, it looked like there was an issue when there wasn't. Autocomplete was working just fine. I added a try/catch block and that made the IDE happy.

 $.ajax({
            url: "/MyController/MyAction",
            type: "POST",
            dataType: "json",
            data: { prefix: request.term },
            success: function (data) {
                try {
                    response($.map(data, function (item) {
                        return { label: item.Name, value: item.Name };
                    }))
                } catch (err) { }

            }
        })

How to check java bit version on Linux?

Go to this JVM online test and run it.

Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

No == operator found while comparing structs in C++

Starting in C++20, it should be possible to add a full set of default comparison operators (==, <=, etc.) to a class by declaring a default three-way comparison operator ("spaceship" operator), like this:

struct Point {
    int x;
    int y;
    auto operator<=>(const Point&) const = default;
};

With a compliant C++20 compiler, adding that line to MyStruct1 and MyStruct2 may be enough to allow equality comparisons, assuming the definition of MyStruct2 is compatible.

Connect to network drive with user name and password

var fileName = "Mylogs.log";
var local = Path.Combine(@"C:\TempLogs", fileName);
var remote = Path.Combine(@"\\servername\c$\Windows\Temp\", fileName);

WebClient request = new WebClient();
request.Credentials = new NetworkCredential(@"username", "password");

if (File.Exists(local))
{
    File.Delete(local);

    File.Copy(remote, local, true);
}
else
{
    File.Copy(remote, local, true);
}

converting epoch time with milliseconds to datetime

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to convert int to NSString?

Primitives can be converted to objects with @() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:

NSString *strValue = [@(myInt) stringValue];

or

NSString *strValue = @(myInt).stringValue;

Why is the Android emulator so slow? How can we speed up the Android emulator?

Simple easy solution for beginners. I have tried many ways and stopped with Genymotion in combination with Eclipse. Genymotion simply adds a virtual device to Eclipse.

Step by step:

  1. Download Genymotion with VirtualBox included from here.
  2. Install this package included build in VirtualBox.
  3. Install the plugin into Eclipse from here.
  4. Start GenyMotion and create a virtual device you want use, and start it.
  5. In Eclipse, go to Window -> Preferences -> GenyMobile -> GenyMotion, and set the path to GenyMotion (in my case, C:/ProgramFiles/GenyMobile/Genymotion).
  6. Click on a project name in Eclipse that you want to start. Start the application using "Run as". In the list of devices, you should see the emulated device.
  7. You cam emulate what you want.

In my case, this solution is the one and only fast solution. No emulators in Eclipse have never worked so fast, and every setting was very slow. Only this solution works almost in realtime. I can recommend (notebook i3, 2.6 GHz).

How to keep onItemSelected from firing off on a newly instantiated Spinner?

The solution with a boolean flag or a counter didn't help me, 'cause during orientation change onItemSelected() calls "overflew" the flag or the counter.

I subclassed android.widget.Spinner and made tiny additions. The relevant parts are below. This solution worked for me.

private void setHandleOnItemSelected()
{
  final StackTraceElement [] elements = Thread.currentThread().getStackTrace();

  for (int index = 1; index < elements.length; index++)
  {
     handleOnItemSelected = elements[index].toString().indexOf("PerformClick") != -1; //$NON-NLS-1$

     if (handleOnItemSelected)
     {
        break;
     }
  }
}

@Override
public void setSelection(int position, boolean animate)
{
  super.setSelection(position, animate);

  setHandleOnItemSelected();
}

@Override
public void setSelection(int position)
{
  super.setSelection(position);

  setHandleOnItemSelected();
}

public boolean shouldHandleOnItemSelected()
{
  return handleOnItemSelected;
}

When should I use the Visitor Design Pattern?

Based on the excellent answer of @Federico A. Ramponi.

Just imagine you have this hierarchy:

public interface IAnimal
{
    void DoSound();
}

public class Dog : IAnimal
{
    public void DoSound()
    {
        Console.WriteLine("Woof");
    }
}

public class Cat : IAnimal
{
    public void DoSound(IOperation o)
    {
        Console.WriteLine("Meaw");
    }
}

What happen if you need to add a "Walk" method here? That will be painful to the whole design.

At the same time, adding the "Walk" method generate new questions. What about "Eat" or "Sleep"? Must we really add a new method to the Animal hierarchy for every new action or operation that we want to add? That's ugly and most important, we will never be able to close the Animal interface. So, with the visitor pattern, we can add new method to the hierarchy without modifying the hierarchy!

So, just check and run this C# example:

using System;
using System.Collections.Generic;

namespace VisitorPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            var animals = new List<IAnimal>
            {
                new Cat(), new Cat(), new Dog(), new Cat(), 
                new Dog(), new Dog(), new Cat(), new Dog()
            };

            foreach (var animal in animals)
            {
                animal.DoOperation(new Walk());
                animal.DoOperation(new Sound());
            }

            Console.ReadLine();
        }
    }

    public interface IOperation
    {
        void PerformOperation(Dog dog);
        void PerformOperation(Cat cat);
    }

    public class Walk : IOperation
    {
        public void PerformOperation(Dog dog)
        {
            Console.WriteLine("Dog walking");
        }

        public void PerformOperation(Cat cat)
        {
            Console.WriteLine("Cat Walking");
        }
    }

    public class Sound : IOperation
    {
        public void PerformOperation(Dog dog)
        {
            Console.WriteLine("Woof");
        }

        public void PerformOperation(Cat cat)
        {
            Console.WriteLine("Meaw");
        }
    }

    public interface IAnimal
    {
        void DoOperation(IOperation o);
    }

    public class Dog : IAnimal
    {
        public void DoOperation(IOperation o)
        {
            o.PerformOperation(this);
        }
    }

    public class Cat : IAnimal
    {
        public void DoOperation(IOperation o)
        {
            o.PerformOperation(this);
        }
    }
}

How to create a label inside an <input> element?

Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
    <meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <style type="text/css" >

        input.searcher
        {
            background-image: url(/images/search_back.png);
            background-repeat: no-repeat;
            background-attachment: scroll;
            background-x-position: left;
            background-y-position: center;
        }

    </style>

    <script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
    <input type="text" id="q" name="q" value="" />

    <script type="text/javascript" language="JavaScript" >
    //  <![CDATA[
        function f(e){
            $('q').removeClassName('searcher');
        }

        function b(e){
            if ( $F('q') == '' )
            {
                $('q').addClassName('searcher');
            }
        }

        Event.observe( 'q', 'focus', f);
        Event.observe( 'q', 'blur', b);
        Event.observe( window, 'load', b);

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

How to run Visual Studio post-build events for debug build only

Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step.

ISO time (ISO 8601) in Python

ISO 8601 Time Representation

The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are

2010-12-16 17:22:15
20101216T172215

(which both stand for the 16th of December 2010), but the format also allows for sub-second resolution times and to specify time zones. This format is of course not Python-specific, but it is good for storing dates and times in a portable format. Details about this format can be found in the Markus Kuhn entry.

I recommend use of this format to store times in files.

One way to get the current time in this representation is to use strftime from the time module in the Python standard library:

>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2010-03-03 21:16:45'

You can use the strptime constructor of the datetime class:

>>> from datetime import datetime
>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 6, 4, 21, 8, 12)

The most robust is the Egenix mxDateTime module:

>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2010, 3, 6, 21, 8, 12)

References

Java: Calling a super method which calls an overridden method

Further more extended the output of the raised question, this will give more insight on the access specifier and override behavior.

            package overridefunction;
            public class SuperClass 
                {
                public void method1()
                {
                    System.out.println("superclass method1");
                    this.method2();
                    this.method3();
                    this.method4();
                    this.method5();
                }
                public void method2()
                {
                    System.out.println("superclass method2");
                }
                private void method3()
                {
                    System.out.println("superclass method3");
                }
                protected void method4()
                {
                    System.out.println("superclass method4");
                }
                void method5()
                {
                    System.out.println("superclass method5");
                }
            }

            package overridefunction;
            public class SubClass extends SuperClass
            {
                @Override
                public void method1()
                {
                    System.out.println("subclass method1");
                    super.method1();
                }
                @Override
                public void method2()
                {
                    System.out.println("subclass method2");
                }
                // @Override
                private void method3()
                {
                    System.out.println("subclass method3");
                }
                @Override
                protected void method4()
                {
                    System.out.println("subclass method4");
                }
                @Override
                void method5()
                {
                    System.out.println("subclass method5");
                }
            }

            package overridefunction;
            public class Demo 
            {
                public static void main(String[] args) 
                {
                    SubClass mSubClass = new SubClass();
                    mSubClass.method1();
                }
            }

            subclass method1
            superclass method1
            subclass method2
            superclass method3
            subclass method4
            subclass method5

Decode JSON with unknown structure

package main

import "encoding/json"

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

https://play.golang.org/p/o8ZwvgsQmoO

Send PHP variable to javascript function

Just write:

<script>
    var my_variable_name = "<?php echo $php_string; ?>";
</script>

Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.

HTTP Status 405 - Method Not Allowed Error for Rest API

You might be doing a PUT call for GET operation Please check once

Use .htaccess to redirect HTTP to HTTPs

I found all solutions listed on this Q&A did not work for me, unfortunately. What did work was:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^/?$ "https\:\/\/www\.example\.com\/" [R=301,L]
</IfModule>
# End Wordpress

Note, the above Wordpress rules are for Wordpress in multi user network mode. If your Wordpress is in single site mode, you would use:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^/?$ "https\:\/\/www\.example\.com\/" [R=301,L]
</IfModule>
# End Wordpress

Target WSGI script cannot be loaded as Python module

I had a similar problem with this error message in the logs:

Target WSGI script '/home/web2py/wsgihandler.py' cannot be loaded as Python module.

The solution was the deletion of an incorrect WSGIPythonHome directive (pointing to the application directory) from /etc/httpd/conf.d/wsgi.conf

I'm on RedHat using CentOS repositories.

Recommend following Graham Dumpleton's installation/configuration instructions. Testing configuration against the helloworld application showed me that mod_wsgi was working and the configuration was at fault.

However, the error message gave little clue as to what was wrong.

Intercept and override HTTP requests from WebView

You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest

Maybe this could help?

How do I upload a file with the JS fetch API?

The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

I'm quoting the code snippet for convenience:

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then((response) => response.json())
.then((result) => {
  console.log('Success:', result);
})
.catch((error) => {
  console.error('Error:', error);
});

Generate war file from tomcat webapp folder

Its just like creating a WAR file of your project, you can do it in several ways (from Eclipse, command line, maven).

If you want to do from command line, the command is

jar -cvf my_web_app.war * 

Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)

How to pass a value from one jsp to another jsp page?

Using Query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using Hidden variable .

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

you can send Using Session object.

   session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.

   int userid = session.getAttribute("userId"); 

How to allow only integers in a textbox?

You can use client-side validation:

<asp:textbox onkeydown="return (!(event.keyCode>=65) && event.keyCode!=32);" />

Get all table names of a particular database by SQL query?

In our Oracle DB (PL/SQL) below code working to get the list of all exists tables in our DB.

select * from tab;

and

select table_name from tabs;

both are working. let's try and find yours.

Displaying unicode symbols in HTML

Make sure that you actually save the file as UTF-8, alternatively use HTML entities (&#nnn;) for the special characters.

Call a function after previous function is complete

If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :

function function1 (someVariable) {
    var date = Date.now ();
    while (Date.now () - date < 2000);      // function1 takes some time to complete
    console.log (someVariable);
}
function function2 (someVariable) {
    console.log (someVariable);
}
function onClick () {
    window.setTimeout (() => { function1 ("This is function1"); }, 0);
    window.setTimeout (() => { function2 ("This is function2"); }, 0);
    console.log ("Click handled");  // To show that the function will return before both functions are executed
}
onClick ();

The output will be :

Click handled

...and after 2 seconds :

This is function 1
This is function 2

This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.

Notice that this as funny as it may the code difficult to understand...

Multi-dimensional arraylist or list in C#?

you just make a list of lists like so:

List<List<string>> results = new List<List<string>>();

and then it's just a matter of using the functionality you want

results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list

iPhone App Development on Ubuntu

There are two things I think you could try to develop iPhone applications.

  1. You can try the Aptana mobile wep app plugin for eclipse which is nice, although still in early stage. It comes with a emulator for running the applications so this could be helpful

  2. You can try cocoa

  3. (Extra) Here is a nice guide I found of guy who managed to get the iPhone SDK running in ubuntu, hope this help -_-. iPhone on Ubuntu

How to make Python script run as service?

I use this code to daemonize my applications. It allows you start/stop/restart the script using the following commands.

python myscript.py start
python myscript.py stop
python myscript.py restart

In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.

Here is a simple example to get your going. Simply move your code inside a class, and call it from the run function inside MyDeamon.

import sys
import time

from daemon import Daemon


class YourCode(object):
    def run(self):
        while True:
            time.sleep(1)


class MyDaemon(Daemon):
    def run(self):
        # Or simply merge your code with MyDaemon.
        your_code = YourCode()
        your_code.run()


if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

Upstart

If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf

start on started sshd
stop on runlevel [!2345]

exec /usr/bin/python /opt/my_service.py
respawn

You can then use start/stop/restart to manage your service.

e.g.

start my-service
stop my-service
restart my-service

A more detailed example of working with upstart is available here.

Systemd

If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

declare:

final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

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

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            imgView.setImageBitmap(selectedBitmap);
        }
    }
}

It is pretty easy for me to implement and also shows darken areas.

Where can I download JSTL jar

Visit Here to get your required jar files of JSTL.

and to get any of your required jar files visit HERE

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

it is working in my google chrome browser version 11.0.696.60

I created a simple page with no other items just basic tags and no separate CSS file and got an image

this is what i setup:

<div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div>

I put an id just in case there was a hidden id tag and it works

Center a position:fixed element

I used vw (viewport width) and vh (viewport height). viewport is your entire screen. 100vw is your screens total width and 100vh is total height.

.class_name{
    width: 50vw;
    height: 50vh;
    border: 1px solid red;
    position: fixed;
    left: 25vw;top: 25vh;   
}

Display curl output in readable JSON format in Unix shell script

Motivation: You want to print prettify JSON response after curl command request.

Solution: json_pp - commandline tool that converts between some input and output formats (one of them is JSON). This program was copied from json_xs and modified. The default input format is json and the default output format is json with pretty option.

Synposis: json_pp [-v] [-f from_format] [-t to_format] [-json_opt options_to_json1[,options_to_json2[,...]]]

Formula: <someCommand> | json_pp

Example:

Request

curl -X https://jsonplaceholder.typicode.com/todos/1 | json_pp 

Response

{
   "completed" : false,
   "id" : 1,
   "title" : "delectus aut autem",
   "userId" : 1
}

Slide right to left?

I've done it this way:

var btn_width = btn.width();
btn.width(0);
btn.show().animate({width: btn_width}, {duration: 500});

Note, that node "btn" should be hidden before animation, and you might also need to set "position: absolute" to it.

Need to remove href values when printing in Chrome

If you use the following CSS

<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css"    />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />

just change it into the following style by adding media="screen"

<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />

I think it will work.

the former answers like

    @media print {
  a[href]:after {
    content: none !important;
  }
}

were not worked well in the chrome browse.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

In case someone comes across this and is looking for these settings (like I was)

You have to

  1. On the left hand side, click "+Add Product" and select "Facebook Login" (it was at the top for me)
  2. See the new settings available on the left hand side
  3. You will now have these OAuth settings on that "Product Settings"

enter image description here

Additional Info: Make sure to add the Callback URL like http://localhost:3000 to the Valid OAuth redirect URIs field on the settings page of Facebook Login

How to programmatically click a button in WPF?

As Greg D said, I think that an alternative to Automation to click a button using the MVVM pattern (click event raised and command executed) is to call the OnClick method using reflection:

typeof(System.Windows.Controls.Primitives.ButtonBase).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(button, new object[0]);

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

What is REST? Slightly confused

REST is an architectural style and a design for network-based software architectures.

REST concepts are referred to as resources. A representation of a resource must be stateless. It is represented via some media type. Some examples of media types include XML, JSON, and RDF. Resources are manipulated by components. Components request and manipulate resources via a standard uniform interface. In the case of HTTP, this interface consists of standard HTTP ops e.g. GET, PUT, POST, DELETE.

REST is typically used over HTTP, primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles. REST however is not tied to any specific protocol.

Fundamental REST Principles

Client-Server Communication

Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in principle.

Stateless

Each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.

Cacheable

Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.

Uniform Interface

All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!

The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.

See this blog post on REST Design Principals for more details on REST and the above principles.

Call Jquery function

calling a function is simple ..

 myFunction();

so your code will be something like..

 $(function(){
     $('#elementID').click(function(){
         myFuntion();  //this will call your function
    });
 });

  $(function(){
     $('#elementID').click( myFuntion );

 });

or with some condition

if(something){
   myFunction();  //this will call your function
}

Opening a CHM file produces: "navigation to the webpage was canceled"

Summary

Microsoft Security Updates 896358 & 840315 block display of CHM file contents when opened from a network drive (or a UNC path). This is Windows' attempt to stop attack vectors for viruses/malware from infecting your computer and has blocked out the .chm file that draw data over the "InfoTech" protocol, which this chm file uses.

Microsoft's summary of the problem: http://support.microsoft.com/kb/896054

Solutions

  1. If you are using Windows Server 2008, Windows 7, windows has created a quick fix. Right click the chm file, and you will get the "yourfile.chm Properties" dialog box, at the bottom, a button called "Unblock" appears. Click Unblock and press OK, and try to open the chm file again, it works correctly. This option is not available for earlier versions of Windows before WindowsXP (SP3).

  2. Solve the problem by moving your chm file OFF the network drive. You may be unaware you are using a network drive, double check now: Right click your .chm file, click properties and look at the "location" field. If it starts with two backslashes like this: \\epicserver\blah\, then you are using a networked drive. So to fix it, Copy the chm file, and paste it into a local drive, like C:\ or E:. Then try to reopen the chm file, windows does not freak out.

  3. Last resort, if you can't copy/move the file off the networked drive. If you must open it where it sits, and you are using a lesser version of windows like XP, Vista, ME or other, you will have to manually tell Windows not to freak out over this .chm file. HHReg (HTML Help Registration Utility) Utility Automates this Task. Basically you download the HHReg utility, load your .chm file, press OK, and it will create the necessary registry keys to tell Windows not to block it. For more info: http://www.winhelponline.com/blog/fix-cannot-view-chm-files-network-xp-2003-vista/

Windows 8 or 10? --> Upgrade to Windows XP.

Location for session files in Apache/PHP

If unsure of compiled default for session.save_path, look at the pertinent php.ini.
Normally, this will show the commented out default value.

Ubuntu/Debian old/new php.ini locations:
Older php5 with Apache: /etc/php5/apache2/php.ini
Older php5 with NGINX+FPM: /etc/php5/fpm/php.ini
Ubuntu 16+ with Apache: /etc/php/*/apache2/php.ini *
Ubuntu 16+ with NGINX+FPM - /etc/php/*/fpm/php.ini *

* /*/ = the current PHP version(s) installed on system.

To show the PHP version in use under Apache:

$ a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+"

7.3

Since PHP 7.3 is the version running for this example, you would use that for the php.ini:

$ grep "session.save_path" /etc/php/7.3/apache2/php.ini

;session.save_path = "/var/lib/php/sessions"

Or, combined one-liner:

$ APACHEPHPVER=$(a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+") \ && grep ";session.save_path" /etc/php/${APACHEPHPVER}/apache2/php.ini

Result:

;session.save_path = "/var/lib/php/sessions"


Or, use PHP itself to grab the value using the "cli" environment (see NOTE below):

$ php -r 'echo session_save_path() . "\n";'
/var/lib/php/sessions
$

These will also work:

php -i | grep session.save_path

php -r 'echo phpinfo();' | grep session.save_path

NOTE:

The 'cli' (command line) version of php.ini normally has the same default values as the Apache2/FPM versions (at least as far as the session.save_path). You could also use a similar command to echo the web server's current PHP module settings to a webpage and use wget/curl to grab the info. There are many posts regarding phpinfo() use in this regard. But, it is quicker to just use the PHP interface or grep for it in the correct php.ini to show it's default value.

EDIT: Per @aesede comment -> Added php -i. Thanks

Creating a new user and password with Ansible

Well I'am totally late to party :) I had the need for ansible play that creates multiple local users with randoms passwords. This what I came up with, used some of examples from top and put them together with some changes.

create-user-with-password.yml

---
# create_user playbook

- hosts: all
  become: True
  user: root
  vars:
#Create following user
   users:
    - test24
    - test25
#with group
   group: wheel
  roles:
    - create-user-with-password

/roles/create-user-with-password/tasks/main.yml

- name: Generate password for new user
  local_action: shell pwgen -s -N 1 20
  register: user_password
  with_items: "{{ users }}"
  run_once: true

- name: Generate encrypted password
  local_action: shell python -c 'import crypt; print(crypt.crypt( "{{ item.stdout }}", crypt.mksalt(crypt.METHOD_SHA512)))'
  register: encrypted_user_password
  with_items: "{{ user_password.results }}"
  run_once: true

- name: Create new user with group
  user:
    name: "{{ item }}"
    groups: "{{ group }}"
    shell: /bin/bash
    append: yes
    createhome: yes
    comment: 'Created with ansible'
  with_items:
    - "{{ users }}"
  register: user_created

- name: Update user Passwords
  user:
    name: '{{ item.0 }}'
    password: '{{ item.1.stdout }}'
  with_together:
    - "{{ users }}"
    - "{{ encrypted_user_password.results }}"
  when: user_created.changed

- name: Force user to change the password at first login
  shell: chage -d 0 "{{ item }}"
  with_items:
    - "{{ users }}"
  when: user_created.changed

- name: Save Passwords Locally
  become: no
  local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
  with_items: "{{ user_password.results }}"
  when: user_created.changed

Playing m3u8 Files with HTML Video Tag

Adding to ben.bourdin answer, you can at least in any HTML based application, check if the browser supports HLS in its video element:

Let´s assume that your video element ID is "myVideo", then through javascript you can use the "canPlayType" function (http://www.w3schools.com/tags/av_met_canplaytype.asp)

var videoElement = document.getElementById("myVideo");
if(videoElement.canPlayType('application/vnd.apple.mpegurl') === "probably" || videoElement.canPlayType('application/vnd.apple.mpegurl') === "maybe"){
    //Actions like playing the .m3u8 content
}
else{
    //Actions like playing another video type
}

The canPlayType function, returns:

"" when there is no support for the specified audio/video type

"maybe" when the browser might support the specified audio/video type

"probably" when it most likely supports the specified audio/video type (you can use just this value in the validation to be more sure that your browser supports the specified type)

Hope this help :)

Best regards!

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

If you are to format a system_clock::time_point in the format of numpy datetime64, you could use:

std::string format_time_point(system_clock::time_point point)
{
    static_assert(system_clock::time_point::period::den == 1000000000 && system_clock::time_point::period::num == 1);
    std::string out(29, '0');
    char* buf = &out[0];
    std::time_t now_c = system_clock::to_time_t(point);
    std::strftime(buf, 21, "%Y-%m-%dT%H:%M:%S.", std::localtime(&now_c));
    sprintf(buf+20, "%09ld", point.time_since_epoch().count() % 1000000000);
    return out;
}

sample output: 2019-11-19T17:59:58.425802666

Java Delegates?

It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:

private interface SingleFunc {
    void printMe();
}

public static void main(String[] args) {
    SingleFunc sf = () -> {
        System.out.println("Hello, I am a simple single func.");
    };
    SingleFunc sfComplex = () -> {
        System.out.println("Hello, I am a COMPLEX single func.");
    };
    delegate(sf);
    delegate(sfComplex);
}

private static void delegate(SingleFunc f) {
    f.printMe();
}

Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.

Python: Get HTTP headers from urllib2.urlopen call?

Actually, it appears that urllib2 can do an HTTP HEAD request.

The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.

Here's my take on it:

import urllib2

# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"

myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)

try:
    response = urllib2.urlopen(request)
    response_headers = response.info()

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response_headers.dict

except urllib2.HTTPError, e:
    # Prints the HTTP Status code of the response but only if there was a 
    # problem.
    print ("Error code: %s" % e.code)

If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.

This is the HTTP request and response from the code above, as captured by Wireshark:

HEAD /doFeT HTTP/1.1
Accept-Encoding: identity
Host: bit.ly
Connection: close
User-Agent: Python-urllib/2.7

HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 19 Feb 2012 13:20:56 GMT
Content-Type: text/html; charset=utf-8
Cache-control: private; max-age=90
Location: http://www.kidsidebyside.org/?p=445
MIME-Version: 1.0
Content-Length: 127
Connection: close
Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly

However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.

The request above involves a redirect. Here is request to the destination, as captured by Wireshark:

GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Accept-Encoding: identity
Host: www.kidsidebyside.org
Connection: close
User-Agent: Python-urllib/2.7

An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:

import httplib2

url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()

try:
    response, content = http_interface.request(url, method="HEAD")
    print ("Response status: %d - %s" % (response.status, response.reason))

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response.__dict__

except httplib2.ServerNotFoundError, e:
    print (e.message)

This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.

Here's the first request:

HEAD /doFeT HTTP/1.1
Host: bit.ly
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

Here's the second request, to the destination:

HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Host: www.kidsidebyside.org
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

How to disable button in React.js

just Add:

<button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>

Git refusing to merge unrelated histories on rebase

I struggled with this as well, but I managed to find a workaround.

When you run into the error above, just cherry-pick the merge commit and then continue the rebase:

git cherry-pick -m 1 1234deadbeef1234deadbeef
git rebase --continue

Return content with IHttpActionResult for non-OK response

A more detailed example with support of HTTP code not defined in C# HttpStatusCode.

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        HttpStatusCode codeNotDefined = (HttpStatusCode)429;
        return Content(codeNotDefined, "message to be sent in response body");
    }
}

Content is a virtual method defined in abstract class ApiController, the base of the controller. See the declaration as below:

protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

How to check if an integer is in a given range?

I think

if (0 < i && i < 100) 

is more elegant. Looks like maths equation.

If you are looking for something special you can try:

Math.max(0, i) == Math.min(i, 100)

at least it uses library.

Getting value of HTML Checkbox from onclick/onchange events

For React.js, you can do this with more readable code. Hope it helps.

handleCheckboxChange(e) {
  console.log('value of checkbox : ', e.target.checked);
}
render() {
  return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}

Add custom buttons on Slick Carousel

This worked for me when a lot of these other items did not:

.slick-prev:before {
  content: url('your-arrow.png');
}
.slick-next:before {
  content: url('your-arrow.png');
}

What data type to use for money in Java?

For simple case (one currency) it'is enough int/long. Keep money in cents (...) or hundredth / thousandth of cents (any precision you need with fixed divider)

WPF Timer Like C# Timer

The usual WPF timer is the DispatcherTimer, which is not a control but used in code. It basically works the same way like the WinForms timer:

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();


private void dispatcherTimer_Tick(object sender, EventArgs e)
{
  // code goes here
}

More on the DispatcherTimer can be found here

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

How to perform case-insensitive sorting in JavaScript?

The other answers assume that the array contains strings. My method is better, because it will work even if the array contains null, undefined, or other non-strings.

var notdefined;
var myarray = ['a', 'c', null, notdefined, 'nulk', 'BYE', 'nulm'];

myarray.sort(ignoreCase);

alert(JSON.stringify(myarray));    // show the result

function ignoreCase(a,b) {
    return (''+a).toUpperCase() < (''+b).toUpperCase() ? -1 : 1;
}

The null will be sorted between 'nulk' and 'nulm'. But the undefined will be always sorted last.

JPA OneToMany not deleting child

As explained, it is not possible to do what I want with JPA, so I employed the hibernate.cascade annotation, with this, the relevant code in the Parent class now looks like this:

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, mappedBy = "parent")
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE,
            org.hibernate.annotations.CascadeType.DELETE,
            org.hibernate.annotations.CascadeType.MERGE,
            org.hibernate.annotations.CascadeType.PERSIST,
            org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private Set<Child> childs = new HashSet<Child>();

I could not simple use 'ALL' as this would have deleted the parent as well.

python - if not in list

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Following command resolved my issue:

sudo chown -R _mysql:mysql /usr/local/var/mysql

sudo mysql.server start

gcloud command not found - while installing Google Cloud SDK

You have to add the command to the path

Run

brew info --cask google-cloud-sdk

and find the lines to append to ~/.zshrc

The lines to append can be obtained from the output of the previous command. For zsh users, It should be some like these:

export CLOUDSDK_PYTHON="/usr/local/opt/[email protected]/libexec/bin/python"
source "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/path.zsh.inc"
source "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc"

(or choose the proper ones from the command output depending un the Shell you are using)

Updating an object with setState in React

You can try with this: (Note: name of input tag === field of object)

<input name="myField" type="text" 
      value={this.state.myObject.myField} 
     onChange={this.handleChangeInpForm}>
</input>

-----------------------------------------------------------
handleChangeInpForm = (e) => {
   let newObject = this.state.myObject;
   newObject[e.target.name] = e.target.value;
   this.setState({
     myObject: newObject 
   })
}

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

php how to go one level up on dirname(__FILE__)

I use this, if there is an absolute path (this is an example):

$img = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT']."/Folder-B/image1.jpg");

if there is a picture to show, this is enough:

echo("<img src='/Folder-B/image1.jpg'>");

JavaScript associative array to JSON

Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).

If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:

> AssocArray.length
0

What is often referred to as "associative array" is actually just an object in JS:

var AssocArray = {};  // <- initialize an object, not an array
AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"

Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

Twitter-Bootstrap-2 logo image on top of navbar

Overwrite the brand class, either in the bootstrap.css or a new CSS file, as below -

.brand
{
  background: url(images/logo.png) no-repeat left center;
  height: 20px;
  width: 100px;
}

and your html should look like -

<div class="container-fluid">
  <a class="brand" href="index.html"></a>
</div>

Count elements with jQuery

try this:

var count_element = $('.element').length

How do I loop through or enumerate a JavaScript object?

_x000D_
_x000D_
    var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},_x000D_
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]_x000D_
for(var value in p) {_x000D_
    for (var key in value) {_x000D_
        if (p.hasOwnProperty(key)) {_x000D_
            console.log(key + " -> " + p[key]);_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Pass Parameter to Gulp Task

@Ethan's answer would completely work. From my experience, the more node way is to use environment variables. It's a standard way to configure programs deployed on hosting platforms (e.g. Heroku or Dokku).

To pass the parameter from the command line, do it like this:

Development: gulp dev

Production: NODE_ENV=production gulp dev

The syntax is different, but very Unix, and it's compatible with Heroku, Dokku, etc.

You can access the variable in your code at process.env.NODE_ENV

MYAPP=something_else gulp dev

would set

process.env.MYAPP === 'something_else'

This answer might give you some other ideas.

How do I use 3DES encryption/decryption in Java?

Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64:

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

public class TrippleDes {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public TrippleDes() throws Exception {
        myEncryptionKey = "ThisIsSpartaThisIsSparta";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }


    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedText = Base64.decodeBase64(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }


    public static void main(String args []) throws Exception
    {
        TrippleDes td= new TrippleDes();

        String target="imparator";
        String encrypted=td.encrypt(target);
        String decrypted=td.decrypt(encrypted);

        System.out.println("String To Encrypt: "+ target);
        System.out.println("Encrypted String:" + encrypted);
        System.out.println("Decrypted String:" + decrypted);

    }

}

Running the above program results with the following output:

String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator

How do I open a new window using jQuery?

This works:

myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");

Understanding timedelta

why do I have to pass seconds = uptime to timedelta

Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int is superfluous as they could also accept floats.

and why does the string casting works so nicely that I get HH:MM:SS ?

It's not the typecasting that formats, is the internal __str__ method of the object. In fact you will achieve the same result if you write:

print datetime.timedelta(seconds=int(uptime))

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

There seems to be a confusion between "Parent" and "Owner". If you open a form as MDI-form, i.e. imbedded inside another form, then this surrounding form is the Parent. The form property StartPosition with the value FormStartPosition.CenterParent refers to this one. The parameter you may pass to the Show method is the Owner, not the Parent! This is why frm.StartPosition = FormStartPosition.CenterParent does not work as you may expect.

The following code placed in a form will center it with respect to its owner with some offset, if its StartPosition is set to Manual. The small offset opens the forms in a tiled manner. This is an advantage if the owner and the owned form have the same size or if you open several owned forms.

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    if (Owner != null && StartPosition == FormStartPosition.Manual) {
        int offset = Owner.OwnedForms.Length * 38;  // approx. 10mm
        Point p = new Point(Owner.Left + Owner.Width / 2 - Width / 2 + offset, Owner.Top + Owner.Height / 2 - Height / 2 + offset);
        this.Location = p;
    }
}

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

Browser: Identifier X has already been declared

I had a very close issue but in my case, it was Identifier 'e' has already been declared.

In my case caused because of using try {} catch (e) { var e = ... } where letter e is generated via minifier (uglifier).

So better solution could be use catch(ex){} (ex as an Excemption)

Hope somebody who searched with the similar question could find this question helpful.

jQuery animate margin top

As said marginTop - not MarginTop.

Also why not animate it back? :)

See: http://jsfiddle.net/kX7b6/2/

how to use html2canvas and jspdf to export to pdf in a proper and simple way

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

SQL Query to add a new column after an existing column in SQL Server 2005

ALTER won't do it because column order does not matter for storage or querying

If SQL Server, you'd have to use the SSMS Table Designer to arrange your columns, which can then generate a script which drops and recreates the table

Edit Jun 2013

Cross link to my answer here: Performance / Space implications when ordering SQL Server columns?

How to use Scanner to accept only valid int as input

Try this:

    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("^\\d+$");
        Scanner kb = new Scanner(System.in);
        int num1;
        int num2 = 0;
        String temp;
        Matcher numberMatcher;
        System.out.print("Enter number 1: ");
        try
        {
            num1 = kb.nextInt();
        }

        catch (java.util.InputMismatchException e)
        {
            System.out.println("Invalid Input");
            //
            return;
        }
        while(num2<num1)
        {
            System.out.print("Enter number 2: ");
            temp = kb.next();
            numberMatcher = p.matcher(temp);
            if (numberMatcher.matches())
            {
                num2 = Integer.parseInt(temp);
            }

            else
            {
                System.out.println("Invalid Number");
            }
        }
    }

You could try to parse the string into an int as well, but usually people try to avoid throwing exceptions.

What I have done is that I have defined a regular expression that defines a number, \d means a numeric digit. The + sign means that there has to be one or more numeric digits. The extra \ in front of the \d is because in java, the \ is a special character, so it has to be escaped.

CSS vertical-align: text-bottom;

Vertical align only works in some select cases. The easiest way to make it function is to set display: table in the parent element's CSS and display: table-cell; to the child element and then apply your vertical align attribute.

How to check Grants Permissions at Run-Time?

Check out the below library in git :

RuntimePermission

Implementation :

        allprojects {
            repositories {
                ...
                maven { url 'https://jitpack.io' }
            }
        }
        
        dependencies {
            implementation 'com.github.manoj140220:RuntimePermission:1.0.3'
        }
    
    
      
    
        new RuntimePermission({Current Class Object}, String[] , {ActvityContext});
          
          String[] : permission array.
          example  : String[] permissionArray = {Manifest.permission.CAMERA, Manifest.permission.BODY_SENSORS,...} 
    
    Implement : {PermissionNotify}
    
    interface notifier methods.
    
    @Override
    public void notifyPermissionGrant() {
        
    }
    
    @Override
    public void notifyPermissionDeny() {
         
    }

submitting a GET form with query string params and hidden params disappear

What you can do is using a simple foreach on the table containing the GET information. For example in php :

foreach ($_GET as $key => $value) {
    echo("<input type='hidden' name='$key' value='$value'/>");
}

Select NOT IN multiple columns

I'm not sure whether you think about:

select * from friend f
where not exists (
    select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)

it works only if id1 is related with id1 and id2 with id2 not both.

Get url without querystring

Try this:

urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))

from this: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye you'll get this: mypage.aspx

How to execute a function when page has fully loaded?

the window.onload event will fire when everything is loaded, including images etc.

You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.

Is there a decorator to simply cache function return values?

There is fastcache, which is "C implementation of Python 3 functools.lru_cache. Provides speedup of 10-30x over standard library."

Same as chosen answer, just different import:

from fastcache import lru_cache
@lru_cache(maxsize=128, typed=False)
def f(a, b):
    pass

Also, it comes installed in Anaconda, unlike functools which needs to be installed.

Passing headers with axios POST request

You can also use interceptors to pass the headers

It can save you a lot of code

axios.interceptors.request.use(config => {
  if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

  const accessToken = AuthService.getAccessToken();
  if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;

  return config;
});

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

If you really want an iterator-free solution, you can use numpy and its array round function.

import numpy as np
myList = list(np.around(np.array(myList),2))

Matplotlib tight_layout() doesn't take into account figure suptitle

I had a similar issue that cropped up when using tight_layout for a very large grid of plots (more than 200 subplots) and rendering in a jupyter notebook. I made a quick solution that always places your suptitle at a certain distance above your top subplot:

import matplotlib.pyplot as plt

n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)

#make plots ...

# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)

For variably-sized subplots, you can still use this method to get the top of the topmost subplot, then manually define an additional amount to add to the suptitle.

What are the complexity guarantees of the standard containers?

Another quick lookup table is available at this github page

Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this

Service will not start: error 1067: the process terminated unexpectedly

This error message appears if the Windows service launcher has quit immediately after being started. This problem usually happens because the license key has not been correctly deployed(license.txt file in the license folder). If service is not strtign with correct key, just put incorrect key and try to start. Once started, place the correct key, it will work.

How to get a Static property with Reflection

myType.GetProperties(BindingFlags.Public | BindingFlags.Static |  BindingFlags.FlattenHierarchy);

This will return all static properties in static base class or a particular type and probably the child as well.

How can I print a circular structure in a JSON-like format?

just do

npm i --save circular-json

then in your js file

const CircularJSON = require('circular-json');
...
const json = CircularJSON.stringify(obj);

https://github.com/WebReflection/circular-json

NOTE: I have nothing to do with this package. But I do use it for this.

Update 2020

Please note CircularJSON is in maintenance only and flatted is its successor.

SQL Query to find the last day of the month

select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-0, -1) LastDate

Should you always favor xrange() over range()?

Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)

What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.

Align Bootstrap Navigation to Center

Try this css

.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
    content: " ";
    display: table-cell;
}

ul.nav {
    float: none;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    width: 240px;
}

Is there a MessageBox equivalent in WPF?

The WPF equivalent would be the System.Windows.MessageBox. It has a quite similar interface, but uses other enumerations for parameters and return value.

How to export the Html Tables data into PDF using Jspdf

A good option is AutoTable(a Table plugin for jsPDF), it includes themes, rowspan, colspan, extract data from html, works with json, you can also personalize your headers and make them horizontals. Here is a demo.

enter image description here

Bundle ID Suffix? What is it?

If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.

In Bundle ID Suffix you should write full name of bundle ID.

Example:

Bundle ID suffix = thebestapp (NOT CORRECT!!!!)

Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)

The reason for this is explained in the Developer Portal:

The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g. ABCDE12345), and an App ID Suffix (a Bundle ID search string, e.g. com.mycompany.appname). [emphasis added]

So in this case the suffix is the full string com.awesomeapps.thebestapp.

Change input text border color without changing its height

use this, it won't effect height:

<input type="text" style="border:1px solid #ff0000" />

How can I use tabs for indentation in IntelliJ IDEA?

To expand on @Dmitiri Algazin 's answer: settings for individual languages are overridden by the general setting

Preferences -> Code Style -> Detect and use existing file indents for editing

So if you are wondering why your new settings are being ignored after changing your settings for a specific language, there is a chance this checkbox is ticked.

As a side note; changing any default settings automamagically creates a settings profile clone (i.e. Default(1)) which I assume is in place so that the default IDE settings are never overwritten.

It is a little confusing at first, really, whether editing Default settings or Project Settings is going to have any effect on your project, since you can select Default from the drop down menu and then edit from there.

If you don't want to keep seeing random clones of Default populating your settings profiles, edit the Project Settings directly.

Current date without time

This should work:

string datetime = DateTime.Today.ToString();

HTML5 Video Autoplay not working correctly

Mobile browsers generally ignore this attribute to prevent consuming data until user explicitly starts the download.

UPDATE: newer version of mobile browser on Android and iOS do support autoplay function. But it only works if the video is muted or has no audio channel:

Some additional info: https://webkit.org/blog/6784/new-video-policies-for-ios/

What does it mean to have an index to scalar variable error? python

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

Using Python's os.path, how do I go up one directory?

From the current file path you could use:

os.path.join(os.path.dirname(__file__),'..','img','banner.png')

How do I check if a string contains a specific word?

You could use regular expressions as it's better for word matching compared to strpos, as mentioned by other users. A strpos check for are will also return true for strings such as: fare, care, stare, etc. These unintended matches can simply be avoided in regular expression by using word boundaries.

A simple match for are could look something like this:

$a = 'How are you?';

if (preg_match('/\bare\b/', $a)) {
    echo 'true';
}

On the performance side, strpos is about three times faster. When I did one million compares at once, it took preg_match 1.5 seconds to finish and for strpos it took 0.5 seconds.

Edit: In order to search any part of the string, not just word by word, I would recommend using a regular expression like

$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
    echo 'true';
}

The i at the end of regular expression changes regular expression to be case-insensitive, if you do not want that, you can leave it out.

Now, this can be quite problematic in some cases as the $search string isn't sanitized in any way, I mean, it might not pass the check in some cases as if $search is a user input they can add some string that might behave like some different regular expression...

Also, here's a great tool for testing and seeing explanations of various regular expressions Regex101

To combine both sets of functionality into a single multi-purpose function (including with selectable case sensitivity), you could use something like this:

function FindString($needle,$haystack,$i,$word)
{   // $i should be "" or "i" for case insensitive
    if (strtoupper($word)=="W")
    {   // if $word is "W" then word search instead of string in string search.
        if (preg_match("/\b{$needle}\b/{$i}", $haystack)) 
        {
            return true;
        }
    }
    else
    {
        if(preg_match("/{$needle}/{$i}", $haystack)) 
        {
            return true;
        }
    }
    return false;
    // Put quotes around true and false above to return them as strings instead of as bools/ints.
}

One more thing to take in mind, is that \b will not work in different languages other than english.

The explanation for this and the solution is taken from here:

\b represents the beginning or end of a word (Word Boundary). This regex would match apple in an apple pie, but wouldn’t match apple in pineapple, applecarts or bakeapples.

How about “café”? How can we extract the word “café” in regex? Actually, \bcafé\b wouldn’t work. Why? Because “café” contains non-ASCII character: é. \b can’t be simply used with Unicode such as ??????, ??, ????? and .

When you want to extract Unicode characters, you should directly define characters which represent word boundaries.

The answer: (?<=[\s,.:;"']|^)UNICODE_WORD(?=[\s,.:;"']|$)

So in order to use the answer in PHP, you can use this function:

function contains($str, array $arr) {
    // Works in Hebrew and any other unicode characters
    // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
    // Thanks https://www.phpliveregex.com/
    if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
}

And if you want to search for array of words, you can use this:

function arrayContainsWord($str, array $arr)
{
    foreach ($arr as $word) {
        // Works in Hebrew and any other unicode characters
        // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
        // Thanks https://www.phpliveregex.com/
        if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
    }
    return false;
}

As of PHP 8.0.0 you can now use str_contains

<?php
    if (str_contains('abc', '')) {
        echo "Checking the existence of the empty string will always 
        return true";
    }

New features in java 7

I think ForkJoinPool and related enhancement to Executor Framework is an important addition in Java 7.

Checking version of angular-cli that's installed?

Simply just enter any of below in the command line,

ng --version OR ng v OR ng -v

The Output would be like,

Screenshot

Not only the Angular version but also the Node version is also mentioned there. I use Angular 6.

Nested jQuery.each() - continue/break

Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".

What is the correct format to use for Date/Time in an XML file

The XmlConvert class provides these kinds of facilities. About DateTimes, in particular, be careful about obsolete methods. See also: https://stackoverflow.com/a/7457718/1288109

How to remove duplicate white spaces in string using Java?

Though it is too late, I have found a better solution (that works for me) that will replace all consecutive same type white spaces with one white space of its type. That is:

   Hello!\n\n\nMy    World  

will be

 Hello!\nMy World 

Notice there are still leading and trailing white spaces. So my complete solution is:

str = str.trim().replaceAll("(\\s)+", "$1"));

Here, trim() replaces all leading and trailing white space strings with "". (\\s) is for capturing \\s (that is white spaces such as ' ', '\n', '\t') in group #1. + sign is for matching 1 or more preceding token. So (\\s)+ can be consecutive characters (1 or more) among any single white space characters (' ', '\n' or '\t'). $1 is for replacing the matching strings with the group #1 string (which only contains 1 white space character) of the matching type (that is the single white space character which has matched). The above solution will change like this:

   Hello!\n\n\nMy    World  

will be

Hello!\nMy World

I have not found my above solution here so I have posted it.

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Context provides information about the Actvity or Application to newly created components.

Relevant Context should be provided to newly created components (whether application context or activity context)

Since Activity is a subclass of Context, one can use this to get that activity's context

How to convert a HTMLElement to a string

There's a tagName property, and a attributes property as well:

var element = document.getElementById("wtv");
var openTag = "<"+element.tagName;
for (var i = 0; i < element.attributes.length; i++) {
    var attrib = element.attributes[i];
    openTag += " "+attrib.name + "=" + attrib.value;
}
openTag += ">";
alert(openTag);

See also How to iterate through all attributes in an HTML element? (I did!)

To get the contents between the open and close tags you could probably use innerHTML if you don't want to iterate over all the child elements...

alert(element.innerHTML);

... and then get the close tag again with tagName.

var closeTag = "</"+element.tagName+">";
alert(closeTag);

What is the difference between Java RMI and RPC?

1. Approach:

RMI uses an object-oriented paradigm where the user needs to know the object and the method of the object he needs to invoke.

RPC doesn't deal with objects. Rather, it calls specific subroutines that are already established.

2. Working:

With RPC, you get a procedure call that looks pretty much like a local call. RPC handles the complexities involved with passing the call from local to the remote computer.

RMI does the very same thing, but RMI passes a reference to the object and the method that is being called.

RMI = RPC + Object-orientation

3. Better one:

RMI is a better approach compared to RPC, especially with larger programs as it provides a cleaner code that is easier to identify if something goes wrong.

4. System Examples:

RPC Systems: SUN RPC, DCE RPC

RMI Systems: Java RMI, CORBA, Microsoft DCOM/COM+, SOAP(Simple Object Access Protocol)

how to convert a string to date in mysql?

STR_TO_DATE('12/31/2011', '%m/%d/%Y')

Stop form from submitting , Using Jquery

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

I want it to be allowed HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

how to permit an array with strong parameters

If you want to permit an array of hashes(or an array of objects from the perspective of JSON)

params.permit(:foo, array: [:key1, :key2])

2 points to notice here:

  1. array should be the last argument of the permit method.
  2. you should specify keys of the hash in the array, otherwise you will get an error Unpermitted parameter: array, which is very difficult to debug in this case.

Requery a subform from another form?

You must use the name of the subform control, not the name of the subform, though these are often the same:

 Forms![MainForm]![subform control name Name].Form.Requery

Or, if you are on the main form:

 Me.[subform control name Name].Form.Requery

More Info: http://www.mvps.org/access/forms/frm0031.htm

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Add back button to action bar

There are two ways to approach this.

Option 1: Update the Android Manifest If the settings Activity is always called from the same activity, you can make the relationship in the Android Manifest. Android will automagically show the 'back' button in the ActionBar

<activity
    android:name=".SettingsActivity"
    android:label="Setting Activity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.example.MainActivity" />
</activity>

Option 2: Change a setting for the ActionBar If you don't know which Activity will call the Settings Activity, you can create it like this. First in your activity that extends ActionBarActivity (Make sure your @imports match the level of compatibility you are looking for).

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings_test);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Then, detect the 'back button' press and tell Android to close the currently open Activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

That should do it!

SQL Server copy all rows from one table into another i.e duplicate table

select * into x_history from your_table_here;
truncate table your_table_here;

How to format strings in Java

If you choose not to use String.format, the other option is the + binary operator

String str = "Step " + a + " of " + b;

This is the equivalent of

new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2));

Whichever you use is your choice. StringBuilder is faster, but the speed difference is marginal. I prefer to use the + operator (which does a StringBuilder.append(String.valueOf(X))) and find it easier to read.

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

For the warning by warning case, It's wise to restore it to default at some point, since you are doing it on a case by case basis.

#pragma warning(disable: 4996) /* Disable deprecation */
// Code that causes it goes here
#pragma warning(default: 4996) /* Restore default */

Is it possible to decompile an Android .apk file?

Download this jadx tool https://sourceforge.net/projects/jadx/files/

Unzip it and than in lib folder run jadx-gui-0.6.1.jar file now browse your apk file. It's done. Automatically apk will decompile and save it by pressing save button. Hope it will work for you. Thanks

Iterating over dictionaries using 'for' loops

Iterating over dictionaries using 'for' loops

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    ...

How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?

It's not just for loops. The important word here is "iterating".

A dictionary is a mapping of keys to values:

d = {'x': 1, 'y': 2, 'z': 3} 

Any time we iterate over it, we iterate over the keys. The variable name key is only intended to be descriptive - and it is quite apt for the purpose.

This happens in a list comprehension:

>>> [k for k in d]
['x', 'y', 'z']

It happens when we pass the dictionary to list (or any other collection type object):

>>> list(d)
['x', 'y', 'z']

The way Python iterates is, in a context where it needs to, it calls the __iter__ method of the object (in this case the dictionary) which returns an iterator (in this case, a keyiterator object):

>>> d.__iter__()
<dict_keyiterator object at 0x7fb1747bee08>

We shouldn't use these special methods ourselves, instead, use the respective builtin function to call it, iter:

>>> key_iterator = iter(d)
>>> key_iterator
<dict_keyiterator object at 0x7fb172fa9188>

Iterators have a __next__ method - but we call it with the builtin function, next:

>>> next(key_iterator)
'x'
>>> next(key_iterator)
'y'
>>> next(key_iterator)
'z'
>>> next(key_iterator)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

When an iterator is exhausted, it raises StopIteration. This is how Python knows to exit a for loop, or a list comprehension, or a generator expression, or any other iterative context. Once an iterator raises StopIteration it will always raise it - if you want to iterate again, you need a new one.

>>> list(key_iterator)
[]
>>> new_key_iterator = iter(d)
>>> list(new_key_iterator)
['x', 'y', 'z']

Returning to dicts

We've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:

If we change the variable name, we still get the keys. Let's try it:

>>> for each_key in d:
...     print(each_key, '=>', d[each_key])
... 
x => 1
y => 2
z => 3

If we want to iterate over the values, we need to use the .values method of dicts, or for both together, .items:

>>> list(d.values())
[1, 2, 3]
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]

In the example given, it would be more efficient to iterate over the items like this:

for a_key, corresponding_value in d.items():
    print(a_key, corresponding_value)

But for academic purposes, the question's example is just fine.

using extern template (C++11)

You should only use extern template to force the compiler to not instantiate a template when you know that it will be instantiated somewhere else. It is used to reduce compile time and object file size.

For example:

// header.h

template<typename T>
void ReallyBigFunction()
{
    // Body
}

// source1.cpp

#include "header.h"
void something1()
{
    ReallyBigFunction<int>();
}

// source2.cpp

#include "header.h"
void something2()
{
    ReallyBigFunction<int>();
}

This will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>()    // Compiled first time

source2.o
    void something2()
    void ReallyBigFunction<int>()    // Compiled second time

If both files are linked together, one void ReallyBigFunction<int>() will be discarded, resulting in wasted compile time and object file size.

To not waste compile time and object file size, there is an extern keyword which makes the compiler not compile a template function. You should use this if and only if you know it is used in the same binary somewhere else.

Changing source2.cpp to:

// source2.cpp

#include "header.h"
extern template void ReallyBigFunction<int>();
void something2()
{
    ReallyBigFunction<int>();
}

Will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>() // compiled just one time

source2.o
    void something2()
    // No ReallyBigFunction<int> here because of the extern

When both of these will be linked together, the second object file will just use the symbol from the first object file. No need for discard and no wasted compile time and object file size.

This should only be used within a project, like in times when you use a template like vector<int> multiple times, you should use extern in all but one source file.

This also applies to classes and function as one, and even template member functions.

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

React components names should be capitalized and custom hooks functions should start with the use keyword to identify as a react hook function.

So, capitalize your app components to App

How to display HTML in TextView?

If you use androidx.* classes in your project, you should use HtmlCompat.fromHtml(text, flag).

Source of the method is:

@NonNull
    public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(source, flags);
        }
        //noinspection deprecation
        return Html.fromHtml(source);
    }

It is better to use HtmlCompat.fromHtml than Html.fromHtml as there is less code- only one line of code, and it's recommended way to use it.

How to get the Mongo database specified in connection string in C#

The answer below is apparently obsolete now, but works with older drivers. See comments.

If you have the connection string you could also use MongoDatabase directly:

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

Converting integer to string in Python

There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.

To convert an object in string you use the str() function. It works with any object that has a method called __str__() defined. In fact

str(a)

is equivalent to

a.__str__()

The same if you want to convert something to int, float, etc.

How can I fill out a Python string with spaces?

Wouldn't it be more pythonic to use slicing?

For example, to pad a string with spaces on the right until it's 10 characters long:

>>> x = "string"    
>>> (x + " " * 10)[:10]   
'string    '

To pad it with spaces on the left until it's 15 characters long:

>>> (" " * 15 + x)[-15:]
'         string'

It requires knowing how long you want to pad to, of course, but it doesn't require measuring the length of the string you're starting with.

Add space between HTML elements only using CSS

add these rules to the parent container:

display: grid
grid-auto-flow: column
grid-column-gap: 10px

Good reference: https://cssreference.io/

Browser compatibility: https://gridbyexample.com/browsers/

Is "&#160;" a replacement of "&nbsp;"?

&#160; is the numeric reference for the entity reference &nbsp; — they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.

See the Wikipedia page for the non-breaking space.

Insert an item into sorted list in Python

This is the best way to append the list and insert values to sorted list:

 a = [] num = int(input('How many numbers: ')) for n in range(num):
     numbers = int(input('Enter values:'))
     a.append(numbers)

 b = sorted(a) print(b) c = int(input("enter value:")) for i in
 range(len(b)):
     if b[i] > c:
         index = i
         break d = b[:i] + [c] + b[i:] print(d)`

What are the benefits of using C# vs F# or F# vs C#?

  • F# Has Better Performance than C# in Math
  • You could use F# projects in the same solution with C# (and call from one to another)
  • F# is really good for complex algorithmic programming, financial and scientific applications
  • F# logically is really good for the parallel execution (it is easier to make F# code execute on parallel cores, than C#)

How do I install jmeter on a Mac?

I am also new to this.
I have followed this process to start the application in Mac:

  1. I downloaded apache-jmeter-3.3_src.zip from http://jmeter.apache.org/download_jmeter.cgi website.
  2. I extracted the files and then move to bin folder and then you can find a file named jmeter, this is an executable file. Right click on this and open with terminal and wait for 5 minutes, that's it.

Thank you, I hope this might help.

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

Submit HTML form on self page

You can leave action attribute blank. The form will automatically submit itself in the same page.

<form action="">

According to the w3c specification, action attribute must be non-empty valid url in general. There is also an explanation for some situations in which the action attribute may be left empty.

The action of an element is the value of the element’s formaction attribute, if the element is a Submit Button and has such an attribute, or the value of its form owner’s action attribute, if it has one, or else the empty string.

So they both still valid and works:

<form action="">
<form action="FULL_URL_STRING_OF_CURRENT_PAGE">

If you are sure your audience is using html5 browsers, you can even omit the action attribute:

<form>

How do I verify that a string only contains letters, numbers, underscores and dashes?

There are a variety of ways of achieving this goal, some are clearer than others. For each of my examples, 'True' means that the string passed is valid, 'False' means it contains invalid characters.

First of all, there's the naive approach:

import string
allowed = string.letters + string.digits + '_' + '-'

def check_naive(mystring):
    return all(c in allowed for c in mystring)

Then there's use of a regular expression, you can do this with re.match(). Note that '-' has to be at the end of the [] otherwise it will be used as a 'range' delimiter. Also note the $ which means 'end of string'. Other answers noted in this question use a special character class, '\w', I always prefer using an explicit character class range using [] because it is easier to understand without having to look up a quick reference guide, and easier to special-case.

import re
CHECK_RE = re.compile('[a-zA-Z0-9_-]+$')
def check_re(mystring):
    return CHECK_RE.match(mystring)

Another solution noted that you can do an inverse match with regular expressions, I've included that here now. Note that [^...] inverts the character class because the ^ is used:

CHECK_INV_RE = re.compile('[^a-zA-Z0-9_-]')
def check_inv_re(mystring):
   return not CHECK_INV_RE.search(mystring)

You can also do something tricky with the 'set' object. Have a look at this example, which removes from the original string all the characters that are allowed, leaving us with a set containing either a) nothing, or b) the offending characters from the string:

def check_set(mystring):
    return not set(mystring) - set(allowed)

How to fix Invalid AES key length?

You can verify the key length limit:

int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("MaxAllowedKeyLength=[" + maxKeyLen + "].");

The VMware Authorization Service is not running

You can fix this by starting the service manually.

  1. Type services in the Windows search bar.
  2. Open Services; scroll to the VMware Authorization Service (should be close to the bottom of the page)
  3. Double-click to open the Properties page of the service.
  4. Change the startup type to Automatic and then start the service. That way, the service will be started automatically every time you log in.

More detailed info can be found at Powering on a virtual machine fails with the error: The VMware Authorization Service is not running (1007131)

android.content.Context.getPackageName()' on a null object reference

For me the problem was that I was passing Activity to the constructor, not Context

public Adapter(Activity activity, List<MediaItem> items, boolean can) {
    mItems = items;
    canEdit = can;
    mActivity = activity;
}

and using this activity to getDefaultSharedPreferences(), so I changed the Activity to Context and I was still calling the Adapter constructor with MainActivity.this

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

If you are using Maven you may have both src/{main,test}/resources/META-INF/persistence.xml. This is a common setup: test your JPA code with h2 or Derby and deploy it with PostgreSQL or some other full DBMS. If you're using this pattern, do make sure the two files have different unit names, else some versions of the Persistence class will try to load BOTH (because of course your test-time CLASSPATH includes both classes and test-classes); this will cause conflicting definitions of the persistence unit, resulting in the dreaded annoying message that we all hate so much!

Worse: this may "work" with some older versions of e.g., Hibernate, but fail with current versions. Worth getting it right anyway...

Can I grep only the first n lines of a file?

The output of head -10 file can be piped to grep in order to accomplish this:

head -10 file | grep …

Using Perl:

perl -ne 'last if $. > 10; print if /pattern/' file

open link in iframe

<a href="YOUR_URL" target="_YOUR_IFRAME_NAME">LINK NAME</a>

How to get all count of mongoose model?

Background for the solution

As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count() is deprecated. Instead of using count(), the alternatives are the following:

Model.countDocuments(filterObject, callback)

Counts how many documents match the filter in a collection. Passing an empty object {} as filter executes a full collection scan. If the collection is large, the following method might be used.

Model.estimatedDocumentCount()

This model method estimates the number of documents in the MongoDB collection. This method is faster than the previous countDocuments(), because it uses collection metadata instead of going through the entire collection. However, as the method name suggests, and depending on db configuration, the result is an estimate as the metadata might not reflect the actual count of documents in a collection at the method execution moment.

Both methods return a mongoose query object, which can be executed in one of the following two ways. Use .exec() if you want to execute a query at a later time.

The solution

Option 1: Pass a callback function

For example, count all documents in a collection using .countDocuments():

someModel.countDocuments({}, function(err, docCount) {
    if (err) { return handleError(err) } //handle possible errors
    console.log(docCount)
    //and do some other fancy stuff
})

Or, count all documents in a collection having a certain name using .countDocuments():

someModel.countDocuments({ name: 'Snow' }, function(err, docCount) {
    //see other example
}

Option 2: Use .then()

A mongoose query has .then() so it’s “thenable”. This is for a convenience and query itself is not a promise.

For example, count all documents in a collection using .estimatedDocumentCount():

someModel
    .estimatedDocumentCount()
    .then(docCount => {
        console.log(docCount)
        //and do one super neat trick
    })
    .catch(err => {
        //handle possible errors
    })

Option 3: Use async/await

When using async/await approach, the recommended way is to use it with .exec() as it provides better stack traces.

const docCount = await someModel.countDocuments({}).exec();

Learning by stackoverflowing,

How can I programmatically check whether a keyboard is present in iOS app?

SwiftUI - Full Example

import SwiftUI

struct ContentView: View {
    
    @State private var text = defaultText
    
    @State private var isKeyboardShowing = false
    
    private static let defaultText = "write something..."
    
    private var gesture = TapGesture().onEnded({_ in
        UIApplication.shared.endEditing(true)
    })
    
    var body: some View {
        
        ZStack {
            Color.black
            
            VStack(alignment: .leading) {
                TextField("placeholder", text: $text)
                    .foregroundColor(.white)
                    .padding()
                    .background(Color.green)
            }
            
            .padding()
        }
        .edgesIgnoringSafeArea(.all)
        .onChange(of: isKeyboardShowing, perform: { (isShowing) in
            if isShowing {
                if text == Self.defaultText { text = "" }
            } else {
                if text == "" { text = Self.defaultText }
            }
        })
        .simultaneousGesture(gesture)
        .onReceive(NotificationCenter.default
                    .publisher(for: UIResponder.keyboardWillShowNotification), perform: { (value) in
                        isKeyboardShowing = true
                    })
        .onReceive(NotificationCenter.default
                    .publisher(for: UIResponder.keyboardWillHideNotification), perform: { (value) in
                        isKeyboardShowing = false
                    })
    }
}

extension UIApplication {
    func endEditing(_ force: Bool) {
        self.windows
            .filter{$0.isKeyWindow}
            .first?
            .endEditing(force)
    }
}

Remove a file from a Git repository without deleting it from the local filesystem

Above answers didn't work for me. I used filter-branch to remove all committed files.

Remove a file from a git repository with:

git filter-branch --tree-filter 'rm  file'

Remove a folder from a git repository with:

git filter-branch --tree-filter 'rm -rf directory'

This removes the directory or file from all the commits.

You can specify a commit by using:

git filter-branch --tree-filter 'rm -rf directory' HEAD

Or an range:

git filter-branch --tree-filter 'rm -rf vendor/gems' t49dse..HEAD

To push everything to remote, you can do:

git push origin master --force

How to reduce a huge excel file

I have worked extensively in Excel and have found the following 3 points very useful

Find if there are cells which apparently do not hold any data but Excel considers them to have data

You can find this by using the following property on a sheet

ActiveSheet.UsedRange.Rows.Count
ActiveSheet.UsedRange.Columns.Count

If this range is more than the cells on which you have data, delete the rest of the rows/columns

You will be surprised to see the amount of space it can free

Convert files to .xlsb format

XLSM format is to make Excel compliant with Open XML, but there are very few instances when we actually use the XML format of Excel. This reduces size by almost 50% if not more

Optimum way of storing information

For example if you have to save the stock price for around 10 years, and you need to save Open, High, Low, Close for a stock, this would result in (252*10) * (4) cells being used

Instead, of using separate columns for Open,High,Low,Close save them in a single column with a field separator Open:High:Low:Close

You can easily write a function to extract info from the single column whenever you want to, but it will free up almost 2/3rd space that you are currently taking up

Ignore case in Python strings

When something isn't supported well in the standard library, I always look for a PyPI package. With virtualization and the ubiquity of modern Linux distributions, I no longer avoid Python extensions. PyICU seems to fit the bill: https://stackoverflow.com/a/1098160/3461

There now is also an option that is pure python. It's well tested: https://github.com/jtauber/pyuca


Old answer:

I like the regular expression solution. Here's a function you can copy and paste into any function, thanks to python's block structure support.

def equals_ignore_case(str1, str2):
    import re
    return re.match(re.escape(str1) + r'\Z', str2, re.I) is not None

Since I used match instead of search, I didn't need to add a caret (^) to the regular expression.

Note: This only checks equality, which is sometimes what is needed. I also wouldn't go so far as to say that I like it.

How can I check if a directory exists?

You may also use access in combination with opendir to determine if the directory exists, and, if the name exists, but is not a directory. For example:

/* test that dir exists (1 success, -1 does not exist, -2 not dir) */
int
xis_dir (const char *d)
{
    DIR *dirptr;

    if (access ( d, F_OK ) != -1 ) {
        // file exists
        if ((dirptr = opendir (d)) != NULL) {
            closedir (dirptr); /* d exists and is a directory */
        } else {
            return -2; /* d exists but is not a directory */
        }
    } else {
        return -1;     /* d does not exist */
    }

    return 1;
}

Adding a module (Specifically pymorph) to Spyder (Python IDE)

  1. Find the location of a module in Terminal:

    $ python # open python
    
    import pygame # import a module 
    
    pygame # get the location
    
  2. Copy-paste the module folder to the 'Spyder.app/Contents/Resources/lib/python2.7'

  3. Relaunch Spyder.app

How to update npm

Tried the options above on Ubuntu 14.04, but they would constantly produce this error:

npm ERR! tar pack Error reading /root/tmp/npm-15864/1465947804069-0.4854120113886893/package

Then found this solution online:

1) Clean the cache of npm first:

sudo npm cache clean -f

2) Install n module of npm:

sudo npm install -g n

3) Begin the installation by selecting the version of node to install: stable or latest, we will use stable here:

sudo n stable

4) Check the version of node:

node -v

5) Check the version of npm:

npm -v

How to change the style of the title attribute inside an anchor tag?

You can't style an actual title attribute

How the text in the title attribute is displayed is defined by the browser and varies from browser to browser. It's not possible for a webpage to apply any style to the tooltip that the browser displays based on the title attribute.

However, you can create something very similar using other attributes.

You can make a pseudo-tooltip with CSS and a custom attribute (e.g. data-title)

For this, I'd use a data-title attribute. data-* attributes are a method to store custom data in DOM elements/HTML. There are multiple ways of accessing them. Importantly, they can be selected by CSS.

Given that you can use CSS to select elements with data-title attributes, you can then use CSS to create :after (or :before) content that contains the value of the attribute using attr().

Styled tooltip Examples

Bigger and with a different background color (per question's request):

_x000D_
_x000D_
[data-title]:hover:after {_x000D_
    opacity: 1;_x000D_
    transition: all 0.1s ease 0.5s;_x000D_
    visibility: visible;_x000D_
}_x000D_
[data-title]:after {_x000D_
    content: attr(data-title);_x000D_
    background-color: #00FF00;_x000D_
    color: #111;_x000D_
    font-size: 150%;_x000D_
    position: absolute;_x000D_
    padding: 1px 5px 2px 5px;_x000D_
    bottom: -1.6em;_x000D_
    left: 100%;_x000D_
    white-space: nowrap;_x000D_
    box-shadow: 1px 1px 3px #222222;_x000D_
    opacity: 0;_x000D_
    border: 1px solid #111111;_x000D_
    z-index: 99999;_x000D_
    visibility: hidden;_x000D_
}_x000D_
[data-title] {_x000D_
    position: relative;_x000D_
}
_x000D_
<a href="example.com" data-title="My site"> Link </a> with styled tooltip (bigger and with a different background color, as requested in the question)<br/>_x000D_
<a href="example.com" title="My site"> Link </a> with normal tooltip
_x000D_
_x000D_
_x000D_

More elaborate styling (adapted from this blog post):

_x000D_
_x000D_
[data-title]:hover:after {_x000D_
    opacity: 1;_x000D_
    transition: all 0.1s ease 0.5s;_x000D_
    visibility: visible;_x000D_
}_x000D_
[data-title]:after {_x000D_
    content: attr(data-title);_x000D_
    position: absolute;_x000D_
    bottom: -1.6em;_x000D_
    left: 100%;_x000D_
    padding: 4px 4px 4px 8px;_x000D_
    color: #222;_x000D_
    white-space: nowrap; _x000D_
    -moz-border-radius: 5px; _x000D_
    -webkit-border-radius: 5px;  _x000D_
    border-radius: 5px;  _x000D_
    -moz-box-shadow: 0px 0px 4px #222;  _x000D_
    -webkit-box-shadow: 0px 0px 4px #222;  _x000D_
    box-shadow: 0px 0px 4px #222;  _x000D_
    background-image: -moz-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #f8f8f8),color-stop(1, #cccccc));_x000D_
    background-image: -webkit-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -moz-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -ms-linear-gradient(top, #f8f8f8, #cccccc);  _x000D_
    background-image: -o-linear-gradient(top, #f8f8f8, #cccccc);_x000D_
    opacity: 0;_x000D_
    z-index: 99999;_x000D_
    visibility: hidden;_x000D_
}_x000D_
[data-title] {_x000D_
    position: relative;_x000D_
}
_x000D_
<a href="example.com" data-title="My site"> Link </a> with styled tooltip<br/>_x000D_
<a href="example.com" title="My site"> Link </a> with normal tooltip
_x000D_
_x000D_
_x000D_

Known issues

Unlike a real title tooltip, the tooltip produced by the above CSS is not, necessarily, guaranteed to be visible on the page (i.e. it might be outside the visible area). On the other hand, it is guaranteed to be within the current window, which is not the case for an actual tooltip.

In addition, the pseudo-tooltip is positioned relative to the element that has the pseudo-tooltip rather than relative to where the mouse is on that element. You may want to fine-tune where the pseudo-tooltip is displayed. Having it appear in a known location relative to the element can be a benefit or a drawback, depending on the situation.

You can't use :before or :after on elements which are not containers

There's a good explanation in this answer to "Can I use a :before or :after pseudo-element on an input field?"

Effectively, this means that you can't use this method directly on elements like <input type="text"/>, <textarea/>, <img>, etc. The easy solution is to wrap the element that's not a container in a <span> or <div> and have the pseudo-tooltip on the container.

Examples of using a pseudo-tooltip on a <span> wrapping a non-container element:

_x000D_
_x000D_
[data-title]:hover:after {_x000D_
    opacity: 1;_x000D_
    transition: all 0.1s ease 0.5s;_x000D_
    visibility: visible;_x000D_
}_x000D_
[data-title]:after {_x000D_
    content: attr(data-title);_x000D_
    background-color: #00FF00;_x000D_
    color: #111;_x000D_
    font-size: 150%;_x000D_
    position: absolute;_x000D_
    padding: 1px 5px 2px 5px;_x000D_
    bottom: -1.6em;_x000D_
    left: 100%;_x000D_
    white-space: nowrap;_x000D_
    box-shadow: 1px 1px 3px #222222;_x000D_
    opacity: 0;_x000D_
    border: 1px solid #111111;_x000D_
    z-index: 99999;_x000D_
    visibility: hidden;_x000D_
}_x000D_
[data-title] {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.pseudo-tooltip-wrapper {_x000D_
    /*This causes the wrapping element to be the same size as what it contains.*/_x000D_
    display: inline-block;_x000D_
}
_x000D_
Text input with a pseudo-tooltip:<br/>_x000D_
<span class="pseudo-tooltip-wrapper" data-title="input type=&quot;text&quot;"><input type='text'></span><br/><br/><br/>_x000D_
Textarea with a pseudo-tooltip:<br/>_x000D_
<span class="pseudo-tooltip-wrapper" data-title="this is a textarea"><textarea data-title="this is a textarea"></textarea></span><br/>
_x000D_
_x000D_
_x000D_


From the code on the blog post linked above (which I first saw in an answer here that plagiarized it), it appeared obvious to me to use a data-* attribute instead of the title attribute. Doing so was also suggested in a comment by snostorm on that (now deleted) answer.

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")"

Overriding fields or properties in subclasses

You can go with option 3 if you modify your abstract base class to require the property value in the constructor, you won't miss any paths. I'd really consider this option.

abstract class Aunt
{
    protected int MyInt;
    protected Aunt(int myInt)
    {
        MyInt = myInt;
    }

}

Of course, you then still have the option of making the field private and then, depending on the need, exposing a protected or public property getter.

How can I include css files using node, express, and ejs?

The above responses half worked and I'm not why they didn't on my machine but I had to do the following for it work.

  1. Created a directory at the root

    /public/js/

  2. Paste this into your server.js file with name matching the name of directory created above. Note adding /public as the first param

    app.use('/public',express.static('public'));

  3. Finally in the HTML page to which to import the javascript file into,

    <script src="public/js/bundle.js"></script>

Android failed to load JS bundle

Delete the App from your phone! I tried several steps, but that did it eventually.

  1. If you tried to run your app before but failed, delete it from your android device.
  2. Run $ react-native run-android
  3. Open the React Rage Shake Menu from within your app on your android device, go to Dev Settings and then to Debug server host & port for device. There enter your server IP (IP of your computer) and host 8081, e.g. 192.168.50.35:8081. On a mac you can find the IP of your computer at System Preferences -> Network -> Advanced... -> TCP/IP -> IPv4 Address.
  4. Open the Rage Shake Menu again and click Reload JS.

How to determine whether a Pandas Column contains a particular value

Suppose you dataframe looks like :

enter image description here

Now you want to check if filename "80900026941984" is present in the dataframe or not.

You can simply write :

if sum(df["filename"].astype("str").str.contains("80900026941984")) > 0:
    print("found")

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

Not tested, but something like this:

var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
          (now.getUTCMonth() + 1).toString() +
          "/" + now.getUTCDate() + " " + now.getUTCHours() +
          ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();

Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

Laravel Migration table already exists, but I want to add new not the older

You need to run

php artisan migrate:rollback

if that also fails just go in and drop all the tables which you may have to do as it seems your migration table is messed up or your user table when you ran a previous rollback did not drop the table.

EDIT:

The reason this happens is that you ran a rollback previously and it had some error in the code or did not drop the table. This still however messes up the laravel migration table and as far as it's concerned you now have no record of pushing the user table up. The user table does already exist however and this error is throw.

CSS property to pad text inside of div

The CSS property you are looking for is padding. The problem with padding is that it adds to the width of the original element, so if you have a div with a width of 300px, and add 10px of padding to it, the width will now be 320px (10px on the left and 10px on the right).

To prevent this you can add box-sizing: border-box; to the div, this makes it maintain the designated width, even if you add padding. So your CSS would look like this:

div {
    box-sizing: border-box;
    padding: 10px;
}

you can read more about box-sizing and it's overall browser support here:

http://www.paulirish.com/2012/box-sizing-border-box-ftw/

How do I disable the security certificate check in Python requests

If you want to send exactly post request with verify=False option, fastest way is to use this code:

import requests

requests.api.request('post', url, data={'bar':'baz'}, json=None, verify=False)

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

I was having issues with

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'security:http'

and for me I had to add the spring-security-config jar to the classpath

http://docs.spring.io/spring-security/site/docs/3.1.x/reference/ns-config.html

EDIT:

It might be that you have the correct dependency in your pom.

But...

If you are using multiple spring dependencies and assembling into a single jar then the META-INF/spring.schemas is probably being overwritten by the spring.schemas of another of your spring dependencies.

(Extract that file from your assembled jar and you'll understand)

Spring schemas is just a bunch of lines that look like this:

http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler
http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd

But if another dependency overwrites that file, then the definition will be retrieved from http, and if you have a firewall/proxy it will fail to get it.

One solution is to append spring.schemas and spring.handlers into a single file.

Check:

Idea to avoid that spring.handlers/spring.schemas get overwritten when merging multiple spring dependencies in a single jar

How do you list volumes in docker containers?

Here is my version to find mount points of a docker compose. In use this to backup the volumes.

 # for Id in $(docker-compose -f ~/ida/ida.yml ps -q); do docker inspect -f '{{ (index .Mounts 0).Source }}' $Id; done
/data/volumes/ida_odoo-db-data/_data
/data/volumes/ida_odoo-web-data/_data

This is a combination of previous solutions.

Adding text to ImageView in Android

Use drawalbeLeft/Right/Bottom/Top in TextView to render image at respective position.

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/image"    
        android:text="@strings/text" 
        />

How correctly produce JSON by RESTful web service?

You could use a package like org.json http://www.json.org/java/

Because you will need to use JSONObjects more often.

There you can easily create JSONObjects and put some values in it:

 JSONObject json = new JSONObject();
 JSONArray array=new JSONArray();
    array.put("1");
    array.put("2");
    json.put("friends", array);

    System.out.println(json.toString(2));


    {"friends": [
      "1",
      "2"
    ]}

edit This has the advantage that you can build your responses in different layers and return them as an object

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

How to uncommit my last commit in Git

git reset --soft HEAD^ Will keep the modified changes in your working tree.

git reset --hard HEAD^ WILL THROW AWAY THE CHANGES YOU MADE !!!

Spring MVC + JSON = 406 Not Acceptable

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

That should be the problem. JSON is served as application/json. If you set the Accept header accordingly, you should get the proper response. (There are browser plugins that let you set headers, I like "Poster" for Firefox best)

Optional query string parameters in ASP.NET Web API

Default values cannot be supplied for parameters that are not declared 'optional'

 Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)

In your WebApiConfig

 config.Routes.MapHttpRoute( _
          name:="books", _
          routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
          defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
      )

MySQL FULL JOIN?

Try This:

(SELECT p.LastName, p.FirstName, o.OrderNo
 FROM   Persons p
   LEFT JOIN Orders o
   ON o.OrderNo = p.P_id
)
UNION
(SELECT p.LastName, p.FirstName, o.OrderNo
 FROM   Persons p
   RIGHT JOIN Orders o
   ON o.OrderNo = p.P_id
);

+----------+-----------+---------+
| LastName | FirstName | OrderNo |
+----------+-----------+---------+
| Singh    | Shashi    |       1 |
| Yadav    | Sunil     |    NULL |
| Singh    | Satya     |    NULL |
| Jain     | Ankit     |    NULL |
| NULL     | NULL      |      11 |
| NULL     | NULL      |      12 |
| NULL     | NULL      |      13 |
+----------+-----------+---------+

console.log timestamps in Chrome?

Try this also:

this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );

This function puts timestamp, filename and line number as same of built-in console.log.

Xcode : Adding a project as a build dependency

Today I faced with the same problem. As the result of the first run I got next error:

Lexical or Preprocessor Issue: 'SDKProjectName*/*SDKProjectName.h' file not found.

But before running, I, obviously, added my SDK into the demo project, just drag&drop .xcodeproj file into my test project's source tree. After that, I moved into Build Phases tab in setting of the main xcodeproj file (of the demo) and added my SDK as target dependency and embed framework into corresponding tabs.

But at the result, I got an error above!

So, the problem was into empty line on the Header Search Paths option. I just wrote "../**" as value for this key and project compiled successfully. So, after that, you can add #include <SDKName/SDKName.h> into any project, which includes this SDK.

ps. My test app was created into root SDK folder.

tr:hover not working

try

.list1 tr:hover td{
    background-color:#fefefe;
}

127 Return code from $?

A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:

   For  the shell’s purposes, a command which exits with a zero exit status has succeeded.  An exit status
   of zero indicates success.  A non-zero exit status indicates failure.  When a command terminates  on  a
   fatal signal N, bash uses the value of 128+N as the exit status.
   If  a command is not found, the child process created to execute it returns a status of 127.  If a com-
   mand is found but is not executable, the return status is 126.

   If a command fails because of an error during expansion or redirection, the exit status is greater than
   zero.

   Shell  builtin  commands  return  a  status of 0 (true) if successful, and non-zero (false) if an error
   occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.

   Bash itself returns the exit status of the last command executed, unless  a  syntax  error  occurs,  in
   which case it exits with a non-zero value.  See also the exit builtin command below.