Programs & Examples On #Viewexpiredexception

An exception type that is commonly thrown by the JavaServer Faces (JSF) framework

javax.faces.application.ViewExpiredException: View could not be restored

Introduction

The ViewExpiredException will be thrown whenever the javax.faces.STATE_SAVING_METHOD is set to server (default) and the enduser sends a HTTP POST request on a view via <h:form> with <h:commandLink>, <h:commandButton> or <f:ajax>, while the associated view state isn't available in the session anymore.

The view state is identified as value of a hidden input field javax.faces.ViewState of the <h:form>. With the state saving method set to server, this contains only the view state ID which references a serialized view state in the session. So, when the session is expired for some reason (either timed out in server or client side, or the session cookie is not maintained anymore for some reason in browser, or by calling HttpSession#invalidate() in server, or due a server specific bug with session cookies as known in WildFly), then the serialized view state is not available anymore in the session and the enduser will get this exception. To understand the working of the session, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.

There is also a limit on the amount of views JSF will store in the session. When the limit is hit, then the least recently used view will be expired. See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews.

With the state saving method set to client, the javax.faces.ViewState hidden input field contains instead the whole serialized view state, so the enduser won't get a ViewExpiredException when the session expires. It can however still happen on a cluster environment ("ERROR: MAC did not verify" is symptomatic) and/or when there's a implementation-specific timeout on the client side state configured and/or when server re-generates the AES key during restart, see also Getting ViewExpiredException in clustered environment while state saving method is set to client and user session is valid how to solve it.

Regardless of the solution, make sure you do not use enableRestoreView11Compatibility. it does not at all restore the original view state. It basically recreates the view and all associated view scoped beans from scratch and hereby thus losing all of original data (state). As the application will behave in a confusing way ("Hey, where are my input values..??"), this is very bad for user experience. Better use stateless views or <o:enableRestorableView> instead so you can manage it on a specific view only instead of on all views.

As to the why JSF needs to save view state, head to this answer: Why JSF saves the state of UI components on server?

Avoiding ViewExpiredException on page navigation

In order to avoid ViewExpiredException when e.g. navigating back after logout when the state saving is set to server, only redirecting the POST request after logout is not sufficient. You also need to instruct the browser to not cache the dynamic JSF pages, otherwise the browser may show them from the cache instead of requesting a fresh one from the server when you send a GET request on it (e.g. by back button).

The javax.faces.ViewState hidden field of the cached page may contain a view state ID value which is not valid anymore in the current session. If you're (ab)using POST (command links/buttons) instead of GET (regular links/buttons) for page-to-page navigation, and click such a command link/button on the cached page, then this will in turn fail with a ViewExpiredException.

To fire a redirect after logout in JSF 2.0, either add <redirect /> to the <navigation-case> in question (if any), or add ?faces-redirect=true to the outcome value.

<h:commandButton value="Logout" action="logout?faces-redirect=true" />

or

public String logout() {
    // ...
    return "index?faces-redirect=true";
}

To instruct the browser to not cache the dynamic JSF pages, create a Filter which is mapped on the servlet name of the FacesServlet and adds the needed response headers to disable the browser cache. E.g.

@WebFilter(servletNames={"Faces Servlet"}) // Must match <servlet-name> of your FacesServlet.
public class NoCacheFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
            res.setDateHeader("Expires", 0); // Proxies.
        }

        chain.doFilter(request, response);
    }

    // ...
}

Avoiding ViewExpiredException on page refresh

In order to avoid ViewExpiredException when refreshing the current page when the state saving is set to server, you not only need to make sure you are performing page-to-page navigation exclusively by GET (regular links/buttons), but you also need to make sure that you are exclusively using ajax to submit the forms. If you're submitting the form synchronously (non-ajax) anyway, then you'd best either make the view stateless (see later section), or to send a redirect after POST (see previous section).

Having a ViewExpiredException on page refresh is in default configuration a very rare case. It can only happen when the limit on the amount of views JSF will store in the session is hit. So, it will only happen when you've manually set that limit way too low, or that you're continuously creating new views in the "background" (e.g. by a badly implemented ajax poll in the same page or by a badly implemented 404 error page on broken images of the same page). See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews for detail on that limit. Another cause is having duplicate JSF libraries in runtime classpath conflicting each other. The correct procedure to install JSF is outlined in our JSF wiki page.

Handling ViewExpiredException

When you want to handle an unavoidable ViewExpiredException after a POST action on an arbitrary page which was already opened in some browser tab/window while you're logged out in another tab/window, then you'd like to specify an error-page for that in web.xml which goes to a "Your session is timed out" page. E.g.

<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/WEB-INF/errorpages/expired.xhtml</location>
</error-page>

Use if necessary a meta refresh header in the error page in case you intend to actually redirect further to home or login page.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Session expired</title>
        <meta http-equiv="refresh" content="0;url=#{request.contextPath}/login.xhtml" />
    </head>
    <body>
        <h1>Session expired</h1>
        <h3>You will be redirected to login page</h3>
        <p><a href="#{request.contextPath}/login.xhtml">Click here if redirect didn't work or when you're impatient</a>.</p>
    </body>
</html>

(the 0 in content represents the amount of seconds before redirect, 0 thus means "redirect immediately", you can use e.g. 3 to let the browser wait 3 seconds with the redirect)

Note that handling exceptions during ajax requests requires a special ExceptionHandler. See also Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request. You can find a live example at OmniFaces FullAjaxExceptionHandler showcase page (this also covers non-ajax requests).

Also note that your "general" error page should be mapped on <error-code> of 500 instead of an <exception-type> of e.g. java.lang.Exception or java.lang.Throwable, otherwise all exceptions wrapped in ServletException such as ViewExpiredException would still end up in the general error page. See also ViewExpiredException shown in java.lang.Throwable error-page in web.xml.

<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/errorpages/general.xhtml</location>
</error-page>

Stateless views

A completely different alternative is to run JSF views in stateless mode. This way nothing of JSF state will be saved and the views will never expire, but just be rebuilt from scratch on every request. You can turn on stateless views by setting the transient attribute of <f:view> to true:

<f:view transient="true">

</f:view>

This way the javax.faces.ViewState hidden field will get a fixed value of "stateless" in Mojarra (have not checked MyFaces at this point). Note that this feature was introduced in Mojarra 2.1.19 and 2.2.0 and is not available in older versions.

The consequence is that you cannot use view scoped beans anymore. They will now behave like request scoped beans. One of the disadvantages is that you have to track the state yourself by fiddling with hidden inputs and/or loose request parameters. Mainly those forms with input fields with rendered, readonly or disabled attributes which are controlled by ajax events will be affected.

Note that the <f:view> does not necessarily need to be unique throughout the view and/or reside in the master template only. It's also completely legit to redeclare and nest it in a template client. It basically "extends" the parent <f:view> then. E.g. in master template:

<f:view contentType="text/html">
    <ui:insert name="content" />
</f:view>

and in template client:

<ui:define name="content">
    <f:view transient="true">
        <h:form>...</h:form>
    </f:view>
</f:view>

You can even wrap the <f:view> in a <c:if> to make it conditional. Note that it would apply on the entire view, not only on the nested contents, such as the <h:form> in above example.

See also


Unrelated to the concrete problem, using HTTP POST for pure page-to-page navigation isn't very user/SEO friendly. In JSF 2.0 you should really prefer <h:link> or <h:button> over the <h:commandXxx> ones for plain vanilla page-to-page navigation.

So instead of e.g.

<h:form id="menu">
    <h:commandLink value="Foo" action="foo?faces-redirect=true" />
    <h:commandLink value="Bar" action="bar?faces-redirect=true" />
    <h:commandLink value="Baz" action="baz?faces-redirect=true" />
</h:form>

better do

<h:link value="Foo" outcome="foo" />
<h:link value="Bar" outcome="bar" />
<h:link value="Baz" outcome="baz" />

See also

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

Would this work better?

import java.util.Scanner;

public class Work {

public static void main(String[] args){

    System.out.println("Please enter the following information");

    String name = "0";
    String num = "0";
    String address = "0";

    int i = 0;

    Scanner input = new Scanner(System.in);

    //The Arrays
    String [] contactName = new String [7];
    String [] contactNum = new String [7];
    String [] contactAdd = new String [7];

    //I set these as the Array titles
    contactName[0] = "Name";
    contactNum[0] = "Phone Number";
    contactAdd[0] = "Address";

    //This asks for the information and builds an Array for each
    //i -= i resets i back to 0 so the arrays are not 7,14,21+
    while (i < 6){

        i++;
        System.out.println("Enter contact name." + i);
        name = input.nextLine();
        contactName[i] = name;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact number." + i);
        num = input.nextLine();
        contactNum[i] = num;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact address." + i);
        num = input.nextLine();
        contactAdd[i] = num;
    }


    //Now lets print out the Arrays
    i -= i;
    while(i < 6){
    i++;
    System.out.print( i + " " + contactName[i] + " / " );
    }

    //These are set to print the array on one line so println will skip a line
    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
    i++;

    System.out.print( i + " " + contactNum[i] + " / " );
    }

    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
        i++;

    System.out.print( i + " " + contactAdd[i] + " / " );
    }

    System.out.println();

    System.out.println("End of program");

}

}

Before and After Suite execution hook in jUnit 4.x

The only way I think then to get the functionality you want would be to do something like

import junit.framework.Test;  
import junit.framework.TestResult;  
import junit.framework.TestSuite;  

public class AllTests {  
    public static Test suite() {  
        TestSuite suite = new TestSuite("TestEverything");  
        //$JUnit-BEGIN$  
        suite.addTestSuite(TestOne.class);  
        suite.addTestSuite(TestTwo.class);  
        suite.addTestSuite(TestThree.class);  
        //$JUnit-END$  
     }  

     public static void main(String[] args)  
     {  
        AllTests test = new AllTests();  
        Test testCase = test.suite();  
        TestResult result = new TestResult();  
        setUp();  
        testCase.run(result);  
        tearDown();  
     }  
     public void setUp() {}  
     public void tearDown() {}  
} 

I use something like this in eclipse, so I'm not sure how portable it is outside of that environment

Java generics - ArrayList initialization

A lot of this has to do with polymorphism. When you assign

X = new Y();

X can be much less 'specific' than Y, but not the other way around. X is just the handle you are accessing Y with, Y is the real instantiated thing,

You get an error here because Integer is a Number, but Number is not an Integer.

ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

As such, any method of X that you call must be valid for Y. Since X is more generally it probably shares some, but not all of Y's methods. Still, any arguments given must be valid for Y.

In your examples with add, an int (small i) is not a valid Object or Integer.

ArrayList<?> a = new ArrayList<?>();

This is no good because you can't actually instantiate an array list containing ?'s. You can declare one as such, and then damn near anything can follow in new ArrayList<Whatever>();

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I eventually figured out there was a byte mark exception and removed it using this code:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
    if (xml.StartsWith(_byteOrderMarkUtf8))
    {
        var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;
        xml = xml.Remove(0, lastIndexOfUtf8);
    }

Getting Access Denied when calling the PutObject operation with bucket-level permission

Error : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I solved the issue by passing Extra Args parameter as PutObjectAcl is disabled by company policy.

s3_client.upload_file('./local_file.csv', 'bucket-name', 'path', ExtraArgs={'ServerSideEncryption': 'AES256'})

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

If you are using jsvc to run tomcat as tomcat (run /etc/init.d/tomcat as root), edit /etc/init.d/tomcat and add $CATALINA_HOME/bin/tomcat-juli.jar to CLASSPATH.

Convert a video to MP4 (H.264/AAC) with ffmpeg

Software patents led Debian/Ubuntu to disable the H.264 and AAC encoders in ffmpeg. See /usr/share/doc/ffmpeg/README.Debian.gz.

So go install x264, mplayer/mencoder, and Nero's AAC encoder. (Or, if you want to use all Free software, and don't care so much about audio quality, then sudo aptitude install faac.)

I don't remember if the medibuntu package of mencoder includes x264 vid encoding, since I build my own from git x264 and svn mplayer sources. (x264 is very actively developed, with significant quality and speed improvements frequently added.) http://git.videolan.org/?p=x264.git;a=summary

x264 is also packaged, but you should check that it's up to date enough to include weightp with recent bugfixes, and even more recent speed improvements...

