Programs & Examples On #Examdiff

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

How to generate a unique hash code for string input in android...?

I use this i tested it as key from my EhCacheManager Memory map ....

Its cleaner i suppose

   /**
     * Return Hash256 of String value
     *
     * @param text
     * @return 
     */
    public static String getHash256(String text) {
        try {
            return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        } catch (Exception ex) {
            Logger.getLogger(HashUtil.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }

am using maven but this is the jar commons-codec-1.9.jar

How can I switch themes in Visual Studio 2012

For those who are using "High Contrast" windows themes but still want a regular Visual Studio theme you might notice that the theme selector drop down is disabled. You can still change it by doing the following...

  1. Going to the registry key: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0_Config\Themes (or whichever version of VS you are using)
  2. Export the key of the theme you want (it's a bunch of random letters / numbers) to a .reg file.
  3. Then copy the "high contrast" key's name (again random letters / numbers)
  4. Delete the high contrast key and then rename the dark theme to the copied name
  5. Then import the exported theme from the reg file.

This permanently sets the theme to the one you've chosen.

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

vertical & horizontal lines in matplotlib

If you want to add a bounding box, use a rectangle:

ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)

Rectangle doc

Free Barcode API for .NET

Could the Barcode Rendering Framework at Codeplex GitHub be of help?

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

Most efficient way to concatenate strings?

The most efficient is to use StringBuilder, like so:

StringBuilder sb = new StringBuilder();
sb.Append("string1");
sb.Append("string2");
...etc...
String strResult = sb.ToString();

@jonezy: String.Concat is fine if you have a couple of small things. But if you're concatenating megabytes of data, your program will likely tank.

Android AlertDialog Single Button

You could use this:

AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle("Title");
builder1.setMessage("my message");
builder1.setCancelable(true);
builder1.setNeutralButton(android.R.string.ok,
        new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        dialog.cancel();
    }
});

AlertDialog alert11 = builder1.create();
alert11.show();

How do I return the SQL data types from my query?

select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME='yourTable';

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.

Response::json() - Laravel 5.1

use the helper function in laravel 5.1 instead:

return response()->json(['name' => 'Abigail', 'state' => 'CA']);

This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:

/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response 
* @static 
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){

    return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}

How can I get the current PowerShell executing file?

If you are looking for the current directory in which the script is being executed, you can try this one:

$fullPathIncFileName = $MyInvocation.MyCommand.Definition
$currentScriptName = $MyInvocation.MyCommand.Name
$currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "")

Write-Host $currentExecutingPath

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

If you are using create-react-app on C9 just run this command to start

npm run start --public $C9_HOSTNAME

And access the app from whatever your hostname is (eg type $C_HOSTNAME in the terminal to get the hostname)

How to check if a file exists from inside a batch file

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

How to post SOAP Request from PHP

You might want to look here and here.

A Little code example from the first link:

<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
        print "Error: ". $fault;
        }
else if ($price == -1) {
        print "The book is not in the database.";
} else {
        // otherwise output the result
        print "The price of book number ". $param[isbn] ." is $". $price;
        }
// kill object
unset($client);
?>

What evaluates to True/False in R?

T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

Mvn install or Mvn package

From the Lifecycle reference, install will run the project's integration tests, package won't.

If you really need to not install the generated artifacts, use at least verify.

How can I get date in application run by node.js?

Node.js is a server side JS platform build on V8 which is chrome java-script runtime.

It leverages the use of java-script on servers too.

You can use JS Date() function or Date class.

How to extract svg as file from web page

1. Inspect the page with the svg on.

2. Click on the link that displays the imagine in full resolution.

3. Do CMD/CTRL+S

4. You are done!

Does :before not work on img elements?

Try this code

.button:after {
    content: ""
    position: absolute
    width: 70px
    background-image: url('../../images/frontapp/mid-icon.svg')
    display: inline-block
    background-size: contain
    background-repeat: no-repeat
    right: 0
    bottom: 0
}

How do I script a "yes" response for installing programs?

You just need to put -y with the install command.

For example: yum install <package_to_install> -y

How to compare character ignoring case in primitive types

This is how the JDK does it (adapted from OpenJDK 8, String.java/regionMatches):

static boolean charactersEqualIgnoringCase(char c1, char c2) {
  if (c1 == c2) return true;

  // If characters don't match but case may be ignored,
  // try converting both characters to uppercase.
  char u1 = Character.toUpperCase(c1);
  char u2 = Character.toUpperCase(c2);
  if (u1 == u2) return true;

  // Unfortunately, conversion to uppercase does not work properly
  // for the Georgian alphabet, which has strange rules about case
  // conversion.  So we need to make one last check before
  // exiting.
  return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}

I suppose that works for Turkish too.

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

How to download PDF automatically using js?

Please try this

_x000D_
_x000D_
(function ($) {
    $(document).ready(function(){
       function validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
           }
       
       if($('.submitclass').length){
            $('.submitclass').click(function(){
                $email_id = $('.custom-email-field').val();
                if (validateEmail($email_id)) {
                  var url= $(this).attr('pdf_url');
                  var link = document.createElement('a');
                  link.href = url;
                  link.download = url.split("/").pop();
                  link.dispatchEvent(new MouseEvent('click'));
                }
            });
       }
    });
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
        <div class="form-item form-type-textfield form-item-email-id form-group">
            <input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
        </div>
        <button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
_x000D_
_x000D_
_x000D_

Or use download attribute to tag in HTML5

WP -- Get posts by category?

Create a taxonomy field category (field name = post_category) and import it in your template as shown below:

<?php
          $categ = get_field('post_category');  
          $args = array( 'posts_per_page' => 6,
         'category_name' => $categ->slug );
          $myposts = get_posts( $args );
          foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
            //your code here
          <?php endforeach; 
          wp_reset_postdata();?>

How to get the version of ionic framework?

The method version on ionic object returns the current version in string format.

Getting the difference between two sets

If you use Guava (former Google Collections) library there is a solution:

SetView<Number> difference = com.google.common.collect.Sets.difference(test2, test1);

The returned SetView is a Set, it is a live representation you can either make immutable or copy to another set. test1 and test2 are left intact.

Can't append <script> element

Can try like this

var code = "<script></" + "script>";
$("#someElement").append(code);

The only reason you can't do "<script></script>" is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's HTML.

What's the easiest way to call a function every 5 seconds in jQuery?

Both setInterval and setTimeout can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suites you most and how to stop each of them.

What is the proper way to check if a string is empty in Perl?

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
{
    # empty
}

How can I put strings in an array, split by new line?

You don't need preg_* functions nor preg patterns nor str_replace within, etc .. in order to sucessfuly break a string into array by newlines. In all scenarios, be it Linux/Mac or m$, this will do.

<?php 

 $array = explode(PHP_EOL, $string);
 // ...  
 $string = implode(PHP_EOL, $array);

?>

PHP_EOL is a constant holding the line break character(s) used by the server platform.

Eclipse: Enable autocomplete / content assist

I am not sure if this has to be explicitly enabled anywhere..but for this to work in the first place you need to include the javadoc jar files with the related jars in your project. Then when you do a Cntrl+Space it shows autocomplete and javadocs.

Shortcut to open file in Vim

With Exuberant ctags, you can create tag files with file information:

ctags --extra=+f -R *

Then, open file from VIM with

:tag filename

You can also use <tab> to autocomplete file name.

const vs constexpr on variables

A constexpr symbolic constant must be given a value that is known at compile time. For example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    constexpr int c2 = n+7;   // Error: we don’t know the value of c2
    // ...
}

To handle cases where the value of a “variable” that is initialized with a value that is not known at compile time but never changes after initialization, C++ offers a second form of constant (a const). For Example:

?constexpr int max = 100; 
void use(int n)
{
    constexpr int c1 = max+7; // OK: c1 is 107
    const int c2 = n+7; // OK, but don’t try to change the value of c2
    // ...
    c2 = 7; // error: c2 is a const
}

Such “const variables” are very common for two reasons:

  1. C++98 did not have constexpr, so people used const.
  2. List item “Variables” that are not constant expressions (their value is not known at compile time) but do not change values after initialization are in themselves widely useful.

Reference : "Programming: Principles and Practice Using C++" by Stroustrup

How to cd into a directory with space in the name?

Instead of:

DOCS="/cygdrive/c/Users/my\ dir/Documents"

Try:

DOCS="/cygdrive/c/Users/my dir/Documents" 

This should work on any POSIX system.

How do I inject a controller into another controller in AngularJS

use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...

for more info about typescipt click here

Here one simple example I have created to share data between two controller using Typescript...

module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
    sharedData: any;
    constructor() {
        this.sharedData = "send this data to Controller";
    }
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);

//Create One controller for one purpose
export class FirstController {
    dataInCtrl1: any;
    //Don't forget to inject service to access data from service
    static $inject = ['CommonService']
    constructor(private commonService: CommonService) { }
    public getDataFromService() {
        this.dataInCtrl1 = this.commonService.sharedData;
    }
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
    dataInCtrl2: any;
    static $inject = ['CommonService']
    constructor(private commonService: CommonService) { }
    public getDataFromService() {
        this.dataInCtrl2 = this.commonService.sharedData;
    }
}
angular.module('app').controller('SecondController', SecondController);

}

how to dynamically add options to an existing select in vanilla javascript

.add() also works.

var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(option);

W3 School - try

Failed to load AppCompat ActionBar with unknown error in android studio

The solution to this problem depends on the version of the Android support library you're using:

Support library 26.0.0-beta2

This android support library version has a bug causing the mentioned problem

In your Gradle build file use:

compile 'com.android.support:appcompat-v7:26.0.0'

with:

buildToolsVersion '26.0.0' 

and

classpath 'com.android.tools.build:gradle:3.0.0-alpha8'

everything should work fine now.


Library version 28 (beta)

These new versions seem to suffer from similar difficulties again.

In your res/values/styles.xml modify the AppTheme style from

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

(note the added Base.)

Or alternatively downgrade the library until the problem is fixed:

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

Get only filename from url in php without any variable values which exist in the url

Use parse_url() as Pekka said:

<?php
$url = 'http://www.example.com/search.php?arg1=arg2';

$parts = parse_url($url);

$str = $parts['scheme'].'://'.$parts['host'].$parts['path'];

echo $str;
?>

http://codepad.org/NBBf4yTB

In this example the optional username and password aren't output!

Length of a JavaScript object

A nice way to achieve this (Internet Explorer 9+ only) is to define a magic getter on the length property:

Object.defineProperty(Object.prototype, "length", {
    get: function () {
        return Object.keys(this).length;
    }
});

And you can just use it like so:

var myObj = { 'key': 'value' };
myObj.length;

It would give 1.

Modifying a file inside a jar

Not sure if this help, but you can edit without extracting:

  1. Open the jar file from vi editor
  2. Select the file you want to edit from the list
  3. Press enter to open the file do the changers and save it pretty simple

Check the blog post for more details http://vinurip.blogspot.com/2015/04/how-to-edit-contents-of-jar-file-on-mac.html

Builder Pattern in Effective Java

You need to declare the Builder inner class as static.

Consult some documentation for both non-static inner classes and static inner classes.

Basically the non-static inner classes instances cannot exist without attached outer class instance.

Using putty to scp from windows to Linux

You need to tell scp where to send the file. In your command that is not working:

scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

The correct upload command, based on your comments, should be something like:

C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

If you are running the command from your home directory, you can use a relative path:

C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

PHP Error: Cannot use object of type stdClass as array (array and object issues)

StdClass object is accessed by using ->

foreach ($blogs as $blog) {
    $id         = $blog->id;
    $title  = $blog->title;
    $content    = $blog->content;
}

How to fill in form field, and submit, using javascript?

You can try something like this:

    <script type="text/javascript">
        function simulateLogin(userName)
        {
            var userNameField = document.getElementById("username");
            userNameField.value = userName;
            var goButton = document.getElementById("go");
            goButton.click();
        }

        simulateLogin("testUser");
</script>

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

generate random string for div id

Based on HTML 4, the id should start from letter:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

So, one of the solutions could be (alphanumeric):

  var length = 9;
  var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter

  // Convert it to base 36 (numbers + letters), and grab the first 9 characters
  // after the decimal.
  var id = prefix + Math.random().toString(36).substr(2, length);

Another solution - generate string with letters only:

  var length = 9;
  var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);

Flexbox Not Centering Vertically in IE

If you can define the parent's width and height, there's a simpler way to centralize the image without having to create a container for it.

For some reason, if you define the min-width, IE will recognize max-width as well.

This solution works for IE10+, Firefox and Chrome.

<div>
  <img src="http://placehold.it/350x150"/>
</div>

div {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: center;
    justify-content: center;
    -ms-flex-align: center;
    align-items: center;
    border: 1px solid orange;
    width: 100px;
    height: 100px;
}

img{
  min-width: 10%;
  max-width: 100%;
  min-height: 10%;
  max-height: 100%;
}

https://jsfiddle.net/HumbertoMendes/t13dzsmn/

Windows batch: sleep

timeout /t 10 /nobreak > NUL

/t specifies the time to wait in seconds

/nobreak won't interrupt the timeout if you press a key (except CTRL-C)

> NUL will suppress the output of the command

How to use the 'og' (Open Graph) meta tag for Facebook share

I built a tool for meta generation. It pre-configures entries for Facebook, Google+ and Twitter, and you can use it free here: http://www.groovymeta.com

To answer the question a bit more, OG tags (Open Graph) tags work similarly to meta tags, and should be placed in the HEAD section of your HTML file. See Facebook's best practises for more information on how to use OG tags effectively.

Does Java have a complete enum for HTTP response codes?

The best provider for http status code constants is likely to be Jetty's org.eclipse.jetty.http.HttpStatus class because:

  • there is a javadoc package in maven which is important if you search for the constant and only know the number -> just open the api docs page and search for the number
  • the constants contain the status code number itself.

Only thing I would improve: put the status code number in front of the text description in order to make auto-completion lookup more convient when you are starting with the code.

Easy way to turn JavaScript array into comma-separated list?

Actually, the toString() implementation does a join with commas by default:

var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto

I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

Reading file input from a multipart/form-data POST

I have implemented MultipartReader NuGet package for ASP.NET 4 for reading multipart form data. It is based on Multipart Form Data Parser, but it supports more than one file.

What is the difference between a var and val definition in Scala?

It's as simple as it name.

var means it can vary

val means invariable

Changing .gitconfig location on Windows

As someone who has been interested in this for a VERY LONG TIME. See from the manual:

$XDG_CONFIG_HOME/git/config - Second user-specific configuration file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/config will be used. Any single-valued variable set in this file will be overwritten by whatever is in ~/.gitconfig. It is a good idea not to create this file if you sometimes use older versions of Git, as support for this file was added fairly recently.

Which was only recently added. This dump is from 2.15.0.

Works for me.

Why doesn't Java allow overriding of static methods?

In Java (and many OOP languages, but I cannot speak for all; and some do not have static at all) all methods have a fixed signature - the parameters and types. In a virtual method, the first parameter is implied: a reference to the object itself and when called from within the object, the compiler automatically adds this.

There is no difference for static methods - they still have a fixed signature. However, by declaring the method static you have explicitly stated that the compiler must not include the implied object parameter at the beginning of that signature. Therefore, any other code that calls this must must not attempt to put a reference to an object on the stack. If it did do that, then the method execution would not work since the parameters would be in the wrong place - shifted by one - on the stack.

Because of this difference between the two; virtual methods always have a reference to the context object (i.e. this) so then it is possible to reference anything within the heap that belong to that instance of the object. But with static methods, since there is no reference passed, that method cannot access any object variables and methods since the context is not known.

If you wish that Java would change the definition so that a object context is passed in for every method, static or virtual, then you would in essence have only virtual methods.

As someone asked in a comment to the op - what is your reason and purpose for wanting this feature?