Or if you're already willing to convert from .flv, instead of going from the high-quality source the flv was made from, then probably whatever recent version of x264 you can find will be fine.

What is an 'undeclared identifier' error and how do I fix it?

These error meassages

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

mean that you use name printf but the compiler does not see where the name was declared and accordingly does not know what it means.

Any name used in a program shall be declared before its using. The compiler has to know what the name denotes.

In this particular case the compiler does not see the declaration of name printf . As we know (but not the compiler) it is the name of standard C function declared in header <stdio.h> in C or in header <cstdio> in C++ and placed in standard (std::) and global (::) (not necessarily) name spaces.

So before using this function we have to provide its name declaration to the compiler by including corresponding headers.

For example C:

#include <stdio.h>

int main( void )
{
   printf( "Hello World\n" );
}

C++:

#include <cstdio>

int main()
{
   std::printf( "Hello World\n" );
   // or printf( "Hello World\n" );
   // or ::printf( "Hello World\n" );
}

Sometimes the reason of such an error is a simple typo. For example let's assume that you defined function PrintHello

void PrintHello()
{
    std::printf( "Hello World\n" );
}

but in main you made a typo and instead of PrintHello you typed printHello with lower case letter 'p'.

#include <cstdio>

void PrintHello()
{
    std::printf( "Hello World\n" );
}

int main()
{
   printHello();
}

In this case the compiler will issue such an error because it does not see the declaration of name printHello. PrintHello and printHello are two different names one of which was declared and other was not declared but used in the body of main

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A     int64
#B      bool
#C    object
#dtype: object

Binding ConverterParameter

No, unfortunately this will not be possible because ConverterParameter is not a DependencyProperty so you won't be able to use bindings

But perhaps you could cheat and use a MultiBinding with IMultiValueConverter to pass in the 2 Tag properties.

jQuery - adding elements into an array

var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');

        ids.push(this.id);       
    });
});

How to format a string as a telephone number in C#

Try this

string result;
if ( (!string.IsNullOrEmpty(phoneNumber)) && (phoneNumber.Length >= 10 ) )
    result = string.Format("{0:(###)###-"+new string('#',phoneNumber.Length-6)+"}",
    Convert.ToInt64(phoneNumber)
    );
else
    result = phoneNumber;
return result;

Cheers.

How to check if mysql database exists

Long winded and convoluted (but bear with me!), here is a class system I made to check if a DB exists and also to create the tables required:

<?php
class Table
{
    public static function Script()
    {
        return "
            CREATE TABLE IF NOT EXISTS `users` ( `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT );

        ";
    }
}

class Install
{
    #region Private constructor
    private static $link;
    private function __construct()
    {
        static::$link = new mysqli();
        static::$link->real_connect("localhost", "username", "password");
    }
    #endregion

    #region Instantiator
    private static $instance;
    public static function Instance()
    {
        static::$instance = (null === static::$instance ? new self() : static::$instance);
        return static::$instance;
    }
    #endregion

    #region Start Install
    private static $installed;
    public function Start()
    {
        var_dump(static::$installed);
        if (!static::$installed)
        {
            if (!static::$link->select_db("en"))
            {
                static::$link->query("CREATE DATABASE `en`;")? $die = false: $die = true;
                if ($die)
                    return false;
                static::$link->select_db("en");
            }
            else
            {
                static::$link->select_db("en");          
            }
            return static::$installed = static::DatabaseMade();  
        }
        else
        {
            return static::$installed;
        }
    }
    #endregion

    #region Table creator
    private static function CreateTables()
    {
        $tablescript = Table::Script();
        return static::$link->multi_query($tablescript) ? true : false;
    }
    #endregion

    private static function DatabaseMade()
    {
        $created = static::CreateTables();
        if ($created)
        {
            static::$installed = true;
        }
        else
        {
            static::$installed = false;
        }
        return $created;
    }
}

In this you can replace the database name en with any database name you like and also change the creator script to anything at all and (hopefully!) it won't break it. If anyone can improve this, let me know!

Note
If you don't use Visual Studio with PHP tools, don't worry about the regions, they are they for code folding :P

Local storage in Angular 2

To set the item or object in local storage:

   localStorage.setItem('yourKey', 'yourValue');

To get the item or object in local storage, you must remember your key.

   let yourVariable = localStorage.getItem('yourKey');

To remove it from local storage:

   localStorage.removeItem('yourKey');

Best JavaScript compressor

I recently released UglifyJS, a JavaScript compressor which is written in JavaScript (runs on the NodeJS Node.js platform, but it can be easily modified to run on any JavaScript engine, since it doesn't need any Node.js internals). It's a lot faster than both YUI Compressor and Google Closure, it compresses better than YUI on all scripts I tested it on, and it's safer than Closure (knows to deal with "eval" or "with").

Other than whitespace removal, UglifyJS also does the following:

  • changes local variable names (usually to single characters)
  • joins consecutive var declarations
  • avoids inserting any unneeded brackets, parens and semicolons
  • optimizes IFs (removes "else" when it detects that it's not needed, transforms IFs into the &&, || or ?/: operators when possible, etc.).
  • transforms foo["bar"] into foo.bar where possible
  • removes quotes from keys in object literals, where possible
  • resolves simple expressions when this leads to smaller code (1+3*4 ==> 13)

PS: Oh, it can "beautify" as well. ;-)

Reading a column from CSV file using JAVA

Read the input continuously within the loop so that the variable line is assigned a value other than the initial value

while ((line = br.readLine()) !=null) {
  ...
}

Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files

Check if a class is derived from a generic class

I worked through some of these samples and found they were lacking in some cases. This version works with all kinds of generics: types, interfaces and type definitions thereof.

public static bool InheritsOrImplements(this Type child, Type parent)
{
    parent = ResolveGenericTypeDefinition(parent);

    var currentChild = child.IsGenericType
                           ? child.GetGenericTypeDefinition()
                           : child;

    while (currentChild != typeof (object))
    {
        if (parent == currentChild || HasAnyInterfaces(parent, currentChild))
            return true;

        currentChild = currentChild.BaseType != null
                       && currentChild.BaseType.IsGenericType
                           ? currentChild.BaseType.GetGenericTypeDefinition()
                           : currentChild.BaseType;

        if (currentChild == null)
            return false;
    }
    return false;
}

private static bool HasAnyInterfaces(Type parent, Type child)
{
    return child.GetInterfaces()
        .Any(childInterface =>
        {
            var currentInterface = childInterface.IsGenericType
                ? childInterface.GetGenericTypeDefinition()
                : childInterface;

            return currentInterface == parent;
        });
}

private static Type ResolveGenericTypeDefinition(Type parent)
{
    var shouldUseGenericType = true;
    if (parent.IsGenericType && parent.GetGenericTypeDefinition() != parent)
        shouldUseGenericType = false;

    if (parent.IsGenericType && shouldUseGenericType)
        parent = parent.GetGenericTypeDefinition();
    return parent;
}

Here are the unit tests also:

protected interface IFooInterface
{
}

protected interface IGenericFooInterface<T>
{
}

protected class FooBase
{
}

protected class FooImplementor
    : FooBase, IFooInterface
{
}

protected class GenericFooBase
    : FooImplementor, IGenericFooInterface<object>
{

}

protected class GenericFooImplementor<T>
    : FooImplementor, IGenericFooInterface<T>
{
}


[Test]
public void Should_inherit_or_implement_non_generic_interface()
{
    Assert.That(typeof(FooImplementor)
        .InheritsOrImplements(typeof(IFooInterface)), Is.True);
}

[Test]
public void Should_inherit_or_implement_generic_interface()
{
    Assert.That(typeof(GenericFooBase)
        .InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}

[Test]
public void Should_inherit_or_implement_generic_interface_by_generic_subclass()
{
    Assert.That(typeof(GenericFooImplementor<>)
        .InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}

[Test]
public void Should_inherit_or_implement_generic_interface_by_generic_subclass_not_caring_about_generic_type_parameter()
{
    Assert.That(new GenericFooImplementor<string>().GetType()
        .InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}

[Test]
public void Should_not_inherit_or_implement_generic_interface_by_generic_subclass_not_caring_about_generic_type_parameter()
{
    Assert.That(new GenericFooImplementor<string>().GetType()
        .InheritsOrImplements(typeof(IGenericFooInterface<int>)), Is.False);
}

[Test]
public void Should_inherit_or_implement_non_generic_class()
{
    Assert.That(typeof(FooImplementor)
        .InheritsOrImplements(typeof(FooBase)), Is.True);
}

[Test]
public void Should_inherit_or_implement_any_base_type()
{
    Assert.That(typeof(GenericFooImplementor<>)
        .InheritsOrImplements(typeof(FooBase)), Is.True);
}

PHP XML how to output nice format

// ##### IN SUMMARY #####

$xmlFilepath = 'test.xml';
echoFormattedXML($xmlFilepath);

/*
 * echo xml in source format
 */
function echoFormattedXML($xmlFilepath) {
    header('Content-Type: text/xml'); // to show source, not execute the xml
    echo formatXML($xmlFilepath); // format the xml to make it readable
} // echoFormattedXML

/*
 * format xml so it can be easily read but will use more disk space
 */
function formatXML($xmlFilepath) {
    $loadxml = simplexml_load_file($xmlFilepath);

    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($loadxml->asXML());
    $formatxml = new SimpleXMLElement($dom->saveXML());
    //$formatxml->saveXML("testF.xml"); // save as file

    return $formatxml->saveXML();
} // formatXML

How can I create a two dimensional array in JavaScript?

Javascript does not support two dimensional arrays, instead we store an array inside another array and fetch the data from that array depending on what position of that array you want to access. Remember array numeration starts at ZERO.

Code Example:

/* Two dimensional array that's 5 x 5 

       C0 C1 C2 C3 C4 
    R0[1][1][1][1][1] 
    R1[1][1][1][1][1] 
    R2[1][1][1][1][1] 
    R3[1][1][1][1][1] 
    R4[1][1][1][1][1] 
*/

var row0 = [1,1,1,1,1],
    row1 = [1,1,1,1,1],
    row2 = [1,1,1,1,1],
    row3 = [1,1,1,1,1],
    row4 = [1,1,1,1,1];

var table = [row0,row1,row2,row3,row4];
console.log(table[0][0]); // Get the first item in the array

C# Select elements in list as List of string

List<string> empnames = (from e in emplist select e.Enaame).ToList();

Or

string[] empnames = (from e in emplist select e.Enaame).ToArray();

Etc...

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

NameError: name 'self' is not defined

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

jQuery 'input' event

jQuery has the following signature for the .on() method: .on( events [, selector ] [, data ], handler )

Events could be anyone of the ones listed on this reference:

https://developer.mozilla.org/en-US/docs/Web/Events

Though, they are not all supported by every browser.

Mozilla states the following about the input event:

The DOM input event is fired synchronously when the value of an or element is changed. Additionally, it fires on contenteditable editors when its contents are changed.

How to get selected option using Selenium WebDriver with Java

In Selenium Python it is:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select

def get_selected_value_from_drop_down(self):
    try:
        select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
        return select.first_selected_option.get_attribute("value")
    except NoSuchElementException, e:
        print "Element not found "
        print e

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

Try pulling out the NVIDIA graphics card and reinserting it.

Python to print out status bar and percentage

Here you can use following code as a function:

def drawProgressBar(percent, barLen = 20):
    sys.stdout.write("\r")
    progress = ""
    for i in range(barLen):
        if i < int(barLen * percent):
            progress += "="
        else:
            progress += " "
    sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
    sys.stdout.flush()

With use of .format:

def drawProgressBar(percent, barLen = 20):
    # percent float from 0 to 1. 
    sys.stdout.write("\r")
    sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
    sys.stdout.flush()

Uncaught TypeError: Cannot read property 'value' of null

My mistake was that I was keeping the Javascript file ( tag) above the html declaration.

It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)

How do I compare two strings in python?

If you want a really simple answer:

s_1 = "abc def ghi"
s_2 = "def ghi abc"
flag = 0
for i in s_1:
    if i not in s_2:
        flag = 1
if flag == 0:
    print("a == b")
else:
    print("a != b")

.htaccess not working on localhost with XAMPP

Edit the .htaccess file, so the first line reads 'Test.':

Test.

Set the default handler

DirectoryIndex index.php index.html index.htm

...

Notification Icon with the new Firebase Cloud Messaging system

write this

<meta-data 
         android:name="com.google.firebase.messaging.default_notification_icon"
         android:resource="@drawable/ic_notification" />

right down <application.....>

enter image description here

Rotating a view in Android

Applying a rotation animation (without duration, thus no animation effect) is a simpler solution than either calling View.setRotation() or override View.onDraw method.

// substitude deltaDegrees for whatever you want
RotateAnimation rotate = new RotateAnimation(0f, deltaDegrees, 
    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  

// prevents View from restoring to original direction. 
rotate.setFillAfter(true); 

someButton.startAnimation(rotate);

Remove Fragment Page from ViewPager in Android

The ViewPager doesn't remove your fragments with the code above because it loads several views (or fragments in your case) into memory. In addition to the visible view, it also loads the view to either side of the visible one. This provides the smooth scrolling from view to view that makes the ViewPager so cool.

To achieve the effect you want, you need to do a couple of things.

  1. Change the FragmentPagerAdapter to a FragmentStatePagerAdapter. The reason for this is that the FragmentPagerAdapter will keep all the views that it loads into memory forever. Where the FragmentStatePagerAdapter disposes of views that fall outside the current and traversable views.

  2. Override the adapter method getItemPosition (shown below). When we call mAdapter.notifyDataSetChanged(); the ViewPager interrogates the adapter to determine what has changed in terms of positioning. We use this method to say that everything has changed so reprocess all your view positioning.

And here's the code...

private class MyPagerAdapter extends FragmentStatePagerAdapter {

    //... your existing code

    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_NONE;
    }

}

How to remove files that are listed in the .gitignore but still on the repository?

You can remove them from the repository manually:

git rm --cached file1 file2 dir/file3

Or, if you have a lot of files:

git rm --cached `git ls-files -i --exclude-from=.gitignore`

But this doesn't seem to work in Git Bash on Windows. It produces an error message. The following works better:

git ls-files -i --exclude-from=.gitignore | xargs git rm --cached  

Regarding rewriting the whole history without these files, I highly doubt there's an automatic way to do it.
And we all know that rewriting the history is bad, don't we? :)

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

/Artist/GetImages/cher/api-key

you could add a route like:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

How can I add new dimensions to a Numpy array?

You could just create an array of the correct size up-front and fill it:

frames = np.empty((480, 640, 3, 100))

for k in xrange(nframes):
    frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))

if the frames were individual jpg file that were named in some particular way (in the example, frame_0.jpg, frame_1.jpg, etc).

Just a note, you might consider using a (nframes, 480,640,3) shaped array, instead.

How to copy only a single worksheet to another workbook using vba

The much longer example below combines some of the useful snippets above:

  • You can specify any number of sheets you want to copy across
  • You can copy entire sheets, i.e. like dragging the tab across, or you can copy over the contents of cells as values-only but preserving formatting.

It could still do with a lot of work to make it better (better error-handling, general cleaning up), but it hopefully provides a good start.

Note that not all formatting is carried across because the new sheet uses its own theme's fonts and colours. I can't work out how to copy those across when pasting as values only.

 Option Explicit

Sub copyDataToNewFile()
    Application.ScreenUpdating = False

    ' Allow different ways of copying data:
    ' sheet = copy the entire sheet
    ' valuesWithFormatting = create a new sheet with the same name as the
    '                        original, copy values from the cells only, then
    '                        apply original formatting. Formatting is only as
    '                        good as the Paste Special > Formats command - theme
    '                        colours and fonts are not preserved.
    Dim copyMethod As String
    copyMethod = "valuesWithFormatting"

    Dim newFilename As String           ' Name (+optionally path) of new file
    Dim themeTempFilePath As String     ' To temporarily save the source file's theme

    Dim sourceWorkbook As Workbook      ' This file
    Set sourceWorkbook = ThisWorkbook

    Dim newWorkbook As Workbook         ' New file

    Dim sht As Worksheet                ' To iterate through sheets later on.
    Dim sheetFriendlyName As String     ' To store friendly sheet name
    Dim sheetCount As Long              ' To avoid having to count multiple times

    ' Sheets to copy over, using internal code names as more reliable.
    Dim colSheetObjectsToCopy As New Collection
    colSheetObjectsToCopy.Add Sheet1
    colSheetObjectsToCopy.Add Sheet2

    ' Get filename of new file from user.
    Do
        newFilename = InputBox("Please Specify the name of your new workbook." & vbCr & vbCr & "Either enter a full path or just a filename, in which case the file will be saved in the same location (" & sourceWorkbook.Path & "). Don't use the name of a workbook that is already open, otherwise this script will break.", "New Copy")
        If newFilename = "" Then MsgBox "You must enter something.", vbExclamation, "Filename needed"
    Loop Until newFilename > ""

    ' If they didn't supply a path, assume same location as the source workbook.
    ' Not perfect - simply assumes a path has been supplied if a path separator
    ' exists somewhere. Could still be a badly-formed path. And, no check is done
    ' to see if the path actually exists.
    If InStr(1, newFilename, Application.PathSeparator, vbTextCompare) = 0 Then
        newFilename = sourceWorkbook.Path & Application.PathSeparator & newFilename
    End If

    ' Create a new workbook and save as the user requested.
    ' NB This fails if the filename is the same as a workbook that's
    ' already open - it should check for this.
    Set newWorkbook = Application.Workbooks.Add(xlWBATWorksheet)
    newWorkbook.SaveAs Filename:=newFilename, _
        FileFormat:=xlWorkbookDefault

    ' Theme fonts and colours don't get copied over with most paste-special operations.
    ' This saves the theme of the source workbook and then loads it into the new workbook.
    ' BUG: Doesn't work!
    'themeTempFilePath = Environ("temp") & Application.PathSeparator & sourceWorkbook.Name & " - Theme.xml"
    'sourceWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
    'sourceWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
    'newWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
    'newWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
    'On Error Resume Next
    'Kill themeTempFilePath  ' kill = delete in VBA-speak
    'On Error GoTo 0


    ' getWorksheetNameFromObject returns null if the worksheet object doens't
    ' exist
    For Each sht In colSheetObjectsToCopy
        sheetFriendlyName = getWorksheetNameFromObject(sourceWorkbook, sht)
        Application.StatusBar = "VBL Copying " & sheetFriendlyName
        If Not IsNull(sheetFriendlyName) Then
            Select Case copyMethod
                Case "sheet"
                    sourceWorkbook.Sheets(sheetFriendlyName).Copy _
                        After:=newWorkbook.Sheets(newWorkbook.Sheets.count)
                Case "valuesWithFormatting"
                    newWorkbook.Sheets.Add After:=newWorkbook.Sheets(newWorkbook.Sheets.count), _
                        Type:=sourceWorkbook.Sheets(sheetFriendlyName).Type
                    sheetCount = newWorkbook.Sheets.count
                    newWorkbook.Sheets(sheetCount).Name = sheetFriendlyName
                    ' Copy all cells in current source sheet to the clipboard. Could copy straight
                    ' to the new workbook by specifying the Destination parameter but in this case
                    ' we want to do a paste special as values only and the Copy method doens't allow that.
                    sourceWorkbook.Sheets(sheetFriendlyName).Cells.Copy ' Destination:=newWorkbook.Sheets(newWorkbook.Sheets.Count).[A1]
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlValues
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlFormats
                    newWorkbook.Sheets(sheetCount).Tab.Color = sourceWorkbook.Sheets(sheetFriendlyName).Tab.Color
                    Application.CutCopyMode = False
            End Select
        End If
    Next sht

    Application.StatusBar = False
    Application.ScreenUpdating = True
    ActiveWorkbook.Save

Is key-value observation (KVO) available in Swift?

(Edited to add new info): consider whether using the Combine framework can help you accomplish what you wanted, rather than using KVO

Yes and no. KVO works on NSObject subclasses much as it always has. It does not work for classes that don't subclass NSObject. Swift does not (currently at least) have its own native observation system.

(See comments for how to expose other properties as ObjC so KVO works on them)

See the Apple Documentation for a full example.

boundingRectWithSize for NSAttributedString returning wrong size

I had the same problem, but I recognised that height constrained has been set correctly. So I did the following:

-(CGSize)MaxHeighForTextInRow:(NSString *)RowText width:(float)UITextviewWidth {

    CGSize constrainedSize = CGSizeMake(UITextviewWidth, CGFLOAT_MAX);

    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,
                                          nil];

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:RowText attributes:attributesDictionary];

    CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

    if (requiredHeight.size.width > UITextviewWidth) {
        requiredHeight = CGRectMake(0, 0, UITextviewWidth, requiredHeight.size.height);
    }

    return requiredHeight.size;
}

Why does Oracle not find oci.dll?

I notice that recent Oracle client installers change file permissions.

I had Oracle 12.0.1 32 bit client installed for a year. I recently installed Oracle 12.0.1 64 bit client. The Oracle install change ALL file permissions in the 32 bit folders.

My application suddenly failed to run.

I used PROCMON.EXE (https://docs.microsoft.com/en-us/sysinternals/downloads/) and noticed that permission was denied opening OCI.DLL

I changed the permissions for everything in the Oracle client folders and application works as expected.

How To Run PHP From Windows Command Line in WAMPServer

The following solution is specifically for wamp environments:

This foxed me for a little while, tried all the other suggestions, $PATH etc even searched the windows registry looking for clues:

The GUI (wampmanager) indicates I have version 7 selected and yes if I phpinfo() in a page in the browser it will tell me its version 7.x.x yet php -v in the command prompt reports a 5.x.x

If you right click on the wampmanager head to icon->tools->delete unused versions and remove the old version, let it restart the services then the command prompt will return a 7.x.x

This solution means you no longer have the old version if you want to switch between php versions but there is a configuration file in C:\wamp64\wampmanager.conf which appears to specify the version to use with CLI (the parameter is called phpCliVersion). I changed it, restarted the server ... thought I had solved it but no effect perhaps I was a little impatient so I have a feeling there may be some mileage in that.

Hope that helps someone

How to read large text file on windows?

The integrated Text-Viewer of Total Commander can open huge files (>10GB) for viewing without any problems. It also provides different views, e.g. a Hex-View.

How to check if a string contains text from an array of substrings in JavaScript?

Best answer is here: This is case insensitive as well

    var specsFilter = [.....];
    var yourString = "......";

    //if found a match
    if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
        // do something
    }

SpringApplication.run main method

Using:

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);  

        //do your ReconTool stuff
    }
}

will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.

Using maven just use mvn spring-boot:run

while in gradle it would be gradle bootRun

An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner. That would look like:

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
       //implement your business logic here
    }
}

Check out this guide from Spring's official guide repository.

The full Spring Boot documentation can be found here

How do you access the matched groups in a JavaScript regular expression?

One line solution:

const matches = (text,regex) => [...text.matchAll(regex)].map(([match])=>match)

So you can use this way (must use /g):

matches("something format_abc", /(?:^|\s)format_(.*?)(?:\s|$)/g)

result:

[" format_abc"]

What is the $$hashKey added to my JSON.stringify result

Update : From Angular v1.5, track by $index is now the standard syntax instead of using link as it gave me a ng-repeat dupes error.

I ran into this for a nested ng-repeat and the below worked.

<tbody>
    <tr ng-repeat="row in data track by $index">
    <td ng-repeat="field in headers track by $index">{{row[field.caption] }}</td>
</tr>

Change limit for "Mysql Row size too large"

If this occures on a SELECT with many columns, the cause can be that mysql is creating a temporary table. If this table is too large to fit in memory, it will use its default temp table format, which is InnoDB, to store it on Disk. In this case the InnoDB size limits apply.

You then have 4 options:

  1. change the innodb row size limit like stated in another post, which requires reinitialization of the server.
  2. change your query to include less columns or avoid causing it to create a temporary table (by i.e. removing order by and limit clauses).
  3. changing max_heap_table_size to be large so the result fits in memory and does not need to get written to disk.
  4. change the default temp table format to MYISAM, this is what i did. Change in my.cnf:

    internal_tmp_disk_storage_engine=MYISAM
    

Restart mysql, query works.

Selecting multiple items in ListView

and to get it :

public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

                Log.d(getLocalClassName(), "onItemClick(" + view + ","
                        + position + "," + id + ")");
        }
    });

How can I get the root domain URI in ASP.NET?

For anyone still wondering, a more complete answer is available at http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/.

public string FullyQualifiedApplicationPath
{
    get
    {
        //Return variable declaration
        var appPath = string.Empty;

        //Getting the current context of HTTP request
        var context = HttpContext.Current;

        //Checking the current context content
        if (context != null)
        {
            //Formatting the fully qualified website url/name
            appPath = string.Format("{0}://{1}{2}{3}",
                                    context.Request.Url.Scheme,
                                    context.Request.Url.Host,
                                    context.Request.Url.Port == 80
                                        ? string.Empty
                                        : ":" + context.Request.Url.Port,
                                    context.Request.ApplicationPath);
        }

        if (!appPath.EndsWith("/"))
            appPath += "/";

        return appPath;
    }
}

How to split a large text file into smaller files with equal number of lines?

split the file "file.txt" into 10000 lines files:

split -l 10000 file.txt

Mercurial undo last commit

after you have pulled and updated your workspace do a thg and right click on the change set you want to get rid of and then click modify history -> strip, it will remove the change set and you will point to default tip.

How do I update a GitHub forked repository?

If you want to keep your GitHub forks up to date with the respective upstreams, there also exists this probot program for GitHub specifically: https://probot.github.io/apps/pull/ which does the job. You would need to allow installation in your account and it will keep your forks up to date.

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

$.get(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    },
    'json'
);

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

Correct way to delete cookies server-side

Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.

How do you convert epoch time in C#?

// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}

Should use ToUniversalTime() for the DateTime object.

ASP.Net MVC Redirect To A Different View

Here's what you can do:

return View("another view name", anotherviewmodel);

What's your favorite "programmer" cartoon?

I like this one: http://xkcd.com/149/

alt text

(Proper User Policy apparently means Simon Says.)

How can I add comments in MySQL?

You can use single line comments:

-- this is a comment
# this is also a comment

Or a multiline comment:

/*
   multiline
   comment
*/

What is the difference between Session.Abandon() and Session.Clear()

This is sort of covered by the various responses above, but the first time I read this article I missed an important fact, which led to a minor bug in my code...

Session.Clear() will CLEAR the values of all the keys but will NOT cause the session end event to fire.

Session.Abandon() will NOT clear the values on the current request. IF another page is requested, the values will be gone for that one. However, abandon WILL throw the event.

So, in my case (and perhaps in yours?), I needed Clear() followed by Abandon().

How to get previous month and year relative to today, using strtotime and date?

If you want the previous year and month relative to a specific date and have DateTime available then you can do this:

$d = new DateTime('2013-01-01', new DateTimeZone('UTC')); 
$d->modify('first day of previous month');
$year = $d->format('Y'); //2012
$month = $d->format('m'); //12

Disabling tab focus on form elements

Building on Terry's simple answer I made this into a basic jQuery function

$.prototype.disableTab = function() {
    this.each(function() {
        $(this).attr('tabindex', '-1');
    });
};

$('.unfocusable-element, .another-unfocusable-element').disableTab();

Invalid length parameter passed to the LEFT or SUBSTRING function

Something else you can use is isnull:

isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)

How can I convert String[] to ArrayList<String>

You can do the following:

String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList

Searching for UUIDs in text with regex

Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.

source: http://en.wikipedia.org/wiki/Uuid#Definition

Therefore, this is technically more correct:

/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

How to center content in a bootstrap column?

Bootstrap 4, horizontal and vertical align contents using flex box

<div class="page-hero d-flex align-items-center justify-content-center">
 <h1>Some text </h1>
</div>

Use bootstrap class align-items-center and justify-content-center

Vertically and horizontally center aligned text

_x000D_
_x000D_
.page-hero {
  height: 200px;
  background-color: grey;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<div class="page-hero d-flex align-items-center justify-content-center">
  <h1>Some text </h1>
</div>
_x000D_
_x000D_
_x000D_

Cannot issue data manipulation statements with executeQuery()

If you're using spring boot, just add an @Modifying annotation.

@Modifying
@Query
(value = "UPDATE user SET middleName = 'Mudd' WHERE id = 1", nativeQuery = true)
void updateMiddleName();

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

In my case I needed to install "JST Server Adapters". I am running Eclipse 3.6 Helios RCP Edition.

Here are the steps I followed:

  1. Help -> Install New Software
  2. Choose "Helios - http://download.eclipse.org/releases/helios" site or kepler - http://download.ecliplse.org/releases/kepler
  3. Expand "Web, XML, and Java EE Development"
  4. Check JST Server Adapters (version 3.2.2)

After that I could define new Server Runtime Environments.

EDIT: With Eclipse 3.7 Indigo Classic, Eclipse Kepler and Luna, the steps are the same (with appropriate update site) but you need both JST Server Adapters and JST Server Adapters Extentions to get the Server Runtime Environment options.

How to repeat a char using printf?

If you limit yourself to repeating either a 0 or a space you can do:

For spaces:

printf("%*s", count, "");

For zeros:

printf("%0*d", count, 0);

How to create a new figure in MATLAB?

figure;
plot(something);

or

figure(2);
plot(something);
...
figure(3);
plot(something else);
...

etc.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Based on BaileyP's answer. The main difference is that these methods return -1 if the pattern can't be matched.

Edit: Thanks to Jason Bunting's answer I got an idea. Why not modify the .lastIndex property of the regex? Though this will only work for patterns with the global flag (/g).

Edit: Updated to pass the test-cases.

String.prototype.regexIndexOf = function(re, startPos) {
    startPos = startPos || 0;

    if (!re.global) {
        var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
        re = new RegExp(re.source, flags);
    }

    re.lastIndex = startPos;
    var match = re.exec(this);

    if (match) return match.index;
    else return -1;
}

String.prototype.regexLastIndexOf = function(re, startPos) {
    startPos = startPos === undefined ? this.length : startPos;

    if (!re.global) {
        var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
        re = new RegExp(re.source, flags);
    }

    var lastSuccess = -1;
    for (var pos = 0; pos <= startPos; pos++) {
        re.lastIndex = pos;

        var match = re.exec(this);
        if (!match) break;

        pos = match.index;
        if (pos <= startPos) lastSuccess = pos;
    }

    return lastSuccess;
}

Using Pairs or 2-tuples in Java

If you are looking for a built-in Java two-element tuple, try AbstractMap.SimpleEntry.

Listing only directories in UNIX

Try this ls -d */ to list directories within the current directory

Can't connect to MySQL server on 'localhost' (10061) after Installation

I solved this by adding the following arguments to the command line string:

mysql --user username --password password --host localhost --port 3306 databasename < "system path to .sql file"

Without the --host and --port arguments, especially if you change the port to let's say 3307, which is a non default value, will cause this error.

Find the most frequent number in a NumPy array

Starting in Python 3.4, the standard library includes the statistics.mode function to return the single most common data point.

from statistics import mode

mode([1, 2, 3, 1, 2, 1, 1, 1, 3, 2, 2, 1])
# 1

If there are multiple modes with the same frequency, statistics.mode returns the first one encountered.


Starting in Python 3.8, the statistics.multimode function returns a list of the most frequently occurring values in the order they were first encountered:

from statistics import multimode

multimode([1, 2, 3, 1, 2])
# [1, 2]

R cannot be resolved - Android error

I would say "R can not be resolved" is something too general and can be misleading at times. I also had the same problem many times ago even when I first create a new project (which mean I did not mess with the code yet). Most of the time I just need to update my sdk manager (as some people have mentioned). But in my recent case, I found out that the path to my project file is too long (something like this E:\R&D\ANDROID\ANDROID BASIC\Folder 1\ Folder 2\..... \Folder n\MyProject). The folder names also contain spaces character. I thought it could be the case and indeed it's true, when I created a new project in another folder with shortest path possible, and none of the folders' names containing space character, it worked as normal.

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

What is the printf format specifier for bool?

If you like C++ better than C, you can try this:

#include <ios>
#include <iostream>

bool b = IsSomethingTrue();
std::cout << std::boolalpha << b;

printf() formatting for hex

The %#08X conversion must precede the value with 0X; that is required by the standard. There's no evidence in the standard that the # should alter the behaviour of the 08 part of the specification except that the 0X prefix is counted as part of the length (so you might want/need to use %#010X. If, like me, you like your hex presented as 0x1234CDEF, then you have to use 0x%08X to achieve the desired result. You could use %#.8X and that should also insert the leading zeroes.

Try variations on the following code:

#include <stdio.h>

int main(void)
{
    int j = 0;
    printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    for (int i = 0; i < 8; i++)
    {
        j = (j << 4) | (i + 6);
        printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    }
    return(0);
}

On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:

0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd

I'm a little surprised at the treatment of 0; I'm not clear why the 0X prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the # option.


The treatment of zero is according to the standard.

ISO/IEC 9899:2011 §7.21.6.1 The fprintf function

¶6 The flag characters and their meanings are:
...
# The result is converted to an "alternative form". ... For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. ...

(Emphasis added.)


Note that using %#X will use upper-case letters for the hex digits and 0X as the prefix; using %#x will use lower-case letters for the hex digits and 0x as the prefix. If you prefer 0x as the prefix and upper-case letters, you have to code the 0x separately: 0x%X. Other format modifiers can be added as needed, of course.

For printing addresses, use the <inttypes.h> header and the uintptr_t type and the PRIXPTR format macro:

#include <inttypes.h>
#include <stdio.h>

int main(void)
{
    void *address = &address;  // &address has type void ** but it converts to void *
    printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
    return 0;
}

Example output:

Address 0x7FFEE5B29428

Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the . to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).

rsync: difference between --size-only and --ignore-times

There are several ways rsync compares files -- the authoritative source is the rsync algorithm description: https://www.andrew.cmu.edu/course/15-749/READINGS/required/cas/tridgell96.pdf. The wikipedia article on rsync is also very good.

For local files, rsync compares metadata and if it looks like it doesn't need to copy the file because size and timestamp match between source and destination it doesn't look further. If they don't match, it cp's the file. However, what if the metadata do match but files aren't actually the same? Then rsync probably didn't do what you intended.

Files that are the same size may still have changed. One simple example is a text file where you correct a typo -- like changing "teh" to "the". The file size is the same, but the corrected file will have a newer timestamp. --size-only says "don't look at the time; if size matches assume files match", which would be the wrong choice in this case.

On the other hand, suppose you accidentally did a big cp -r A B yesterday, but you forgot to preserve the time stamps, and now you want to do the operation in reverse rsync B A. All those files you cp'ed have yesterday's time stamp, even though they weren't really modified yesterday, and rsync will by default end up copying all those files, and updating the timestamp to yesterday too. --size-only may be your friend in this case (modulo the example above).

--ignore-times says to compare the files regardless of whether the files have the same modify time. Consider the typo example above, but then not only did you correct the typo but you used touch to make the corrected file have the same modify time as the original file -- let's just say you're sneaky that way. Well --ignore-times will do a diff of the files even though the size and time match.

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

Convert .class to .java

This is for Mac users:

first of all you have to clarify where the class file is... so for example, in 'Terminal' (A Mac Application) you would type:

cd

then wherever you file is e.g:

cd /Users/CollarBlast/Desktop/JavaFiles/

then you would hit enter. After that you would do the command. e.g:

cd /Users/CollarBlast/Desktop/JavaFiles/ (then i would press enter...)

Then i would type the command:

javap -c JavaTestClassFile.class (then i would press enter again...)

and hopefully it should work!

Html.ActionLink as a button or an image, not a link

Call me simplistic, but I just do:

<a href="<%: Url.Action("ActionName", "ControllerName") %>">
    <button>Button Text</button>
</a>

And you just take care of the hyperlink highlight. Our users love it :)

Best way to make WPF ListView/GridView sort on column-header clicking?

I made an adaptation of the Microsoft way, where I override the ListView control to make a SortableListView:

public partial class SortableListView : ListView
    {        
        private GridViewColumnHeader lastHeaderClicked = null;
        private ListSortDirection lastDirection = ListSortDirection.Ascending;       

        public void GridViewColumnHeaderClicked(GridViewColumnHeader clickedHeader)
        {
            ListSortDirection direction;

            if (clickedHeader != null)
            {
                if (clickedHeader.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (clickedHeader != lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    string sortString = ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path;

                    Sort(sortString, direction);

                    lastHeaderClicked = clickedHeader;
                    lastDirection = direction;
                }
            }
        }

        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource != null ? this.ItemsSource : this.Items);

            dataView.SortDescriptions.Clear();
            SortDescription sD = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sD);
            dataView.Refresh();
        }
    }

The line ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path bit handles the cases where your column names are not the same as their binding paths, which the Microsoft method does not do.

I wanted to intercept the GridViewColumnHeader.Click event so that I wouldn't have to think about it anymore, but I couldn't find a way to to do. As a result I add the following in XAML for every SortableListView:

GridViewColumnHeader.Click="SortableListViewColumnHeaderClicked"

And then on any Window that contains any number of SortableListViews, just add the following code:

private void SortableListViewColumnHeaderClicked(object sender, RoutedEventArgs e)
        {
            ((Controls.SortableListView)sender).GridViewColumnHeaderClicked(e.OriginalSource as GridViewColumnHeader);
        }

Where Controls is just the XAML ID for the namespace in which you made the SortableListView control.

So, this does prevent code duplication on the sorting side, you just need to remember to handle the event as above.

Get a Windows Forms control by name in C#

You can do the following:

private ToolStripMenuItem getToolStripMenuItemByName(string nameParam)
   {
      foreach (Control ctn in this.Controls)
         {
            if (ctn is ToolStripMenuItem)
               {
                   if (ctn.Name = nameParam)
                      {
                         return ctn;
                      }
                }
         }
         return null;
    }

How to delete selected text in the vi editor

I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?

Forget the mouse. To remove 5 lines, either:

  • Go to the first line and type d5d (dd deletes one line, d5d deletes 5 lines) ~or~
  • Type Shift-v to enter linewise selection mode, then move the cursor down using j (yes, use h, j, k and l to move left, down, up, right respectively, that's much more efficient than using the arrows) and type d to delete the selection.

Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?

As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.

I suggest spending some time with the Vim Tutor (run vimtutor) to get more familiar with Vim in a very didactic way.

See also

Convert Xml to DataTable

I would first create a DataTable with the columns that you require, then populate it via Linq-to-XML.

You could use a Select query to create an object that represents each row, then use the standard approach for creating DataRows for each item ...

class Quest
{
    public string Answer1;
    public string Answer2;
    public string Answer3;
    public string Answer4;
}

public static void Main()
{
    var doc = XDocument.Load("filename.xml");

    var rows = doc.Descendants("QuestId").Select(el => new Quest
    {
        Answer1 = el.Element("Answer1").Value,
        Answer2 = el.Element("Answer2").Value,
        Answer3 = el.Element("Answer3").Value,
        Answer4 = el.Element("Answer4").Value,
    });

    // iterate over the rows and add to DataTable ...

}

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal

itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));

I already added these params by xml but it didnot work correctly
and with this line all is ok

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

Generate sql insert script from excel worksheet

There is a handy tool which saves a lot of time at

http://tools.perceptus.ca/text-wiz.php?ops=7

You just have to feed in the table name, field names and the data - tab separated and hit Go!

How do I share variables between different .c files?

In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.

In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.

In those few rare cases when you need to share a variable between files, do like this:

// file.h
extern int my_var;

// file.c
#include "file.h"
int my_var = something;

// main.c
#include "file.h"
use(my_var);

Never put any form of variable definition in a h-file.

Checking if a variable is an integer in PHP

When i start reading it i did notice that you guys forgot about abvious think like type of to check if we have int, string, null or Boolean. So i think gettype() should be as 1st answer. Explain: So if we have $test = [1,w2,3.45,sasd]; we start test it

foreach ($test as $value) {
        $check = gettype($value);
        if($check == 'integer'){
            echo "This var is int\r\n";
        }
        if($check != 'integer'){
            echo "This var is {$check}\r\n";
        }
}

And output:

> This var is int 
> This var is string 
> This var is double 
> This var is string

I think this is easiest way to check if our var is int, string, double or Boolean.

matplotlib savefig in jpeg format

I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig.

To upgrade to matplotlib 1.1.0 with pip, use this command:

pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'

EDIT (to respond to comment):

pylab is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.

On my system, pylab is just this:

from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__

You can see that pylab is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab or with matplotlib.pyplot.

If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.

How to create an HTML button that acts like a link?

The only way to do this (except for BalusC's ingenious form idea!) is by adding a JavaScript onclick event to the button, which is not good for accessibility.

Have you considered styling a normal link like a button? You can't achieve OS specific buttons that way, but it's still the best way IMO.

jQuery check if an input is type checkbox?

$('#myinput').is(':checkbox')

this is the only work, to solve the issue to detect if checkbox checked or not. It returns true or false, I search it for hours and try everything, now its work to be clear I use EDG as browser and W2UI

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

The livereload plugin fails to serve cordova.js file and serves // mock cordova file during development.

FIX: You need go to node_modules/@ionic/app-scripts/dist/dev-server/serve-config.js

and replace

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'assets', 'www');

to

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'app', 'src', 'main', 'assets', 'www');

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

Convert NSDate to NSString

Define your own utility for format your date required date format for eg.

NSString * stringFromDate(NSDate *date)  
 {   NSDateFormatter *formatter
    [[NSDateFormatter alloc] init];  
    [formatter setDateFormat:@"MM / dd / yyyy, hh?mm a"];    
    return [formatter stringFromDate:date]; 
}

Listen for key press in .NET console app

Here is an approach for you to do something on a different thread and start listening to the key pressed in a different thread. And the Console will stop its processing when your actual process ends or the user terminates the process by pressing Esc key.

class SplitAnalyser
{
    public static bool stopProcessor = false;
    public static bool Terminate = false;

    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Split Analyser starts");
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Press Esc to quit.....");
        Thread MainThread = new Thread(new ThreadStart(startProcess));
        Thread ConsoleKeyListener = new Thread(new ThreadStart(ListerKeyBoardEvent));
        MainThread.Name = "Processor";
        ConsoleKeyListener.Name = "KeyListener";
        MainThread.Start();
        ConsoleKeyListener.Start();

        while (true) 
        {
            if (Terminate)
            {
                Console.WriteLine("Terminating Process...");
                MainThread.Abort();
                ConsoleKeyListener.Abort();
                Thread.Sleep(2000);
                Thread.CurrentThread.Abort();
                return;
            }

            if (stopProcessor)
            {
                Console.WriteLine("Ending Process...");
                MainThread.Abort();
                ConsoleKeyListener.Abort();
                Thread.Sleep(2000);
                Thread.CurrentThread.Abort();
                return;
            }
        } 
    }

    public static void ListerKeyBoardEvent()
    {
        do
        {
            if (Console.ReadKey(true).Key == ConsoleKey.Escape)
            {
                Terminate = true;
            }
        } while (true); 
    }

    public static void startProcess()
    {
        int i = 0;
        while (true)
        {
            if (!stopProcessor && !Terminate)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Processing...." + i++);
                Thread.Sleep(3000);
            }
            if(i==10)
                stopProcessor = true;

        }
    }

}

Using filesystem in node.js with async / await

Node v14.0.0 and above

you can just do:

import { readdir } from "fs/promises";

just like you would import from "fs"

see this PR for more details: https://github.com/nodejs/node/pull/31553

Java List.contains(Object with field value equal to x)

Despite JAVA 8 SDK there is a lot of collection tools libraries can help you to work with, for instance: http://commons.apache.org/proper/commons-collections/

Predicate condition = new Predicate() {
   boolean evaluate(Object obj) {
        return ((Sample)obj).myField.equals("myVal");
   }
};
List result = CollectionUtils.select( list, condition );

How can I make my custom objects Parcelable?

To put: bundle.putSerializable("key",(Serializable) object);

To get: List<Object> obj = (List<Object>)((Serializable)bundle.getSerializable("key"));

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

Should I use SVN or Git?

SVN is one repo and lots of clients. Git is a repo with lots of client repos, each with a user. It's decentralised to a point where people can track their own edits locally without having to push things to an external server.

SVN is designed to be more central where Git is based on each user having their own Git repo and those repos push changes back up into a central one. For that reason, Git gives individuals better local version control.

Meanwhile you have the choice between TortoiseGit, GitExtensions (and if you host your "central" git-repository on github, their own client – GitHub for Windows).

If you're looking on getting out of SVN, you might want to evaluate Bazaar for a bit. It's one of the next generation of version control systems that have this distributed element. It isn't POSIX dependant like git so there are native Windows builds and it has some powerful open source brands backing it.

But you might not even need these sorts of features yet. Have a look at the features, advantages and disadvantages of the distributed VCSes. If you need more than SVN offers, consider one. If you don't, you might want to stick with SVN's (currently) superior desktop integration.

How to normalize an array in NumPy to a unit vector?

If you have multidimensional data and want each axis normalized to its max or its sum:

def normalize(_d, to_sum=True, copy=True):
    # d is a (n x dimension) np array
    d = _d if not copy else np.copy(_d)
    d -= np.min(d, axis=0)
    d /= (np.sum(d, axis=0) if to_sum else np.ptp(d, axis=0))
    return d

Uses numpys peak to peak function.

a = np.random.random((5, 3))

b = normalize(a, copy=False)
b.sum(axis=0) # array([1., 1., 1.]), the rows sum to 1

c = normalize(a, to_sum=False, copy=False)
c.max(axis=0) # array([1., 1., 1.]), the max of each row is 1

How do I initialize an empty array in C#?

If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.

Use a List<string> instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray() on the variable.

var listOfStrings = new List<string>();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();

If you must create an empty array you can do this:

string[] emptyStringArray = new string[0]; 

Efficient way to apply multiple filters to pandas DataFrame or Series

Simplest of All Solutions:

Use:

filtered_df = df[(df['col1'] >= 1) & (df['col1'] <= 5)]

Another Example, To filter the dataframe for values belonging to Feb-2018, use the below code

filtered_df = df[(df['year'] == 2018) & (df['month'] == 2)]

Validate fields after user has left a field

From version 1.3.0 this can easily be done with $touched, which is true after the user has left the field.

<p ng-show="form.field.$touched && form.field.$invalid">Error</p>

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

JAVA_HOME and PATH are set but java -version still shows the old one

While it looks like your setup is correct, there are a few things to check:

  1. The output of env - specifically PATH.
  2. command -v java tells you what?
  3. Is there a java executable in $JAVA_HOME\bin and does it have the execute bit set? If not chmod a+x java it.

I trust you have source'd your .profile after adding/changing the JAVA_HOME and PATH?

Also, you can help yourself in future maintenance of your JDK installation by writing this instead:

export JAVA_HOME=/home/aqeel/development/jdk/jdk1.6.0_35
export PATH=$JAVA_HOME/bin:$PATH

Then you only need to update one env variable when you setup the JDK installation.

Finally, you may need to run hash -r to clear the Bash program cache. Other shells may need a similar command.

Cheers,

Get Unix timestamp with C++

As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:

#include <chrono>

//...

using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.

Insert into C# with SQLCommand

Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;

 using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
 {
            connection.Open();
            string sql =  "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
            using(SqlCommand cmd = new SqlCommand(sql,connection)) 
            {
                  cmd.Parameters.Add("@param1", SqlDbType.Int).value = klantId;  
                  cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = klantNaam;
                  cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = klantVoornaam;
                  cmd.CommandType = CommandType.Text;
                  cmd.ExecuteNonQuery(); 
            }
 }

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

You might check Select2 plugin:

http://ivaynberg.github.io/select2/

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

It's quite popular and very maintainable. It should cover most of your needs if not all.

CSS3 opacity gradient?

You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.

CSS:

p {
    color: red;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}

The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)

See a demo with a solid background, but you can change this to whatever you want.

DEMO

Notice also that all the usual image properties are available for mask-image

_x000D_
_x000D_
p  {_x000D_
  color: red;_x000D_
  font-size: 30px;_x000D_
  -webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
  -webkit-mask-size: 100% 50%;_x000D_
  -webkit-mask-repeat: no-repeat;_x000D_
  -webkit-mask-position: left top, left bottom;_x000D_
  }_x000D_
_x000D_
div {_x000D_
    background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.

The idea is to use

mix-blend-mode: hard-light;

that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency

_x000D_
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
  mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(transparent, gray);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Conditional Formatting using Excel VBA code

This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5 in this case) will be? Then I can try to provide a more complete answer.

Sub setCondFormat()
    Range("B3").Select
    With Range("B3:H63")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = 5287936
                .TintAndShade = 0
            End With
        End With
    End With
End Sub

Note: this is tested in Excel 2010.

Edit: Updated code based on comments.

Set cursor position on contentEditable <div>

Update

I've written a cross-browser range and selection library called Rangy that incorporates an improved version of the code I posted below. You can use the selection save and restore module for this particular question, although I'd be tempted to use something like @Nico Burns's answer if you're not doing anything else with selections in your project and don't need the bulk of a library.

Previous answer

You can use IERange (http://code.google.com/p/ierange/) to convert IE's TextRange into something like a DOM Range and use it in conjunction with something like eyelidlessness's starting point. Personally I would only use the algorithms from IERange that do the Range <-> TextRange conversions rather than use the whole thing. And IE's selection object doesn't have the focusNode and anchorNode properties but you should be able to just use the Range/TextRange obtained from the selection instead.

I might put something together to do this, will post back here if and when I do.

EDIT:

I've created a demo of a script that does this. It works in everything I've tried it in so far except for a bug in Opera 9, which I haven't had time to look into yet. Browsers it works in are IE 5.5, 6 and 7, Chrome 2, Firefox 2, 3 and 3.5, and Safari 4, all on Windows.

http://www.timdown.co.uk/code/selections/

Note that selections may be made backwards in browsers so that the focus node is at the start of the selection and hitting the right or left cursor key will move the caret to a position relative to the start of the selection. I don't think it is possible to replicate this when restoring a selection, so the focus node is always at the end of the selection.

I will write this up fully at some point soon.

Checking host availability by using ping in bash scripts

up=`fping -r 1 $1 `
if [ -z "${up}" ]; then
    printf "Host $1 not responding to ping   \n"
    else
    printf "Host $1 responding to ping  \n"
fi

What are the most-used vim commands/keypresses?

tuxfiles.org holds a pretty good cheat sheet. I think there are a couple of points to learning the commands:

  • Read the cheat sheet regularly. Don't worry about using all of them, or remembering all the keys, just know that the command exists. Look up the command and use it when you find yourself doing something repetitive.
  • If you find yourself doing something regularly (like deleting an entire line after a particular character d$), go a quick google search to see if you can find a command for it.
  • Write down commands you think you'll find useful and keep that list where you can see it while you're writing your code. I would argue against printing something out and instead encourage you to use post it notes for just a few commands at a time.
  • If possible, watch other programmers use vim, and ask them what commands they are using as you see them do something interesting.

Besides these tips, there are some basic concepts you should understand.

  • vim will use the same character to represent the same function. For example, to delete a line after a character use d$. To highlight a line after a particular character use v$. So notice that $ indicates you will be doing something to the end of the line from where your cursor currently is.
  • u is undo, and ctrl+r is redo.
  • putting a number in front of a command will execute it repeatedly. 3dd will delete the line your cursor is on and the two lines that follow, similarly 3yy will copy the line your cursor is on and the two lines that follow.
  • understand how to navigate through the buffers use :ls to list the buffers, and :bn, :bp to cycle through them.
  • read through the tutorial found in :help This is probably the best way to 'learn the ropes', and the rest of the commands you will learn through usage.

PreparedStatement with Statement.RETURN_GENERATED_KEYS

String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);

preparedStatement.setXXX(1, VALUE); 
preparedStatement.setXXX(2, VALUE); 
....
preparedStatement.executeUpdate();  

ResultSet rs = preparedStatement.getGeneratedKeys();  
int key = rs.next() ? rs.getInt(1) : 0;

if(key!=0){
    System.out.println("Generated key="+key);
}

TypeError: 'dict_keys' object does not support indexing

Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:

next(iter(keys))

Or, if you want to iterate over all items, you can use:

items = iter(keys)
while True:
    try:
        item = next(items)
    except StopIteration as e:
        pass # finish

C# - Simplest way to remove first occurrence of a substring from another string

Wrote a quick TDD Test for this

    [TestMethod]
    public void Test()
    {
        var input = @"ProjectName\Iteration\Release1\Iteration1";
        var pattern = @"\\Iteration";

        var rgx = new Regex(pattern);
        var result = rgx.Replace(input, "", 1);

        Assert.IsTrue(result.Equals(@"ProjectName\Release1\Iteration1"));
    }

rgx.Replace(input, "", 1); says to look in input for anything matching the pattern, with "", 1 time.

Passing a local variable from one function to another

First way is

function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;

// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }

Second way is

var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

C++ Dynamic Shared Library on Linux

The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:

shared.h defines the class:

class myclass {
   int myx;

  public:

    myclass() { myx=0; }
    void setx(int newx);
    int  getx();
};

shared.cpp defines the getx/setx functions:

#include "shared.h"

void myclass::setx(int newx) { myx = newx; }
int  myclass::getx() { return myx; }

main.cpp uses the class,

#include <iostream>
#include "shared.h"

using namespace std;

int main(int argc, char *argv[])
{
  myclass m;

  cout << m.getx() << endl;
  m.setx(10);
  cout << m.getx() << endl;
}

and the makefile that generates libshared.so and links main with the shared library:

main: libshared.so main.o
    $(CXX) -o main  main.o -L. -lshared

libshared.so: shared.cpp
    $(CXX) -fPIC -c shared.cpp -o shared.o
    $(CXX) -shared  -Wl,-soname,libshared.so -o libshared.so shared.o

clean:
    $rm *.o *.so

To actual run 'main' and link with libshared.so you will probably need to specify the load path (or put it in /usr/local/lib or similar).

The following specifies the current directory as the search path for libraries and runs main (bash syntax):

export LD_LIBRARY_PATH=.
./main

To see that the program is linked with libshared.so you can try ldd:

LD_LIBRARY_PATH=. ldd main

Prints on my machine:

  ~/prj/test/shared$ LD_LIBRARY_PATH=. ldd main
    linux-gate.so.1 =>  (0xb7f88000)
    libshared.so => ./libshared.so (0xb7f85000)
    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e74000)
    libm.so.6 => /lib/libm.so.6 (0xb7e4e000)
    libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb7e41000)
    libc.so.6 => /lib/libc.so.6 (0xb7cfa000)
    /lib/ld-linux.so.2 (0xb7f89000)

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give name and values to those submit buttons like:

    <td>
    <input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
    </td>
    <td>
    <input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
    </td>

and then in your php script you could check

if($_POST['mybutton'] == 'save')
{
  ///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
  ///do publish processing here
}

Setting up a JavaScript variable from Spring model by using Thymeleaf

If you need to display your variable unescaped, use this format:

<script th:inline="javascript">
/*<![CDATA[*/

    var message = /*[(${message})]*/ 'default';

/*]]>*/
</script>

Note the [( brackets which wrap the variable.

In Mongoose, how do I sort by date? (node.js)

The correct answer is:

Blah.find({}).sort({date: -1}).execFind(function(err,docs){

});

How to assign string to bytes array

For converting from a string to a byte slice, string -> []byte:

[]byte(str)

For converting an array to a slice, [20]byte -> []byte:

arr[:]

For copying a string to an array, string -> [20]byte:

copy(arr[:], str)

Same as above, but explicitly converting the string to a slice first:

copy(arr[:], []byte(str))

  • The built-in copy function only copies to a slice, from a slice.
  • Arrays are "the underlying data", while slices are "a viewport into underlying data".
  • Using [:] makes an array qualify as a slice.
  • A string does not qualify as a slice that can be copied to, but it qualifies as a slice that can be copied from (strings are immutable).
  • If the string is too long, copy will only copy the part of the string that fits.

This code:

var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)\n", arr, arr)

...gives the following output:

array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)

I also made it available at the Go Playground

Printing all global variables/local variables?

In case you want to see the local variables of a calling function use select-frame before info locals

E.g.:

(gdb) bt
#0  0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1  0xfec36f39 in thr_kill () from /lib/libc.so.1
#2  0xfebe3603 in raise () from /lib/libc.so.1
#3  0xfebc2961 in abort () from /lib/libc.so.1
#4  0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5  0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb) 

What does auto do in margin:0 auto?

When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container.

Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there's 50px of free space to share between margin-left and margin-right:

var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;

Which would give:

margin-left:25;
margin-right:25;

Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Access item in a list of lists

This code will print each individual number:

for myList in [[10,13,17],[3,5,1],[13,11,12]]:
    for item in myList:
        print(item)

Or for your specific use case:

((50 - List1[0][0]) + List1[0][1]) - List1[0][2]

Does bootstrap 4 have a built in horizontal divider?

in Bootstrap 5 you can do something like this:

<div class="py-2 my-1 text-center position-relative mx-2">
            <div class="position-absolute w-100 top-50 start-50 translate-middle" style="z-index: 2">
                <span class="d-inline-block bg-white px-2 text-muted">or</span>
            </div>
            <div class="position-absolute w-100 top-50 start-0 border-muted border-top"></div>
</div>

How can change width of dropdown list?

try the !important argument to make sure the CSS is not conflicting with any other styles you have specified. Also using a reset.css is good before you add your own styles.

select#wgmstr {
    max-width: 50px;
    min-width: 50px;
    width: 50px !important;
}

or

<select name="wgtmsr" id="wgtmsr" style="width: 50px !important; min-width: 50px; max-width: 50px;">

Custom exception type

From WebReference:

throw { 
  name:        "System Error", 
  level:       "Show Stopper", 
  message:     "Error detected. Please contact the system administrator.", 
  htmlMessage: "Error detected. Please contact the <a href=\"mailto:[email protected]\">system administrator</a>.",
  toString:    function(){return this.name + ": " + this.message;} 
}; 

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

Ruby on Rails: How do I add placeholder text to a f.text_field?

In Rails 4(Using HAML):

=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'

Best way to read a large file into a byte array in C#?

I'd say BinaryReader is fine, but can be refactored to this, instead of all those lines of code for getting the length of the buffer:

public byte[] FileToByteArray(string fileName)
{
    byte[] fileData = null;

    using (FileStream fs = File.OpenRead(fileName)) 
    { 
        using (BinaryReader binaryReader = new BinaryReader(fs))
        {
            fileData = binaryReader.ReadBytes((int)fs.Length); 
        }
    }
    return fileData;
}

Should be better than using .ReadAllBytes(), since I saw in the comments on the top response that includes .ReadAllBytes() that one of the commenters had problems with files > 600 MB, since a BinaryReader is meant for this sort of thing. Also, putting it in a using statement ensures the FileStream and BinaryReader are closed and disposed.

UTF-8, UTF-16, and UTF-32

In short:

  • UTF-8: Variable-width encoding, backwards compatible with ASCII. ASCII characters (U+0000 to U+007F) take 1 byte, code points U+0080 to U+07FF take 2 bytes, code points U+0800 to U+FFFF take 3 bytes, code points U+10000 to U+10FFFF take 4 bytes. Good for English text, not so good for Asian text.
  • UTF-16: Variable-width encoding. Code points U+0000 to U+FFFF take 2 bytes, code points U+10000 to U+10FFFF take 4 bytes. Bad for English text, good for Asian text.
  • UTF-32: Fixed-width encoding. All code points take four bytes. An enormous memory hog, but fast to operate on. Rarely used.

In long: see Wikipedia: UTF-8, UTF-16, and UTF-32.

Shell script : How to cut part of a string

$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

How to change package name in android studio?

In projects that use the Gradle build system, what you want to change is the applicationId in the build.gradle file. The build system uses this value to override anything specified by hand in the manifest file when it does the manifest merge and build.

For example, your module's build.gradle file looks something like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        // CHANGE THE APPLICATION ID BELOW
        applicationId "com.example.fred.myapplication"
        minSdkVersion 10
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
}

applicationId is the name the build system uses for the property that eventually gets written to the package attribute of the manifest tag in the manifest file. It was renamed to prevent confusion with the Java package name (which you have also tried to modify), which has nothing to do with it.

SQL Server: Make all UPPER case to Proper Case/Title Case

Here's a UDF that will do the trick...

create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
  declare @Reset bit;
  declare @Ret varchar(8000);
  declare @i int;
  declare @c char(1);

  if @Text is null
    return null;

  select @Reset = 1, @i = 1, @Ret = '';

  while (@i <= len(@Text))
    select @c = substring(@Text, @i, 1),
      @Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
      @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
      @i = @i + 1
  return @Ret
end

You will still have to use it to update your data though.

How does C#'s random number generator work?

I was just wondering how the random number generator in C# works.

That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

You can use Random.Next(int, int):

Random rng = new Random();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(rng.Next(1, 101));
}

Note that the upper bound is exclusive - which is why I've used 101 here.

You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.

convert datetime to date format dd/mm/yyyy

It's simple--tostring() accepts a parameter with this format...

DateTime.ToString("dd/MM/yyyy");

Android Studio doesn't see device

Env - AS 3.3.2 Linux 4 (ubuntu)

in AS used menu Tools > Create desktop entry 

Desktop file content - ( note the path does NOT include Platform-tools )

[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
Name=Android Studio
Icon=jetbrains-studio.png
Path=/home/rob/android-studio
Exec=sh -c ' /home/rob/android-studio/bin/studio.sh' 
StartupNotify=false
StartupWMClass=jetbrains-studio
OnlyShowIn=Unity;
X-UnityGenerated=true

Note that the location of SDK.platform-tools 'adb' below will not be found by desktop.PATH above:

 $ which adb
/usr/local/src/android-sdk-linux/platform-tools/adb

On my setup, my symptom was that any terminal would list the device OK but the toolbar button in AS would never show a connected device... "no devices" is all i would ever see when my phone was connected via USB cable.

SOLUTION for me was adding the correct PATH near the top of the file:

 ${AS_HOME}/bin/studio.sh ...

PATH=$PATH:/usr/local/src/android-sdk-linux/platform-tools:/usr/local/src/android-sdk-linux/tools

pip install: Please check the permissions and owner of that directory

pip install --user <package name> (no sudo needed) worked for me for a very similar problem.

Angular2 Material Dialog css, dialog size

You can also let angular material solve the size itself depending on the content. This means you don't have to cloud your TS files with sizes that depend on your UI. You can keep these in the HTML/CSS.

my-dialog.html

<div class="myContent">
  <h1 mat-dialog-title fxLayoutAlign="center">Your title</h1>
  <form [formGroup]="myForm" fxLayout="column">
    <div mat-dialog-content>
    </div mat-dialog-content>
  </form>
</div>

my-dialog.scss

.myContent {
    width: 300px;
    height: 150px;
}

my-component.ts

const myInfo = {};
this.dialog.open(MyDialogComponent, { data: myInfo });

DbEntityValidationException - How can I easily tell what caused the error?

Use try block in your code like

try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges

    context.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

You can check the details here as well

  1. http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/

  2. Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

  3. http://blogs.infosupport.com/improving-dbentityvalidationexception/

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change event.

You can handle the blur event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.

mysql update query with sub query

You can check your eav_attributes table to find the relevant attribute IDs for each image role, such as; eav_attributes

Then you can use those to set whichever role to any other role for all products like so;

UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`

The above will set all your 'base' roles to the 'small' image of the same product.

Counting number of occurrences in column?

Just adding some extra sorting if needed

=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)

enter image description here

Map vs Object in JavaScript

Summary:

  • Object: A data structure in which data is stored as key value pairs. In an object the key has to be a number, string, or symbol. The value can be anything so also other objects, functions etc. A object is an non ordered data structure, i.e. the sequence of insertion of key value pairs is not remembered
  • ES6 Map: A data structure in which data is stored as key value pairs. In which a unique key maps to a value. Both the key and the value can be in any data type. A map is a iterable data structure, this means that the sequence of insertion is remembered and that we can access the elements in e.g. a for..of loop

Key differences:

  • A Map is ordered and iterable, whereas a objects is not ordered and not iterable

  • We can put any type of data as a Map key, whereas objects can only have a number, string, or symbol as a key.

  • A Map inherits from Map.prototype. This offers all sorts of utility functions and properties which makes working with Map objects a lot easier.

Example:

object:

_x000D_
_x000D_
let obj = {};_x000D_
_x000D_
// adding properties to a object_x000D_
obj.prop1 = 1;_x000D_
obj[2]    =  2;_x000D_
_x000D_
// getting nr of properties of the object_x000D_
console.log(Object.keys(obj).length)_x000D_
_x000D_
// deleting a property_x000D_
delete obj[2]_x000D_
_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Map:

_x000D_
_x000D_
const myMap = new Map();_x000D_
_x000D_
const keyString = 'a string',_x000D_
    keyObj = {},_x000D_
    keyFunc = function() {};_x000D_
_x000D_
// setting the values_x000D_
myMap.set(keyString, "value associated with 'a string'");_x000D_
myMap.set(keyObj, 'value associated with keyObj');_x000D_
myMap.set(keyFunc, 'value associated with keyFunc');_x000D_
_x000D_
console.log(myMap.size); // 3_x000D_
_x000D_
// getting the values_x000D_
console.log(myMap.get(keyString));    // "value associated with 'a string'"_x000D_
console.log(myMap.get(keyObj));       // "value associated with keyObj"_x000D_
console.log(myMap.get(keyFunc));      // "value associated with keyFunc"_x000D_
_x000D_
console.log(myMap.get('a string'));   // "value associated with 'a string'"_x000D_
                         // because keyString === 'a string'_x000D_
console.log(myMap.get({}));           // undefined, because keyObj !== {}_x000D_
console.log(myMap.get(function() {})) // undefined, because keyFunc !== function () {}
_x000D_
_x000D_
_x000D_

source: MDN

How to get JSON response from http.Get

Your Problem were the slice declarations in your data structs (except for Track, they shouldn't be slices...). This was compounded by some rather goofy fieldnames in the fetched json file, which can be fixed via structtags, see godoc.

The code below parsed the json successfully. If you've further questions, let me know.

package main

import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type Tracks struct {
    Toptracks Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  Attr_info `json: "@attr"`
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable Streamable_info
    Artist     Artist_info   
    Attr       Track_attr_info `json: "@attr"`
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string `json: "#text"`
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func perror(err error) {
    if err != nil {
        panic(err)
    }
}

func get_content() {
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)
    perror(err)
    defer res.Body.Close()

    decoder := json.NewDecoder(res.Body)
    var data Tracks
    err = decoder.Decode(&data)
    if err != nil {
        fmt.Printf("%T\n%s\n%#v\n",err, err, err)
        switch v := err.(type){
            case *json.SyntaxError:
                fmt.Println(string(body[v.Offset-40:v.Offset]))
        }
    }
    for i, track := range data.Toptracks.Track{
        fmt.Printf("%d: %s %s\n", i, track.Artist.Name, track.Name)
    }
}

func main() {
    get_content()
}

What's the difference between Cache-Control: max-age=0 and no-cache?

In my recent tests with IE8 and Firefox 3.5, it seems that both are RFC-compliant. However, they differ in their "friendliness" to the origin server. IE8 treats no-cache responses with the same semantics as max-age=0,must-revalidate. Firefox 3.5, however, seems to treat no-cache as equivalent to no-store, which sucks for performance and bandwidth usage.

Squid Cache, by default, seems to never store anything with a no-cache header, just like Firefox.

My advice would be to set public,max-age=0 for non-sensitive resources you want to have checked for freshness on every request, but still allow the performance and bandwidth benefits of caching. For per-user items with the same consideration, use private,max-age=0.

I would avoid the use of no-cache entirely, as it seems it has been bastardized by some browsers and popular caches to the functional equivalent of no-store.

Additionally, do not emulate Akamai and Limelight. While they essentially run massive caching arrays as their primary business, and should be experts, they actually have a vested interest in causing more data to be downloaded from their networks. Google might not be a good choice for emulation, either. They seem to use max-age=0 or no-cache randomly depending on the resource.

How to create standard Borderless buttons (like in the design guideline mentioned)?

Late answer, but many views. As APIs < 11 ain't dead yet, for those interested here is a trick.

Let your container have the desired color (may be transparent). Then give your buttons a selector with default transparent color, and some color when pressed. That way you'll have a transparent button, but will change color when pressed (like holo's). You can also add some animation (like holo's). The selector should be something like this:

res/drawable/selector_transparent_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" 
          android:exitFadeDuration="@android:integer/config_shortAnimTime">
     <item android:state_pressed="true"
         android:drawable="@color/blue" />

   <item android:drawable="@color/transparent" />
</selector>

And the button should have android:background="@drawable/selector_transparent_button"

PS: let you container have the dividers (android:divider='@android:drawable/... for API < 11)

PS [Newbies]: you should define those colors in values/colors.xml

Hex colors: Numeric representation for "transparent"?

Very simple: no color, no opacity:

rgba(0, 0, 0, 0);

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

What does .shape[] do in "for i in range(Y.shape[0])"?

shape is a tuple that gives dimensions of the array..

>>> c = arange(20).reshape(5,4)
>>> c
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

c.shape[0] 
5

Gives the number of rows

c.shape[1] 
4

Gives number of columns

How to show text in combobox when no item selected?

I could not get @Andrei Karcheuski 's approach to work but he inspired me to this approach: (I added the Localizable Property so the Hint can be translated through .resx files for each dialog you use it on)

 public partial class HintComboBox : ComboBox
{
    string hint;
    Font greyFont;

    [Localizable(true)]
    public string Hint
    {
        get { return hint; }
        set { hint = value; Invalidate(); }
    }

    public HintComboBox()
    {
        InitializeComponent();
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        if (string.IsNullOrEmpty(Text))
        {
            this.ForeColor = SystemColors.GrayText;
            Text = Hint;
        }
        else
        {
            this.ForeColor = Color.Black;
        }
    }

    private void HintComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if( string.IsNullOrEmpty(Text) )
        {
            this.ForeColor = SystemColors.GrayText;
            Text = Hint;
        }
        else
        {
            this.ForeColor = Color.Black;
        }
    }

Installing and Running MongoDB on OSX

Download MongoDB and install it on your local machine. Link https://www.mongodb.com/try/download/enterprise

Extract the file and put it on the desktop. Create another folder where you want to store the data. I have created mongodb-data folder. Then run the below command.

Desktop/mongodb/bin/mongod --dbpath=/Users/yourname/Desktop/mongodb-data/

Before the hyphen is the executable path of your mongoDB and after hyphen is your data store.

How to convert array to SimpleXML

So anyway... I took onokazu's code (thanks!) and added the ability to have repeated tags in XML, it also supports attributes, hope someone finds it useful!

 <?php

function array_to_xml(array $arr, SimpleXMLElement $xml) {
        foreach ($arr as $k => $v) {

            $attrArr = array();
            $kArray = explode(' ',$k);
            $tag = array_shift($kArray);

            if (count($kArray) > 0) {
                foreach($kArray as $attrValue) {
                    $attrArr[] = explode('=',$attrValue);                   
                }
            }

            if (is_array($v)) {
                if (is_numeric($k)) {
                    array_to_xml($v, $xml);
                } else {
                    $child = $xml->addChild($tag);
                    if (isset($attrArr)) {
                        foreach($attrArr as $attrArrV) {
                            $child->addAttribute($attrArrV[0],$attrArrV[1]);
                        }
                    }                   
                    array_to_xml($v, $child);
                }
            } else {
                $child = $xml->addChild($tag, $v);
                if (isset($attrArr)) {
                    foreach($attrArr as $attrArrV) {
                        $child->addAttribute($attrArrV[0],$attrArrV[1]);
                    }
                }
            }               
        }

        return $xml;
    }

        $test_array = array (
          'bla' => 'blub',
          'foo' => 'bar',
          'another_array' => array (
            array('stack' => 'overflow'),
            array('stack' => 'overflow'),
            array('stack' => 'overflow'),
          ),
          'foo attribute1=value1 attribute2=value2' => 'bar',
        );  

        $xml = array_to_xml($test_array, new SimpleXMLElement('<root/>'))->asXML();

        echo "$xml\n";
        $dom = new DOMDocument;
        $dom->preserveWhiteSpace = FALSE;
        $dom->loadXML($xml);
        $dom->formatOutput = TRUE;
        echo $dom->saveXml();
    ?>

Android : How to read file in bytes?

Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:

    byte bytes[] = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(bytes);

Blocks until a full read is complete, and doesn't require extra imports.

Selecting data from two different servers in SQL Server

These are all fine answers, but this one is missing and it has it's own powerful uses. Possibly it doesn't fit what the OP wanted, but the question was vague and I feel others may find their way here. Basically you can use 1 window to simultaneously run a query against multiple servers, here's how:

In SSMS open Registered Servers and create a New Server Group under Local Server Groups.

Under this group create New Server Registration for each server you wish to query. If the DB names are different ensure to set a default for each in the properties.

Now go back to the Group you created in the first step, right click and select New Query. A new query window will open and any query you run will be executed on each server in the group. The results are presented in a single data set with an extra column name indicating which server the record came from. If you use the status bar you will note the server name is replaced with multiple.

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

count number of lines in terminal output

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

Understanding the order() function

Running this little piece of code allowed me to understand the order function

x <- c(3, 22, 5, 1, 77)

cbind(
  index=1:length(x),
  rank=rank(x),
  x, 
  order=order(x), 
  sort=sort(x)
)

     index rank  x order sort
[1,]     1    2  3     4    1
[2,]     2    4 22     1    3
[3,]     3    3  5     3    5
[4,]     4    1  1     2   22
[5,]     5    5 77     5   77

Reference: http://r.789695.n4.nabble.com/I-don-t-understand-the-order-function-td4664384.html

"The page you are requesting cannot be served because of the extension configuration." error message

Related to Server 2016, I should add:

  1. Run this command: aspnet_regiis -lv from this dir: C:\Windows\Microsoft.NET\Framework\v2.0.50727\ This gives you the best view of what is going on

  2. On Server 2016, installing .net and iis out of sequence does not seem to be a problem.

  3. What is more likely to be a problem on Server 2016 is simply that asp.net is not installed on the machine.

How to make an HTTP POST web request

There are several ways to perform HTTP GET and POST requests:


Method A: HttpClient (Preferred)

Available in: .NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+ .

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

using System.Net.Http;

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it unless you have a specific reason not to.

private static readonly HttpClient client = new HttpClient();

See HttpClientFactory for a dependency injection solution.


  • POST

    var values = new Dictionary<string, string>
    {
        { "thing1", "hello" },
        { "thing2", "world" }
    };
    
    var content = new FormUrlEncodedContent(values);
    
    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
    
    var responseString = await response.Content.ReadAsStringAsync();
    
  • GET

    var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
    

Method B: Third-Party Libraries

RestSharp

  • POST

     var client = new RestClient("http://example.com");
     // client.Authenticator = new HttpBasicAuthenticator(username, password);
     var request = new RestRequest("resource/{id}");
     request.AddParameter("thing1", "Hello");
     request.AddParameter("thing2", "world");
     request.AddHeader("header", "value");
     request.AddFile("file", path);
     var response = client.Post(request);
     var content = response.Content; // Raw content as string
     var response2 = client.Post<Person>(request);
     var name = response2.Data.Name;
    

Flurl.Http

It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.

    using Flurl.Http;

  • POST

    var responseString = await "http://www.example.com/recepticle.aspx"
        .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
        .ReceiveString();
    
  • GET

    var responseString = await "http://www.example.com/recepticle.aspx"
        .GetStringAsync();
    

Method C: HttpWebRequest (not recommended for new work)

Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps HttpClient, is less performant, and won't get new features.

using System.Net;
using System.Text;  // For class Encoding
using System.IO;    // For StreamReader

  • POST

    var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
    
    var postData = "thing1=" + Uri.EscapeDataString("hello");
        postData += "&thing2=" + Uri.EscapeDataString("world");
    var data = Encoding.ASCII.GetBytes(postData);
    
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;
    
    using (var stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
    
    var response = (HttpWebResponse)request.GetResponse();
    
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    
  • GET

    var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
    
    var response = (HttpWebResponse)request.GetResponse();
    
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    

Method D: WebClient (Not recommended for new work)

This is a wrapper around HttpWebRequest. Compare with HttpClient.

Available in: .NET Framework 1.1+, NET Standard 2.0+, .NET Core 2.0+

using System.Net;
using System.Collections.Specialized;

  • POST

    using (var client = new WebClient())
    {
        var values = new NameValueCollection();
        values["thing1"] = "hello";
        values["thing2"] = "world";
    
        var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
    
        var responseString = Encoding.Default.GetString(response);
    }
    
  • GET

    using (var client = new WebClient())
    {
        var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
    }
    

Reading a resource file from within jar

Up until now (December 2017), this is the only solution I found which works both inside and outside the IDE.

Use PathMatchingResourcePatternResolver

Note: it works also in spring-boot

In this example I'm reading some files located in src/main/resources/my_folder:

try {
    // Get all the files under this inner resource folder: my_folder
    String scannedPackage = "my_folder/*";
    PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
    Resource[] resources = scanner.getResources(scannedPackage);

    if (resources == null || resources.length == 0)
        log.warn("Warning: could not find any resources in this scanned package: " + scannedPackage);
    else {
        for (Resource resource : resources) {
            log.info(resource.getFilename());
            // Read the file content (I used BufferedReader, but there are other solutions for that):
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                // ...
                // ...                      
            }
            bufferedReader.close();
        }
    }
} catch (Exception e) {
    throw new Exception("Failed to read the resources folder: " + e.getMessage(), e);
}

How to conditionally take action if FINDSTR fails to find a string

In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).

There are a couple methods to check that value, but the original one is:

IF ERRORLEVEL value command

Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:

verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%

Findstr command return 0 if the string was found and 1 if not:

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code will copy the file if the string was NOT found in the file.

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code copy the file if the string was found. Try this:

findstr "string" file
if errorlevel 1 (
    echo String NOT found...
) else (
    echo String found
)

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Java: get greatest common divisor

we can use recursive function for find gcd

public class Test
{
 static int gcd(int a, int b)
    {
        // Everything divides 0 
        if (a == 0 || b == 0)
           return 0;

        // base case
        if (a == b)
            return a;

        // a is greater
        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }

    // Driver method
    public static void main(String[] args) 
    {
        int a = 98, b = 56;
        System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}

HashMap and int as key

For somebody who is interested in a such map because you want to reduce footprint of autoboxing in Java of wrappers over primitives types, I would recommend to use Eclipse collections. Trove isn't supported any more, and I believe it is quite unreliable library in this sense (though it is quite popular anyway) and couldn't be compared with Eclipse collections.

import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap;

public class Check {
    public static void main(String[] args) {
        IntObjectHashMap map = new IntObjectHashMap();

        map.put(5,"It works");
        map.put(6,"without");
        map.put(7,"boxing!");

        System.out.println(map.get(5));
        System.out.println(map.get(6));
        System.out.println(map.get(7));
    }
}

In this example above IntObjectHashMap.

As you need int->object mapping, also consider usage of YourObjectType[] array or List<YourObjectType> and access values by index, as map is, by nature, an associative array with int type as index.

How to insert double and float values to sqlite?

I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL

Read http://sqlite.org/datatype3.html to more info.

"Find next" in Vim

The most useful shortcut in Vim, IMHO, is the * key.

Put the cursor on a word and hit the * key and you will jump to the next instance of that word.

The # key does the same, but it jumps to the previous instance of the word.

It is truly a time saver.

How to resolve compiler warning 'implicit declaration of function memset'

You need:

#include <string.h> /* memset */
#include <unistd.h> /* close */

in your code.

References: POSIX for close, the C standard for memset.

How to find the size of an int[]?

int arr1[] = {8, 15, 3, 7};
int n = sizeof(arr1)/sizeof(arr1[0]);

So basically sizeof(arr1) is giving the size of the object being pointed to, each element maybe occupying multiple bits so dividing by the number of bits per element (sizeof(arr1[0]) gives you the actual number of elements you're looking for, i.e. 4 in my example.

AWK to print field $2 first, then field $1

The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.

This will cause the cursor to go to the start of the line after $2.

Use dos2unix or vi with :se ff=unix to get rid of the CRs.

Convert string to number and add one

$('.load_more').live("click",function() { //When user clicks
          var newcurrentpageTemp = parseInt($(this).attr("id")) + 1
          dosomething(newcurrentpageTemp );
      });

http://jsfiddle.net/GfqMM/

Android Studio - Failed to notify project evaluation listener error

In my case, i got wifi problem. make sure you have valid internet connection

ORA-01008: not all variables bound. They are bound

On Charles' comment problem: to make things worse, let

:p1 = 'TRIALDEV'

via a Command Parameter, then execute

select T.table_name as NAME, COALESCE(C.comments, '===') as DESCRIPTION
from all_all_tables T
Inner Join all_tab_comments C on T.owner = C.owner and T.table_name = C.table_name
where Upper(T.owner)=:p1
order by T.table_name

558 line(s) affected. Processing time: 00:00:00.6535711

and when changing the literal string from === to ---

select T.table_name as NAME, COALESCE(C.comments, '---') as DESCRIPTION
[...from...same-as-above...]

ORA-01008: not all variables bound

Both statements execute fine in SQL Developer. The shortened code:

            Using con = New OracleConnection(cs)
                con.Open()
                Using cmd = con.CreateCommand()
                    cmd.CommandText = cmdText
                    cmd.Parameters.Add(pn, OracleDbType.NVarchar2, 250).Value = p
                    Dim tbl = New DataTable
                    Dim da = New OracleDataAdapter(cmd)
                    da.Fill(tbl)
                    Return tbl
                End Using
            End Using

using Oracle.ManagedDataAccess.dll Version 4.121.2.0 with the default settings in VS2015 on the .Net 4.61 platform.

So somewhere in the call chain, there might be a parser that is a bit too aggressively looking for one-line-comments started by -- in the commandText. But even if this would be true, the error message "not all variables bound" is at least misleading.

Elegant way to read file into byte[] array in Java

Use a ByteArrayOutputStream. Here is the process:

  • Get an InputStream to read data
  • Create a ByteArrayOutputStream.
  • Copy all the InputStream into the OutputStream
  • Get your byte[] from the ByteArrayOutputStream using the toByteArray() method

Sum all values in every column of a data.frame in R

mapply(sum,people[,-1])

Height Weight 
   199    425 

How to reload current page without losing any form data?

window.location.reload() // without passing true as argument

works for me.

Why cannot change checkbox color whatever I do?

Checkboxes are not able to be styled. You would need a third party js plugin there are many available.

If you want to do this yourself it basically involves hiding the checkbox creating an element and styling that as you want then binding its click event to two functions one to change its look and another to activate the click event of the checkbox.

The same problem will arise when trying to style that little down arrow on a drop-down select element.

how can I set visible back to true in jquery

The problem is that since you are using ASP.NET controls with a runat attribute, the ID of the control is not actually "test1". It's "test1" with a long string attached to it.

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

FIXED

Give initial height of div and specify height in percentage in your style;

#map {
   height: 100%;
}

<div id="map" style="clear:both; height:200px;"></div> 

Getting strings recognized as variable names in R

What works best for me is using quote() and eval() together.

For example, let's print each column using a for loop:

Columns <- names(dat)
for (i in 1:ncol(dat)){
  dat[, eval(quote(Columns[i]))] %>% print
}

How to configure Glassfish Server in Eclipse manually

To use Glassfish tools with Eclipse Luna you need Java 8. I also faced this problem because I had Java 7. If you have Java 7 in your environment then download eclipse Kepler. It will work fine.

Colspan all columns

Another working but ugly solution : colspan="100", where 100 is a value larger than total columns you need to colspan.

According to the W3C, the colspan="0" option is valid only with COLGROUP tag.

How can I get the MAC and the IP address of a connected client in PHP?

You can do this easily using openWRT. If yo use a captive portal you can mix php and openWRT and make a relation between the IP and the mac.

You can write a simple PHP code using:

 $localIP = getHostByName(getHostName()); 

Later, using openWRT you can go to /tmp/dhcp.leases, you will get something with the form:

 e4:a7:a0:29:xx:xx 10.239.3.XXX DESKTOP-XXX 

There, you have the mac, the IP address and the hostname.