I do not know Ruby much, as this was mentioned by the OP, I did some research. I see that in Ruby classes are really a special kind of object and one can create (even dynamically) new methods. Classes are full class objects in Ruby, they are not in Java. This is just something you will have to accept when working with Java (or C#). These are not dynamic languages, though C# is adding some forms of dynamic. In reality, Ruby does not have "static" methods as far as I could find - in that case these are methods on the singleton class object. You can then override this singleton with a new class and the methods in the previous class object will call those defined in the new class (correct?). So if you called a method in the context of the original class it still would only execute the original statics, but calling a method in the derived class, would call methods either from the parent or sub-class. Interesting and I can see some value in that. It takes a different thought pattern.

Since you are working in Java, you will need to adjust to that way of doing things. Why they did this? Well, probably to improve performance at the time based on the technology and understanding that was available. Computer languages are constantly evolving. Go back far enough and there is no such thing as OOP. In the future, there will be other new ideas.

EDIT: One other comment. Now that I see the differences and as I Java/C# developer myself, I can understand why the answers you get from Java developers may be confusing if you are coming from a language like Ruby. Java static methods are not the same as Ruby class methods. Java developers will have a hard time understanding this, as will conversely those who work mostly with a language like Ruby/Smalltalk. I can see how this would also be greatly confusing by the fact that Java also uses "class method" as another way to talk about static methods but this same term is used differently by Ruby. Java does not have Ruby style class methods (sorry); Ruby does not have Java style static methods which are really just old procedural style functions, as found in C.

By the way - thanks for the question! I learned something new for me today about class methods (Ruby style).

What's the difference between a Python module and a Python package?

Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.

The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question.

How to change checkbox's border style in CSS?

Here is a pure CSS (no images) cross-browser solution based on Martin's Custom Checkboxes and Radio Buttons with CSS3 LINK: http://martinivanov.net/2012/12/21/imageless-custom-checkboxes-and-radio-buttons-with-css3-revisited/

Here is a jsFiddle: http://jsfiddle.net/DJRavine/od26wL6n/

I have tested this on the following browsers:

  • FireFox (41.0.2) (42)
  • Google Chrome (46.0.2490.80 m)
  • Opera (33.0.1990.43)
  • Internet Explorer (11.0.10240.16431 [Update Versions: 11.0.22])
  • Microsoft Edge (20.10240.16384.0)
  • Safari Mobile iPhone iOS9 (601.1.46)

_x000D_
_x000D_
label,_x000D_
input[type="radio"] + span,_x000D_
input[type="radio"] + span::before,_x000D_
label,_x000D_
input[type="checkbox"] + span,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
 _x000D_
label *,_x000D_
label *_x000D_
{_x000D_
    cursor: pointer;_x000D_
}_x000D_
 _x000D_
input[type="radio"],_x000D_
input[type="checkbox"]_x000D_
{_x000D_
    opacity: 0;_x000D_
    position: absolute;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span,_x000D_
input[type="checkbox"] + span_x000D_
{_x000D_
    font: normal 11px/14px Arial, Sans-serif;_x000D_
    color: #333;_x000D_
}_x000D_
 _x000D_
label:hover span::before,_x000D_
label:hover span::before_x000D_
{_x000D_
    -moz-box-shadow: 0 0 2px #ccc;_x000D_
    -webkit-box-shadow: 0 0 2px #ccc;_x000D_
    box-shadow: 0 0 2px #ccc;_x000D_
}_x000D_
 _x000D_
label:hover span,_x000D_
label:hover span_x000D_
{_x000D_
    color: #000;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span::before,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    content: "";_x000D_
    width: 12px;_x000D_
    height: 12px;_x000D_
    margin: 0 4px 0 0;_x000D_
    border: solid 1px #a8a8a8;_x000D_
    line-height: 14px;_x000D_
    text-align: center;_x000D_
     _x000D_
    -moz-border-radius: 100%;_x000D_
    -webkit-border-radius: 100%;_x000D_
    border-radius: 100%;_x000D_
     _x000D_
    background: #f6f6f6;_x000D_
    background: -moz-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -o-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: radial-gradient(#f6f6f6, #dfdfdf);_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before,_x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    color: #666;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:disabled + span,_x000D_
input[type="checkbox"]:disabled + span_x000D_
{_x000D_
    cursor: default;_x000D_
     _x000D_
    -moz-opacity: .4;_x000D_
    -webkit-opacity: .4;_x000D_
    opacity: .4;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    -moz-border-radius: 2px;_x000D_
    -webkit-border-radius: 2px;_x000D_
    border-radius: 2px;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before_x000D_
{_x000D_
    content: "\2022";_x000D_
    font-size: 30px;_x000D_
    margin-top: -1px;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    content: "\2714";_x000D_
    font-size: 12px;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="blue"] + span::before_x000D_
{_x000D_
    border: solid 1px blue;_x000D_
    background: #B2DBFF;_x000D_
    background: -moz-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -o-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: radial-gradient(#B2DBFF, #dfdfdf);_x000D_
}_x000D_
input[class="blue"]:checked + span::before_x000D_
{_x000D_
    color: darkblue;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="red"] + span::before_x000D_
{_x000D_
    border: solid 1px red;_x000D_
    background: #FF9593;_x000D_
    background: -moz-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -o-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: radial-gradient(#FF9593, #dfdfdf);_x000D_
}_x000D_
input[class="red"]:checked + span::before_x000D_
{_x000D_
    color: darkred;_x000D_
}
_x000D_
 <label><input type="radio" checked="checked" name="radios-01" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" disabled="disabled" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-02"  class="blue" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" class="blue" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" disabled="disabled" class="blue" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-03"  class="red" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" class="red" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" disabled="disabled" class="red" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="blue" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="blue" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="blue" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="red" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="red" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="red" /><span>disabled checkbox</span></label>
_x000D_
_x000D_
_x000D_

Java: is there a map function?

Since Java 8, there are some standard options to do this in JDK:

Collection<E> in = ...
Object[] mapped = in.stream().map(e -> doMap(e)).toArray();
// or
List<E> mapped = in.stream().map(e -> doMap(e)).collect(Collectors.toList());

See java.util.Collection.stream() and java.util.stream.Collectors.toList().

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

Add column with constant value to pandas dataframe

Super simple in-place assignment: df['new'] = 0

For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.

df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x

df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

Note for object columns

If you want to add an column of empty lists, here is my advice:

  • Consider not doing this. object columns are bad news in terms of performance. Rethink how your data is structured.
  • Consider storing your data in a sparse data structure. More information: sparse data structures
  • If you must store a column of lists, ensure not to copy the same reference multiple times.

    # Wrong
    df['new'] = [[]] * len(df)
    # Right
    df['new'] = [[] for _ in range(len(df))]
    

Generating a copy: df.assign(new=0)

If you need a copy instead, use DataFrame.assign:

df.assign(new='y')

   A  B  C new
0  x  x  x   y
1  x  x  x   y
2  x  x  x   y
3  x  x  x   y

And, if you need to assign multiple such columns with the same value, this is as simple as,

c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))

   A  B  C new1 new2
0  x  x  x    y    y
1  x  x  x    y    y
2  x  x  x    y    y
3  x  x  x    y    y

Multiple column assignment

Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary.

c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)

   A  B  C new1 new2 new3
0  x  x  x    w    y    z
1  x  x  x    w    y    z
2  x  x  x    w    y    z
3  x  x  x    w    y    z

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to best display in Terminal a MySQL SELECT returning too many fields?

Using mysql's ego command

From mysql's help command:

ego          (\G) Send command to mysql server, display result vertically.

So by appending a \G to your select, you can get a very clean vertical output:

mysql> SELECT * FROM sometable \G

Using a pager

You can tell MySQL to use the less pager with its -S option that chops wide lines and gives you an output that you can scroll with the arrow keys:

mysql> pager less -S

Thus, next time you run a command with a wide output, MySQL will let you browse the output with the less pager:

mysql> SELECT * FROM sometable;

If you're done with the pager and want to go back to the regular output on stdout, use this:

mysql> nopager

How to declare a global variable in a .js file

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

Java enum - why use toString instead of name

Use name() when you want to make a comparison or use the hardcoded value for some internal use in your code.

Use toString() when you want to present information to a user (including a developper looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

From the javadoc (emphasis mine) :

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

How do you get a directory listing sorted by creation date in python?

This was my version:

import os

folder_path = r'D:\Movies\extra\new\dramas' # your path
os.chdir(folder_path) # make the path active
x = sorted(os.listdir(), key=os.path.getctime)  # sorted using creation time

folder = 0

for folder in range(len(x)):
    print(x[folder]) # print all the foldername inside the folder_path
    folder = +1

HTML/JavaScript: Simple form validation on submit

You need to return the validating function. Something like:

onsubmit="return validateForm();"

Then the validating function should return false on errors. If everything is OK return true. Remember that the server has to validate as well.

How to leave space in HTML

The "pre" tag defines preformatted text. It preserves both spaces and line breaks.

<!DOCTYPE html>   
 <html>
        <body>
            <pre>This paragraph will be      pre-formatted. 
I hope this helps! 
All spaces will                    be shown as it is in the original file.
            </pre>
        </body>
 </html>

AndroidStudio: Failed to sync Install build tools

I had the same problem, in my cases this happened because I changed the time on my computer to load .apk on google play. I spent a few hours to fix "this" problem until I remembered and changed the time back.

Plugin with id 'com.google.gms.google-services' not found

Had the same problem.

Fixed by adding the dependency

classpath 'com.google.gms:google-services:3.0.0'

to the root build.gradle.

https://firebase.google.com/docs/android/setup#manually_add_firebase

How to compare two tables column by column in oracle

Try to use 3rd party tool, such as SQL Data Examiner which compares Oracle databases and shows you differences.

jQuery animate backgroundColor

ColorBlend plug in does exactly what u want

http://plugins.jquery.com/project/colorBlend

Here is the my highlight code

$("#container").colorBlend([{
    colorList:["white",  "yellow"], 
    param:"background-color",
    cycles: 1,
    duration: 500
}]);

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

If you want to apply some condition on form submit then you can use this method

<form onsubmit="return checkEmpData();" method="post" action="process.html">
  <input type="text" border="0" name="submit" />
  <button value="submit">submit</button>
</form>

One thing always keep in mind that method and action attribute write after onsubmit attributes

javascript code

function checkEmpData()
{
  var a = 0;

  if(a != 0)
  {
    return confirm("Do you want to generate attendance?");
  }
   else
   {
      alert('Please Select Employee First');
      return false;
   }  
}

Create a variable name with "paste" in R?

In my case the symbols I create (Tax1, Tax2, etc.) already had values but I wanted to use a loop and assign the symbols to another variable. So the above two answers gave me a way to accomplish this. This may be helpful in answering your question as the assignment of a value can take place anytime later.

output=NULL
for(i in 1:8){
   Tax=eval(as.symbol(paste("Tax",i,sep="")))
   L_Data1=L_Data_all[which(L_Data_all$Taxon==Tax[1] | L_Data_all$Taxon==Tax[2] | L_Data_all$Taxon==Tax[3] | L_Data_all$Taxon==Tax[4] | L_Data_all$Taxon==Tax[5]),]
   L_Data=L_Data1$Length[which(L_Data1$Station==Plant[1] | L_Data1$Station==Plant[2])]
   h=hist(L_Data,breaks=breaks,plot=FALSE)
   output=cbind(output,h$counts)
}

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

How to vertically center content with variable height within a div?

Just add

position: relative;
top: 50%;
transform: translateY(-50%);

to the inner div.

What it does is moving the inner div's top border to the half height of the outer div (top: 50%;) and then the inner div up by half its height (transform: translateY(-50%)). This will work with position: absolute or relative.

Keep in mind that transform and translate have vendor prefixes which are not included for simplicity.

Codepen: http://codepen.io/anon/pen/ZYprdb

Space between two divs

You can try something like the following:

h1{
   margin-bottom:<x>px;
}
div{
   margin-bottom:<y>px;
}
div:last-of-type{
   margin-bottom:0;
}

or instead of the first h1 rule:

div:first-of-type{
   margin-top:<x>px;
}

or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:

div + div{
   margin-bottom:<y>px;
}

Respectively, h1 + div would control the first div after your header, giving you additional styling options.

How to use: while not in

Using sets will be screaming fast if you have any volume of data

If you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.

MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])

while not MyList.isdisjoint(MyOper):
    print "No boolean Operator"

http://docs.python.org/library/stdtypes.html#set.isdisjoint

How do I read a string entered by the user in C?

On a POSIX system, you probably should use getline if it's available.

You also can use Chuck Falconer's public domain ggets function which provides syntax closer to gets but without the problems. (Chuck Falconer's website is no longer available, although archive.org has a copy, and I've made my own page for ggets.)

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

Try resetting your password since it seems it has changed you can reset your password by going to

C:\xampp\mysql

and clicking on the resetroot.bat file

Then change in the php config file the password back to blank and you should have access again

How to remove focus from single editText

For me this worked

Add these attributes to your EditText

android:focusable="true"
android:focusableInTouchMode="true"

After this in your code you can simply write

editText.clearFocus()

Android: combining text & image on a Button or ImageButton

MaterialButton has support for setting an icon and aligning it to the text:

<com.google.android.material.button.MaterialButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My button"
        app:icon="@drawable/your_icon"
        app:iconGravity="textStart"
        />

app:iconGravity can also be to start / end if you want to align the icon to the button instead of the text inside it.

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

How to check if any Checkbox is checked in Angular

If you have only one checkbox, you can do this easily with just ng-model:

<input type="checkbox" ng-model="checked"/>
<button ng-disabled="!checked"> Next </button>

And initialize $scope.checked in your Controller (default=false). The official doc discourages the use of ng-init in that case.

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

How to run different python versions in cmd

I would suggest using the Python Launcher for Windows utility that was introduced into Python 3.3. You can manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.

Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py, .pyw, .pyc, and .pyo files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX comments at the beginning of your Python scripts.

Hiding elements in responsive layout?

Additional CSS Remove Sidebar from all pages in Mobile view:

@media only screen and (max-width:767px)
{
#secondary {
display: none;
}
}

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

This version of the application is not configured for billing through Google Play

You need to sign your APK with your live certificate. Then install that onto your test device. You can then test InAppBilling. If you are testing your application by direct run via eclipse to device(In debug mode) then you will get this error.

If you are using android.test.purchased as the SKU, it will work all the way, but you won't have the developerPayload in your final response.

If you are using your own draft in app item you can test all the way but you will be charged and so will have to refund it yourself afterwards.

You cannot buy items with the same gmail account that you use for the google play development console.

How do I erase an element from std::vector<> by index?

To delete a single element, you could do:

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);

Or, to delete more than one element at once:

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);

How to use WHERE IN with Doctrine 2

I found that, despite what the docs indicate, the only way to get this to work is like this:

$ids = array(...); // Array of your values
$qb->add('where', $qb->expr()->in('r.winner', $ids));

http://groups.google.com/group/doctrine-dev/browse_thread/thread/fbf70837293676fb

Export MySQL database using PHP only

If you dont have phpMyAdmin, you can write in php CLI commands such as login to mysql and perform db dump. In this case you would use shell_exec function.

Adding a simple UIAlertView

UIAlertView *myAlert = [[UIAlertView alloc] 
                         initWithTitle:@"Title"
                         message:@"Message"
                         delegate:self
                         cancelButtonTitle:@"Cancel"
                         otherButtonTitles:@"Ok",nil];
[myAlert show];

Calculating time difference in Milliseconds

I pretty much like the (relatively) new java.time library: it's close to awesome, imho.

You can calculate a duration between two instants this way:

import java.time.*

Instant before = Instant.now();
// do stuff
Instant after = Instant.now();
long delta = Duration.between(before, after).toMillis(); // .toWhatsoever()

API is awesome, highly readable and intuitive.

Classes are thread-safe too. !


References: Oracle Tutorial, Java Magazine

How can I clear console

Here is a simple way to do it:

#include <iostream>

using namespace std;

int main()
{
    cout.flush(); // Flush the output stream
    system("clear"); // Clear the console with the "system" function
}

How to generate a HTML page dynamically using PHP?

You dont need to generate any dynamic html page, just use .htaccess file and rewrite the URL.

Hive: how to show all partitions of a table?

Okay, I'm writing this answer by extending wmky's answer above & also, assuming that you've configured mysql for your metastore instead of derby.

select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='<table_name>');

The above query gives you all possible values of the partition columns.

Example:

hive> desc clicks_fact;
OK
time                    timestamp                                   
..                              
day                     date                                        
file_date               varchar(8)                                  

# Partition Information      
# col_name              data_type               comment             

day                     date                                        
file_date               varchar(8)                                  
Time taken: 1.075 seconds, Fetched: 28 row(s)

I'm going to fetch the values of partition columns.

mysql> select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='clicks_fact');
+-----------------------------------+
| PART_NAME                         |
+-----------------------------------+
| day=2016-08-16/file_date=20160816 |
| day=2016-08-17/file_date=20160816 |
....
....
| day=2017-09-09/file_date=20170909 |
| day=2017-09-08/file_date=20170909 |
| day=2017-09-09/file_date=20170910 |
| day=2017-09-10/file_date=20170910 |
+-----------------------------------+

1216 rows in set (0.00 sec)

Returns all partition columns.

Note: JOIN table DBS ON DB_ID when there is a DB involved (i.e, when, multiple DB's have same table_name)

Make an HTTP request with android

Look at this awesome new library which is available via gradle :)

build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'

Usage:

new HttpRequestTask(
    new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
    new HttpRequest.Handler() {
      @Override
      public void response(HttpResponse response) {
        if (response.code == 200) {
          Log.d(this.getClass().toString(), "Request successful!");
        } else {
          Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
        }
      }
    }).execute();

https://github.com/erf/http-request

Angular no provider for NameService

The error No provider for NameService is a common issue that many Angular2 beginners face.

Reason: Before using any custom service you first have to register it with NgModule by adding it to the providers list:

Solution:

@NgModule({
    imports: [...],
    providers: [CustomServiceName]
})

'str' object has no attribute 'decode'. Python 3 error?

Other answers sort of hint at it, but the problem may arise from expecting a bytes object. In Python 3, decode is valid when you have an object of class bytes. Running encode before decode may "fix" the problem, but it is a useless pair of operations that suggest the problem us upstream.

How to provide shadow to Button

Use this approach to get your desired look.
button_selector.xml :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <layer-list>
        <item android:right="5dp" android:top="5dp">
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#D6D6D6" />
            </shape>
        </item>
        <item android:bottom="2dp" android:left="2dp">
            <shape>
                <gradient android:angle="270" 
                    android:endColor="#E2E2E2" android:startColor="#BABABA" />
                <stroke android:width="1dp" android:color="#BABABA" />
                <corners android:radius="4dp" />
                <padding android:bottom="10dp" android:left="10dp" 
                    android:right="10dp" android:top="10dp" />
            </shape>
        </item>
    </layer-list>
</item>

</selector>

And in your xml layout:

<Button
   android:background="@drawable/button_selector"
   ...
   ..
/>

Redirect after Login on WordPress

The accepted answer is clearly not a good answer! It may solve your problem for a while, but what will happen next time you update your WordPress installation? Your core files may get overridden and you will loose all your modifications.

As already stated by others (Dan and Travis answers), the correct answer is to use the login_redirect filter.

How to hide code from cells in ipython notebook visualized with nbviewer?

The accepted solution also works in julia Jupyter/IJulia with the following modifications:

display("text/html", """<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 \$("div.input").hide();
 } else {
 \$("div.input").show();
 }
 code_show = !code_show
} 
\$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>""")

note in particular:

  • use the display function
  • escape the $ sign (otherwise seen as a variable)

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

How to enable Ad Hoc Distributed Queries

The following command may help you..

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

Question mark characters displaying within text, why is this?

I had this issue so I just took all my content, copy/pasted it into notepad, made a new php file, pasted back in, re-saved and overwrote, and.. that worked! It really was some relic of Microsoft Word editing...

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

Getting and removing the first character of a string

See ?substring.

x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"

The idea of having a pop method that both returns a value and has a side effect of updating the data stored in x is very much a concept from object-oriented programming. So rather than defining a pop function to operate on character vectors, we can make a reference class with a pop method.

PopStringFactory <- setRefClass(
  "PopString",
  fields = list(
    x = "character"  
  ),
  methods = list(
    initialize = function(x)
    {
      x <<- x
    },
    pop = function(n = 1)
    {
      if(nchar(x) == 0)
      {
        warning("Nothing to pop.")
        return("")
      }
      first <- substring(x, 1, n)
      x <<- substring(x, n + 1)
      first
    }
  )
)

x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"

running php script (php function) in linux bash

Simply this should do:

php test.php

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

How to enable C++17 compiling in Visual Studio?

Visual Studio 2020 version

In tasks.json file, (after you build and debug with the g++-9)

Add -std=c++2a for 2020 features (c++1z for 2017 features). Add -fconcepts to use concept keyword

"args": [
   "-std=c++2a",
   "-fconcepts",
   "-g",
   "${file}",
   "-o",
   "${fileDirname}/${fileBasenameNoExtension}"
],

now compile and you can use the 2020 features.

How to validate a date?

This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.

For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):

console.log(new Date(2009, 1, 29));

The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)

Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):

var isActualDate = function (month, day, year) {
    var tempDate = new Date(year, --month, day);
    return month === tempDate.getMonth();
};

This isn't a complete solution and doesn't take i18n into account but it could be made more robust.

Change project name on Android Studio

To change the apps name in Android Studio:

  1. Close the project in Android studio and get rid of it from the quick start side of the launcher ( Should be a mini next to the name).

  2. Close Android Studio.

  3. Go into where your app file is located and rename it (Under My Documents Usually).

  4. Restart Android Studio, select add new project and navigate to the folder that was renamed.

Changing the label of the launcher of the application / The applications actual name:

  1. Go into your initial folder (app)
  2. Go into manifests
  3. Go into AndroidManifest.xml.
  4. Rename android:label= _____ to whatever you want to rename your app to

Eg: android:label="Developer Portal".

  1. Click Save All.

Mockito, JUnit and Spring

If you would migrate your project to Spring Boot 1.4, you could use new annotation @MockBean for faking MyDependentObject. With that feature you could remove Mockito's @Mock and @InjectMocks annotations from your test.

How can I add raw data body to an axios request?

There many methods to send raw data with a post request. I personally like this one.

    const url = "your url"
    const data = {key: value}
    const headers = {
        "Content-Type": "application/json"
    }
    axios.post(url, data, headers)

SQL Server SELECT LAST N Rows

use desc with orderby at the end of the query to get the last values.

Define a global variable in a JavaScript function

If you want the variable inside the function available outside of the function, return the results of the variable inside the function.

var x = function returnX { var x = 0; return x; } is the idea...

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">

        var offsetfrommouse = [10, -20];
        var displayduration = 0;
        var obj_selected = 0;

        function makeObj(address) {
            var trailimage = [address, 50, 50];
            document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0"  style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
            obj_selected = 1;
            return trailimage;
        }

        function truebody() {
            return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
        }

        function hidetrail() {
            var x = document.getElementById("trailimageid").style;
            x.visibility = "hidden";
            document.onmousemove = "";
        }

        function followmouse(e) {
            var xcoord = offsetfrommouse[0];
            var ycoord = offsetfrommouse[1];
            var x = document.getElementById("trailimageid").style;
            if (typeof e != "undefined") {
                xcoord += e.pageX;
                ycoord += e.pageY;
            }

            else if (typeof window.event != "undefined") {
                xcoord += truebody().scrollLeft + event.clientX;
                ycoord += truebody().scrollTop + event.clientY;
            }
            var docwidth = 1395;
            var docheight = 676;
            if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
                x.display = "none";
                alert("inja");
            }
            else
                x.display = "";
            x.left = xcoord + "px";
            x.top = ycoord + "px";
        }

        if (obj_selected = 1) {
            alert("obj_selected = true");
            document.onmousemove = followmouse;
            if (displayduration > 0)
                setTimeout("hidetrail()", displayduration * 1000);
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px; top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
    </form>
</body>
</html>

I haven't tested this, but if your code worked prior to that small change, then it should work.

How to print in C

In C, unlike say C++, you would need a format specifier that states the datatype of the variable you want to print-in this case %d as the data type is an integer . Try printf("%d",addNumbers(a,b));

Force sidebar height 100% using CSS (with a sticky bottom image)?

use body background if you are using fixed width sidebar give the same width image as your side bar. also put background-repeat:repeat-y in your css codes.

How do I change the text of a span element using JavaScript?

Using innerHTML is SO NOT RECOMMENDED. Instead, you should create a textNode. This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.

document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!

The right way:

span = document.getElementById("myspan");
txt = document.createTextNode("your cool text");
span.appendChild(txt);

For more information about this vulnerability: Cross Site Scripting (XSS) - OWASP

Edited nov 4th 2017:

Modified third line of code according to @mumush suggestion: "use appendChild(); instead".
Btw, according to @Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle. That way you won't encounter any surprises.

Word-wrap in an HTML table

A long shot, but double-check with Firebug (or similar) that you aren't accidentally inheriting the following rule:

white-space:nowrap;

This may override your specified line break behaviour.

PHP random string generator

There are a lot of answers to this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).

The simple, secure, and correct answer is to use RandomLib and don't reinvent the wheel.

For those of you who insist on inventing your own solution, PHP 7.0.0 will provide random_int() for this purpose; if you're still on PHP 5.x, we wrote a PHP 5 polyfill for random_int() so you can use the new API even before you upgrade to PHP 7.

Safely generating random integers in PHP isn't a trivial task. You should always check with your resident StackExchange cryptography experts before you deploy a home-grown algorithm in production.

With a secure integer generator in place, generating a random string with a CSPRNG is a walk in the park.

Creating a Secure, Random String

/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 *
 * This function uses type hints now (PHP 7+ only), but it was originally
 * written for PHP 5 as well.
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    int $length = 64,
    string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
    if ($length < 1) {
        throw new \RangeException("Length must be a positive integer");
    }
    $pieces = [];
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pieces []= $keyspace[random_int(0, $max)];
    }
    return implode('', $pieces);
}

Usage:

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();

Demo: https://3v4l.org/IMJGF (Ignore the PHP 5 failures; it needs random_compat)

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How to configure Glassfish Server in Eclipse manually

For Eclipse Luna

Go to Help>Eclipse MarketPlace> Search for GlassFish Tools and install it.

Restart Eclipse.

Now go to servers>new>server and you will find Glassfish server.

Communication between tabs or windows

This is a development storage part of Tomas M answer for Chrome. We must add listener

window.addEventListener("storage", (e)=> { console.log(e) } );

Load/save item in storage not runt this event - we MUST trigger it manually by

window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME

and now, all open tab-s will receive event

Adding data attribute to DOM

in Jquery "data" doesn't refresh by default :

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());

You'd use "attr" instead for live update:

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());

Creating a ZIP archive in memory using System.IO.Compression

Just another version of zipping without writing any file.

string fileName = "export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
byte[] fileBytes = here is your file in bytes
byte[] compressedBytes;
string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";

using (var outStream = new MemoryStream())
{
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    {
        var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
        using (var entryStream = fileInArchive.Open())
        using (var fileToCompressStream = new MemoryStream(fileBytes))
        {
            fileToCompressStream.CopyTo(entryStream);
        }
    }
    compressedBytes = outStream.ToArray();
}

HTML5 validation when the input type is not "submit"

The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.

However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.checkValidity()) {
    f.submit();
  } else {
    alert(document.getElementById('example').validationMessage);
  }
}

git pull remote branch cannot find remote ref

The branch name in Git is case sensitive. To see the names of your branches that Git 'sees' (including the correct casing), use:

git branch -vv

... and now that you can see the correct branch name to use, do this:

git pull origin BranchName 

where 'BranchName' is the name of your branch. Ensure that you match the case correctly

So in the OP's (Original Poster's) case, the command would be:

git pull origin DownloadManager

Draggable div without jQuery UI

here's another way of making a draggable object that is centered to the click

http://jsfiddle.net/pixelass/fDcZS/

function endMove() {
    $(this).removeClass('movable');
}

function startMove() {
    $('.movable').on('mousemove', function(event) {
        var thisX = event.pageX - $(this).width() / 2,
            thisY = event.pageY - $(this).height() / 2;

        $('.movable').offset({
            left: thisX,
            top: thisY
        });
    });
}
$(document).ready(function() {
    $("#containerDiv").on('mousedown', function() {
        $(this).addClass('movable');
        startMove();
    }).on('mouseup', function() {
        $(this).removeClass('movable');
        endMove();
    });

});

CSS

#containerDiv {
    background:#333;
    position:absolute;
    width:200px;
    height:100px;
}

What is the difference between char * const and const char *?

Here is a detailed explanation with code

/*const char * p;
char * const p; 
const char * const p;*/ // these are the three conditions,

// const char *p;const char * const p; pointer value cannot be changed

// char * const p; pointer address cannot be changed

// const char * const p; both cannot be changed.

#include<stdio.h>

/*int main()
{
    const char * p; // value cannot be changed
    char z;
    //*p = 'c'; // this will not work
    p = &z;
    printf(" %c\n",*p);
    return 0;
}*/

/*int main()
{
    char * const p; // address cannot be changed
    char z;
    *p = 'c'; 
    //p = &z;   // this will not work
    printf(" %c\n",*p);
    return 0;
}*/



/*int main()
{
    const char * const p; // both address and value cannot be changed
    char z;
    *p = 'c'; // this will not work
    p = &z; // this will not work
    printf(" %c\n",*p);
    return 0;
}*/

How to use if - else structure in a batch file?

A little bit late and perhaps still good for complex if-conditions, because I would like to add a "done" parameter to keep a if-then-else structure:

set done=0
if %F%==1 if %C%==0 (set done=1 & echo found F=1 and C=0: %F% + %C%)
if %F%==2 if %C%==0 (set done=1 & echo found F=2 and C=0: %F% + %C%)
if %F%==3 if %C%==0 (set done=1 & echo found F=3 and C=0: %F% + %C%)
if %done%==0 (echo do something)

How can I join elements of an array in Bash?

With re-use of @doesn't matters' solution, but with a one statement by avoiding the ${:1} substition and need of an intermediary variable.

echo $(printf "%s," "${LIST[@]}" | cut -d "," -f 1-${#LIST[@]} )

printf has 'The format string is reused as often as necessary to satisfy the arguments.' in its man pages, so that the concatenations of the strings is documented. Then the trick is to use the LIST length to chop the last sperator, since cut will retain only the lenght of LIST as fields count.

What do raw.githubusercontent.com URLs represent?

raw.githubusercontent.com/username/repo-name/branch-name/path

Replace username with the username of the user that created the repo.

Replace repo-name with the name of the repo.

Replace branch-name with the name of the branch.

Replace path with the path to the file.

To reverse to go to GitHub.com:

GitHub.com/username/repo-name/directory-path/blob/branch-name/filename

How to iterate through a DataTable

The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:

foreach (DataRow row in dtData.Rows)
        {
            if (row["Column_name"].ToString() == txtBox.Text)
            {
                // Getting the sequence number from the textbox.
                string strName1 = txtRowDeletion.Text;

                // Creating the SqlCommand object to access the stored procedure
                // used to get the data for the grid.
                string strDeleteData = "Sp_name";
                SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
                cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;

                // Running the query.
                conn.Open();
                cmdDeleteData.ExecuteNonQuery();
                conn.Close();

                GetData();

                dtData = (DataTable)Session["GetData"];
                BindGrid(dtData);

                lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
                txtRowDeletion.Text = "";
                break;
            }
            else
            {
                lblMsgForDeletion.Text = "The row is not present ";
            }
        }

How to "fadeOut" & "remove" a div in jQuery?

you really should try to use jQuery in a separate file, not inline. Here is what you need:

<a class="notificationClose "><img src="close.png"/></a>

And then this at the bottom of your page in <script> tags at the very least or in a external JavaScript file.

$(".notificationClose").click(function() {
    $("#notification").fadeOut("normal", function() {
        $(this).remove();
    });
});

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Message 'src refspec master does not match any' when pushing commits in Git

I faced similar error. The error was due to this command

git push -u origin master

subsequent commands worked for me

start with these commands

git init
git add .
git commit -m "second commit"

so before pushing it run these commands to see what remote repository on Github our local repository is connected to and which branch are you on.

git remote
git branch

remote -->origin

branch --> main

git push -u remote branch

or more specifically :

git push -u origin main

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Solution in ES6 for modern browsers and IE11 (with transpilation to ES5):

//Disable default IE help popup
window.onhelp = function() {
    return false;
};
window.onkeydown = evt => {
    switch (evt.keyCode) {
        //ESC
        case 27:
            this.onEsc();
            break;
        //F1
        case 112:
            this.onF1();
            break;
        //Fallback to default browser behaviour
        default:
            return true;
    }
    //Returning false overrides default browser event
    return false;
};

jQuery and TinyMCE: textarea value doesn't submit

You can also simply use the jQuery plugin and package for TinyMCE it sorts out these kinds of issues.

How to use Python's pip to download and keep the zipped files for a package?

pip install --download is deprecated. Starting from version 8.0.0 you should use pip download command:

 pip download <package-name>

Change an image with onclick()

function chkicon(num,allsize) {
    var  flagicon = document.getElementById("flagicon"+num).value;

    if(flagicon=="plus"){
         //alert("P== "+flagicon);

         for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }


         document.images["pic"+num].src = "../images/minus.gif";
         document.getElementById("flagicon"+num).value = "minus";

    }else if(flagicon=="minus"){
         //alert("M== "+flagicon);

          document.images["pic"+num].src  = "../images/plus.gif";    
          document.getElementById("flagicon"+num).value = "plus";

    }else{
          for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }
    }
}

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.

The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

What is the best way to search the Long datatype within an Oracle database?

First convert LONG type column to CLOB type then use LIKE condition, for example:

CREATE TABLE tbl_clob AS
   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

Differentiate between function overloading and function overriding

Overriding means, giving a different definition of an existing function with same parameters, and overloading means adding a different definition of an existing function with different parameters.

Example:

#include <iostream>

class base{
    public:
    //this needs to be virtual to be overridden in derived class
    virtual void show(){std::cout<<"I am base";}
    //this is overloaded function of the previous one
    void show(int x){std::cout<<"\nI am overloaded";} 
};

class derived:public base{
    public:
    //the base version of this function is being overridden
    void show(){std::cout<<"I am derived (overridden)";}
};


int main(){
    base* b;
    derived d;
    b=&d;
    b->show();  //this will call the derived overriden version
    b->show(6); // this will call the base overloaded function
}

Output:

I am derived (overridden)
I am overloaded

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Better way to shuffle two numpy arrays in unison

Shuffle any number of arrays together, in-place, using only NumPy.

import numpy as np


def shuffle_arrays(arrays, set_seed=-1):
    """Shuffles arrays in-place, in the same order, along axis=0

    Parameters:
    -----------
    arrays : List of NumPy arrays.
    set_seed : Seed value if int >= 0, else seed is random.
    """
    assert all(len(arr) == len(arrays[0]) for arr in arrays)
    seed = np.random.randint(0, 2**(32 - 1) - 1) if set_seed < 0 else set_seed

    for arr in arrays:
        rstate = np.random.RandomState(seed)
        rstate.shuffle(arr)

And can be used like this

a = np.array([1, 2, 3, 4, 5])
b = np.array([10,20,30,40,50])
c = np.array([[1,10,11], [2,20,22], [3,30,33], [4,40,44], [5,50,55]])

shuffle_arrays([a, b, c])

A few things to note:

  • The assert ensures that all input arrays have the same length along their first dimension.
  • Arrays shuffled in-place by their first dimension - nothing returned.
  • Random seed within positive int32 range.
  • If a repeatable shuffle is needed, seed value can be set.

After the shuffle, the data can be split using np.split or referenced using slices - depending on the application.

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

if it is just a format issue use ToShortDateString()

Casting LinkedHashMap to Complex Object

You can use ObjectMapper.convertValue(), either value by value or even for the whole list. But you need to know the type to convert to:

POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });

this is functionally same as if you did:

byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);

but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.

Generic List - moving an item within the list

Simplest way:

list[newIndex] = list[oldIndex];
list.RemoveAt(oldIndex);

EDIT

The question isn't very clear ... Since we don't care where the list[newIndex] item goes I think the simplest way of doing this is as follows (with or without an extension method):

    public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
    {
        T aux = list[newIndex];
        list[newIndex] = list[oldIndex];
        list[oldIndex] = aux;
    }

This solution is the fastest because it doesn't involve list insertions/removals.

How to set a variable to current date and date-1 in linux?

you should man date first

date +%Y-%m-%d
date +%Y-%m-%d -d yesterday

how to increase sqlplus column output length?

Actually, even that didn't work for me. When I executed "select dbms_metadata.get_ddl('TABLESPACE','TABLESPACE_NAME') from dual;" I again got only the first three lines, but this time each line was padded out to 15,000 characters. I was able to work around this with:

select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),80) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),160) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),240) from dual;

It sure seemed like there ought to be an easier way, but I couldn't seem to find it.

Use different Python version with virtualenv

For Debian (debian 9) Systems in 2019, I discovered a simple solution that may solve the problem from within the virtual environment.

Suppose the virtual environment were created via:

python3.7 -m venv myenv

but only has versions of python2 and python2.7, and you need the recent features of python3.7.

Then, simply running the command:

(myvenv) $ python3.7 -m venv --upgrade /home/username/path/to/myvenv/

will add python3.7 packages if they are already available on your system.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

What are all codecs and formats supported by FFmpeg?

ffmpeg -codecs

should give you all the info about the codecs available.

You will see some letters next to the codecs:

Codecs:
 D..... = Decoding supported
 .E.... = Encoding supported
 ..V... = Video codec
 ..A... = Audio codec
 ..S... = Subtitle codec
 ...I.. = Intra frame-only codec
 ....L. = Lossy compression
 .....S = Lossless compression

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

I had a bit of a dummy moment this morning when I realized what caused this issue for me.

The strange thing is that the request was failing in both Firefox and Chrome, but worked when I tried to access via Fiddler Web Debugger.

For me, the problem was I had mis-typed a character into one of the PHP files in the project. I didn't notice this until I checked Git for changes to the project.

In my case I had: m<?php runMyProgram(); ?>.

Once I erased the m, it started working again.

Java regex email

import java.util.Scanner;

public class CheckingTheEmailPassword {

    public static void main(String[] args) {
        String email = null;
        String password = null;
        Boolean password_valid = false;
        Boolean email_valid = false;

        Scanner input = new Scanner(System.in);
        do {
            System.out.println("Enter your email: ");
            email = input.nextLine();

            System.out.println("Enter your passsword: ");
            password = input.nextLine();

            // checks for words,numbers before @symbol and between "@" and ".".
            // Checks only 2 or 3 alphabets after "."
            if (email.matches("[\\w]+@[\\w]+\\.[a-zA-Z]{2,3}"))
                email_valid = true;
            else
                email_valid = false;

            // checks for NOT words,numbers,underscore and whitespace.
            // checks if special characters present
            if ((password.matches(".*[^\\w\\s].*")) &&
            // checks alphabets present
                    (password.matches(".*[a-zA-Z].*")) &&
                    // checks numbers present
                    (password.matches(".*[0-9].*")) &&
                    // checks length
                    (password.length() >= 8))
                password_valid = true;
            else
                password_valid = false;

            if (password_valid && email_valid)
                System.out.println(" Welcome User!!");
            else {
                if (!email_valid)
                    System.out.println(" Re-enter your email: ");
                if (!password_valid)
                    System.out.println(" Re-enter your password: ");
            }

        } while (!email_valid || !password_valid);

        input.close();

    }

}

Two div blocks on same line

I think now, the best practice is use display: inline-block;

look like this demo: https://jsfiddle.net/vjLw1z7w/

EDIT (02/2021):

Best practice now may be to using display: flex; flex-wrap: wrap; on div container and flex-basis: XX%; on div

look like this demo: https://jsfiddle.net/42L1emus/1/

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

java.time

Using java.time framework built into Java 8.

import java.time.LocalTime;
import java.time.LocalDateTime;

LocalDateTime now = LocalDateTime.now(); // 2015-11-19T19:42:19.224
// start of a day
now.with(LocalTime.MIN); // 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); // 2015-11-19T00:00
// end of a day
now.with(LocalTime.MAX); // 2015-11-19T23:59:59.999999999

How do you create optional arguments in php?

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

How can I style an Android Switch?

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.

Android: Reverse geocoding - getFromLocation

Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.

Geocoder call procedure, can be located in a Helper class

public static void getAddressFromLocation(
        final Location location, final Context context, final Handler handler) {
    Thread thread = new Thread() {
        @Override public void run() {
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());   
            String result = null;
            try {
                List<Address> list = geocoder.getFromLocation(
                        location.getLatitude(), location.getLongitude(), 1);
                if (list != null && list.size() > 0) {
                    Address address = list.get(0);
                    // sending back first address line and locality
                    result = address.getAddressLine(0) + ", " + address.getLocality();
                }
            } catch (IOException e) {
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            } finally {
                Message msg = Message.obtain();
                msg.setTarget(handler);
                if (result != null) {
                    msg.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putString("address", result);
                    msg.setData(bundle);
                } else 
                    msg.what = 0;
                msg.sendToTarget();
            }
        }
    };
    thread.start();
}

Here is the call to this Geocoder procedure in your UI Activity:

getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());

And the handler to show the results in your UI:

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String result;
        switch (message.what) {
        case 1:
            Bundle bundle = message.getData();
            result = bundle.getString("address");
            break;
        default:
            result = null;
        }
        // replace by what you need to do
        myLabel.setText(result);
    }   
}

Don't forget to put the following permission in your Manifest.xml

<uses-permission android:name="android.permission.INTERNET" />

DataGridView AutoFit and Fill

public void setHeight(DataGridView src)
{
    src.Height= src.ColumnHeadersVisible ? src.ColumnHeadersHeight : 0 +   src.Rows.OfType<DataGridViewRow>().Where(row => row.Visible).Sum(row => row.Height);
}

How to sum the values of one column of a dataframe in spark/scala

Using spark sql query..just incase if it helps anyone!

import org.apache.spark.sql.SparkSession 
import org.apache.spark.SparkConf 
import org.apache.spark.sql.functions._ 
import org.apache.spark.SparkContext 
import java.util.stream.Collectors

val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()

df.createOrReplaceTempView("steps")
val sum = spark.sql("select  sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28

How do you make a LinearLayout scrollable?

You need to wrap your linear layout with a scroll view

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout 
        android:id="@+id/container" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


    </LinearLayout>
</ScrollView>

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

I just think of Rebuild as performing the Clean first followed by the Build. Perhaps I am wrong ... comments?

Simple way to count character occurrences in a string

A character frequency count is a common task for some applications (such as education) but not general enough to warrant inclusion with the core Java APIs. As such, you'll probably need to write your own function.

How do you log content of a JSON object in Node.js?

This will for most of the objects for outputting in nodejs console

_x000D_
_x000D_
var util = require('util')_x000D_
function print (data){_x000D_
  console.log(util.inspect(data,true,12,true))_x000D_
  _x000D_
}_x000D_
_x000D_
print({name : "Your name" ,age : "Your age"})
_x000D_
_x000D_
_x000D_

Usage of $broadcast(), $emit() And $on() in AngularJS

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.


Visual demo:

Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview

Demonstrates the method calls:

  $scope.$on('eventEmitedName', function(event, data) ...
  $scope.broadcastEvent
  $scope.emitEvent

How to detect when a UIScrollView has finished scrolling

For all scrolls related to dragging interactions, this will be sufficient:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _isScrolling = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        _isScrolling = NO;
    }
}

Now, if your scroll is due to a programmatic setContentOffset/scrollRectVisible (with animated = YES or you obviously know when scroll is ended):

 - (void)scrollViewDidEndScrollingAnimation {
     _isScrolling = NO;
}

If your scroll is due to something else (like keyboard opening or keyboard closing), it seems like you'll have to detect the event with a hack because scrollViewDidEndScrollingAnimation is not useful either.

The case of a PAGINATED scroll view:

Because, I guess, Apple apply an acceleration curve, scrollViewDidEndDecelerating get called for every drag so there's no need to use scrollViewDidEndDragging in this case.

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

How do you check for permissions to write to a directory or file?

None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..

/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
    if (string.IsNullOrEmpty(DirectoryPath)) return false;

    try
    {
        AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        WindowsIdentity identity = WindowsIdentity.GetCurrent();

        foreach (FileSystemAccessRule rule in rules)
        {
            if (identity.Groups.Contains(rule.IdentityReference))
            {
                if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
                {
                    if (rule.AccessControlType == AccessControlType.Allow)
                        return true;
                }
            }
        }
    }
    catch {}
    return false;
}

How can I call the 'base implementation' of an overridden virtual method?

Using the C# language constructs, you cannot explicitly call the base function from outside the scope of A or B. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.

You can from inside B.X however call A.X

class B : A
{
  override void X() { 
    base.X();
    Console.WriteLine("y"); 
  }
}

But that's something else.

As Sasha Truf points out in this answer, you can do it through IL. You can probably also accomplish it through reflection, as mhand points out in the comments.

Disable the postback on an <ASP:LinkButton>

In C#, you'd do something like this:

MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");

How to make (link)button function as hyperlink?

you can use linkbutton for navigating to another section in the same page by using PostBackUrl="#Section2"

Python Remove last 3 characters of a string

What's wrong with this?

foo.replace(" ", "")[:-3].upper()

What is the => assignment in C# in a property signature

It is called Expression Bodied Member and it was introduced in C# 6. It is merely syntactic sugar over a get only property.

It is equivalent to:

public int MaxHealth { get { return Memory[Address].IsValid ?
                             Memory[Address].Read<int>(Offs.Life.MaxHp) : 0; }

An equivalent of a method declaration is avaliable:

public string HelloWorld() => "Hello World";

Mainly allowing you shortening of boilerplate.

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

C/C++ maximum stack size of program

Platform-dependent, toolchain-dependent, ulimit-dependent, parameter-dependent.... It is not at all specified, and there are many static and dynamic properties that can influence it.

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

I got the same error and the cause was the directory:

U:.....WEB\WebRoot\WEB-INF\classes\com\yourcompany\cc\dao

was corrupted(directory or file not readable or damaged).. solved with

  • renaming the directory WEB-INF\classes as WEB-INF\classes_old
  • Eclipse's Project menu--> Clean (to recreate directories)
  • redeploy --> restart server.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

To simply explain the difference,

  response.sendRedirect("login.jsp");

doesn't prepend the contextpath (refers to the application/module in which the servlet is bundled)

but, whereas

 request.getRequestDispathcer("login.jsp").forward(request, response);

will prepend the contextpath of the respective application

Furthermore, Redirect request is used to redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url.

Forward request is used to forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved.

SQL Server SELECT INTO @variable?

"SELECT *
  INTO 
    @TempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId"

Which means creating a new @tempCustomer tablevariable and inserting data FROM Customer. You had already declared it above so no need of again declaring. Better to go with

INSERT INTO @tempCustomer SELECT * FROM Customer

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

If a DOM Element is removed, are its listeners also removed from memory?

Yes, the garbage collector will remove them as well. Might not always be the case with legacy browsers though.

Jupyter/IPython Notebooks: Shortcut for "run all"?

For the latest jupyter notebook, (version 5) you can go to the 'help' tab in the top of the notebook and then select the option 'edit keyboard shortcuts' and add in your own customized shortcut for the 'run all' function.

How to have a a razor action link open in a new tab?

If your goal is to use the ActionLink helper and open a new tab:

@Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })

@Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})