Programs & Examples On #Alias method

Should I use alias or alias_method?

A point in favor of alias instead of alias_method is that its semantic is recognized by rdoc, leading to neat cross references in the generated documentation, while rdoc completely ignore alias_method.

Add SUM of values of two LISTS into new LIST

Here is another way to do it.It is working fine for me .

N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")

'Connect-MsolService' is not recognized as the name of a cmdlet

This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.

To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell

2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.

Import-Module MSOnline 

After it complete, we can use this command to check it.

PS C:\Users> Get-Module -ListAvailable -Name MSOnline*


    Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.1.166.0  MSOnline                            {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest   1.1.166.0  MSOnlineExtended                    {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}

More information about this issue, please refer to it.


Update:

We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.

enter image description here

How to determine whether a given Linux is 32 bit or 64 bit?

I can't believe that in all this time, no one has mentioned:

sudo lshw -class cpu

to get details about the speed, quantity, size and capabilities of the CPU hardware.

How to do a newline in output

You can do this all in the File.open block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'

File.open playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z
  end
end

Why does visual studio 2012 not find my tests?

The problem was that the test runner, is configured to not run tests from a remote drive. When I copied the project to a local drive it worked fine, but I needed it on a shared drive (can not remember why).

I read that it can be configured to work from a shared drive, but never got to do it as by the time I discovered the solution I had switched to MonoDevelop on Debian.

How to check if image exists with given url?

Use Case

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API :

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

Note : rm means here risk managment .


Another Use Case :

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • 'http://example/1.png' : if not exist 'http://example/2.png'

  • 'http://example/2.png' : if not exist 'http://example/3.png'

Token based authentication in Web API without any user interface

I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.

You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.

Here's some client side C# code to get a token:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

In order to use the token add it to the header of the request:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

Where Token is:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

Now for the server side:

In Startup.Auth.cs

        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

And in ApplicationOAuthProvider.cs the code that actually grants or denies access:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.

Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.

You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.

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.

How to reload .bashrc settings without logging out and back in again?

Someone edited my answer to add incorrect English, but here was the original, which is inferior to the accepted answer.

. .bashrc

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

What to return if Spring MVC controller method doesn't return value?

But as your system grows in size and functionality... i think that returning always a json is not a bad idea at all. Is more a architectural / "big scale design" matter.

You can think about returing always a JSON with two know fields : code and data. Where code is a numeric code specifying the success of the operation to be done and data is any aditional data related with the operation / service requested.

Come on, when we use a backend a service provider, any service can be checked to see if it worked well.

So i stick, to not let spring manage this, exposing hybrid returning operations (Some returns data other nothing...).. instaed make sure that your server expose a more homogeneous interface. Is more simple at the end of the day.

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

Grid of responsive squares

You could use vw (view-width) units, which would make the squares responsive according to the width of the screen.

A quick mock-up of this would be:

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
div {_x000D_
  height: 25vw;_x000D_
  width: 25vw;_x000D_
  background: tomato;_x000D_
  display: inline-block;_x000D_
  text-align: center;_x000D_
  line-height: 25vw;_x000D_
  font-size: 20vw;_x000D_
  margin-right: -4px;_x000D_
  position: relative;_x000D_
}_x000D_
/*demo only*/_x000D_
_x000D_
div:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: inherit;_x000D_
  width: inherit;_x000D_
  background: rgba(200, 200, 200, 0.6);_x000D_
  transition: all 0.4s;_x000D_
}_x000D_
div:hover:before {_x000D_
  background: rgba(200, 200, 200, 0);_x000D_
}
_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
<div>4</div>_x000D_
<div>5</div>_x000D_
<div>6</div>_x000D_
<div>7</div>_x000D_
<div>8</div>
_x000D_
_x000D_
_x000D_

jQuery multiple events to trigger the same function

The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.

I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:

  • 2.0.2
  • 1.10.1
  • 1.6.4
  • Mobile 1.3.0b1
  • Mobile 1.4.2
  • Mobile 1.2.0

My workaround have been to first define the function,

function myFunction() {
    ...
}

and then handle the events individually

// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);

This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

How can I customize the tab-to-space conversion factor?

We can control tab size by file type with EditorConfig and its EditorConfig for VS Code extension. We then can make Alt + Shift + F specific to each file type.

Installation

Open the VS Code command palette with CTRL + P and paste this:

ext install EditorConfig

Example Configuration

.editorconfig

[*]
indent_style = space

[*.{js,ts,json}]
indent_size = 2

[*.java]
indent_size = 4

[*.go]
indent_style = tab

settings.json

EditorConfig overrides whatever settings.json configures for the editor. There is no need to change editor.detectIndentation.

What is the default username and password in Tomcat?

Check the file in <TOMCAT_HOME>/conf named tomcat-users.xml.
If you don't find something there edit to look something like:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="admin"/>
  <user username="admin" password="password" roles="standard,manager,admin"/>
</tomcat-users>

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

Converting string format to datetime in mm/dd/yyyy

You are looking for the DateTime.Parse() method (MSDN Article)

So you can do:

var dateTime = DateTime.Parse("01/01/2001");

Which will give you a DateTime typed object.

If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)

Which you would use in a situation like this (Where you are using a British style date format):

string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);

How does one target IE7 and IE8 with valid CSS?

I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.

 <!--[if IE 7]>
   <link rel="stylesheet" type="text/css" href="ie7.css" />
 <![endif]-->

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.

An example using Smarty:

Template File

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>

Code

function TestBlockHTML(){
  $smarty = new Smarty();
  $smarty->assign('title', 'My Title');
  $smarty->assign('string', $replStr);
  return $smarty->render('template.tpl');
}

How to put sshpass command inside a bash script?

1 - You can script sshpass's ssh command like this:

#!/bin/bash

export SSHPASS=password
sshpass -e ssh -oBatchMode=no user@host

2 - You can script sshpass's sftp commandlike this:

#!/bin/bash

export SSHPASS=password

sshpass -e sftp -oBatchMode=no -b - user@host << !
   put someFile
   get anotherFile
   bye
!

Python loop for inside lambda

To add on to chepner's answer for Python 3.0 you can alternatively do:

x = lambda x: list(map(print, x))

Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.

I'll just leave this here for reference.

Abstract class in Java

An abstract class is a class that is declared abstract — it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

In other words, a class that is declared with abstract keyword, is known as abstract class in java. It can have abstract(method without body) and non-abstract methods (method with body).

Important Note:- Abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time Polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature in the below example

abstract class Bike{  
  abstract void run();  
}  

class Honda4 extends Bike{  
    void run(){
        System.out.println("running safely..");
    }  

    public static void main(String args[]){  
       Bike obj = new Honda4();  
       obj.run();  
    }  
} 

whitespaces in the path of windows filepath

There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()

C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
 Volume in drive C has no label.
 Volume Serial Number is 46A0-BB64

 Directory of c:\ABC\SEM 2\testfiles

13/02/2013  10:20 PM    <DIR>          .
13/02/2013  10:20 PM    <DIR>          ..
13/02/2013  10:20 PM                 0 all.txt
               1 File(s)              0 bytes
               2 Dir(s)  78,929,309,696 bytes free

C:\Users\Gnibbler>

Associating existing Eclipse project with existing SVN repository

I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)

subclipse not showing "share project" option on project context menu in eclipse

Getting attribute of element in ng-click function in angularjs

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value;

Which would return exampleData.

Here's a full jsFiddle.

Define an alias in fish shell

make a function in ~/.config/fish/functions called mkalias.fish and put this in

function mkalias --argument key value
  echo alias $key=$value
  alias $key=$value
  funcsave $key
end

and this will create aliases automatically.

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

bootstrap 3 tabs not working properly

My problem was with extra </div> tag inside the first tab.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

Simply go to /opt/lampp/var/mysql

There You can find your database name. Open that folder. Remove if any files in it

Now come to phpmyadmin and drop that database

Java reflection: how to get field value from an object, not knowing its class

public abstract class Refl {
    /** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
    public static<T> T get(Object obj, String fieldPath) {
        return (T) getValue(obj, fieldPath);
    }
    public static Object getValue(Object obj, String fieldPath) {
        String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
        String success = "";
        Object res = obj;
        for (String fieldName : fieldNames) {
            if (fieldName.isEmpty()) continue;
            int index = toIndex(fieldName);
            if (index >= 0) {
                try {
                    res = ((Object[])res)[index];
                } catch (ClassCastException cce) {
                    throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
                } catch (IndexOutOfBoundsException iobe) {
                    throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
                }
            } else {
                Field field = getField(res.getClass(), fieldName);
                field.setAccessible(true);
                try {
                    res = field.get(res);
                } catch (Exception ee) {
                    throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
                }
            }
            success += fieldName + ".";
        }
        return res;
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        Class<?> tmpClass = clazz;
        do {
            try {
                Field f = tmpClass.getDeclaredField(fieldName);
                return f;
            } catch (NoSuchFieldException e) {
                tmpClass = tmpClass.getSuperclass();
            }
        } while (tmpClass != null);

        throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
    }

    private static int toIndex(String s) {
        int res = -1;
        if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
            try {
                res = Integer.parseInt(s);
                if (res < 0) {
                    res = -1;
                }
            } catch (Throwable t) {
                res = -1;
            }
        }
        return res;
    }
}

It supports fetching fields and array items, e.g.:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));

there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));

Failed to start mongod.service: Unit mongod.service not found

Just follow the below commands. This has worked for me.

  1. Uninstall your mongo completely from your system:

    sudo service mongod stop
    sudo apt-get purge mongodb-org
    sudo rm -r /var/log/mongodb
    sudo rm -r /var/lib/mongodb
    
  2. Now reinstall mongodb using following commands:

    sudo apt update
    sudo apt install -y mongodb**
    

    Note: The database server is automatically started after installation.

  3. Next, let's verify that the server is running and works correctly.

    sudo systemctl status mongodb
    

    You'll see this output:

    mongodb.service - An object/document-oriented database
    Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
    Active: active (running) since Sat 2018-05-26 07:48:04 UTC; 2min 17s ago
    Docs: man:mongod(1)
    Main PID: 2312 (mongod)
    Tasks: 23 (limit: 1153)
    CGroup: /system.slice/mongodb.service
       +-2312 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf**
    

how to find 2d array size in c++

Suppose you were only allowed to use array then you could find the size of 2-d array by the following way.

  int ary[][5] = { {1, 2, 3, 4, 5},
                   {6, 7, 8, 9, 0}
                 };

  int rows =  sizeof ary / sizeof ary[0]; // 2 rows  

  int cols = sizeof ary[0] / sizeof(int); // 5 cols

Clear Cache in Android Application programmatically

The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

compile 'commons-io:commons-io:2.4'

remove inner shadow of text input

Set border: 1px solid black to make all sides equals and remove any kind of custom border (other than solid). Also, set box-shadow: none to remove any inset shadow applied to it.

Sleep function in C++

For Windows:

#include "windows.h" 
Sleep(10);

For Unix:

#include <unistd.h>
usleep(10)

How to use the IEqualityComparer

Your GetHashCode implementation always returns the same value. Distinct relies on a good hash function to work efficiently because it internally builds a hash table.

When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1

In your code, the solution is to forward GetHashCode to Class_reglement.Numf.GetHashCode and implement it appropriately there.

Apart from that, your Equals method is full of unnecessary code. It could be rewritten as follows (same semantics, ¼ of the code, more readable):

public bool Equals(Class_reglement x, Class_reglement y)
{
    return x.Numf == y.Numf;
}

Lastly, the ToList call is unnecessary and time-consuming: AddRange accepts any IEnumerable so conversion to a List isn’t required. AsEnumerable is also redundant here since processing the result in AddRange will cause this anyway.


1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.

Error: stray '\240' in program

I faced the same problem due to illegal spaces in my entire code.

I fixed it by selecting one of these spaces and use find and replace to replace all matches with regular spaces.

missing FROM-clause entry for table

Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid

how to stop a for loop

Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.

setting content between div tags using javascript

See Creating and modifying HTML at what used to be called the Web Standards Curriculum.

Use the createElement, createTextNode and appendChild methods.

What's the right way to decode a string that has special HTML entities in it?

This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

Example: http://jsfiddle.net/k65s3/

Input:

Entity:&nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Output:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Python, remove all non-alphabet chars from string

If you prefer not to use regex, you might try

''.join([i for i in s if i.isalpha()])

python save image from url

import requests

img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
    handler.write(img_data)

static linking only some libraries

The problem as I understand it is as follows. You have several libraries, some static, some dynamic and some both static and dynamic. gcc's default behavior is to link "mostly dynamic". That is, gcc links to dynamic libraries when possible but otherwise falls back to static libraries. When you use the -static option to gcc the behavior is to only link static libraries and exit with an error if no static library can be found, even if there is an appropriate dynamic library.

Another option, which I have on several occasions wished gcc had, is what I call -mostly-static and is essentially the opposite of -dynamic (the default). -mostly-static would, if it existed, prefer to link against static libraries but would fall back to dynamic libraries.

This option does not exist but it can be emulated with the following algorithm:

  1. Constructing the link command line with out including -static.

  2. Iterate over the dynamic link options.

  3. Accumulate library paths, i.e. those options of the form -L<lib_dir> in a variable <lib_path>

  4. For each dynamic link option, i.e. those of the form -l<lib_name>, run the command gcc <lib_path> -print-file-name=lib<lib_name>.a and capture the output.

  5. If the command prints something other than what you passed, it will be the full path to the static library. Replace the dynamic library option with the full path to the static library.

Rinse and repeat until you've processed the entire link command line. Optionally the script can also take a list of library names to exclude from static linking.

The following bash script seems to do the trick:

#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage: $0 [--exclude <lib_name>]. . . <link_command>"
fi

exclude=()
lib_path=()

while [ $# -ne 0 ]; do
    case "$1" in
        -L*)
            if [ "$1" == -L ]; then
                shift
                LPATH="-L$1"
            else
                LPATH="$1"
            fi

            lib_path+=("$LPATH")
            echo -n "\"$LPATH\" "
            ;;

        -l*)
            NAME="$(echo $1 | sed 's/-l\(.*\)/\1/')"

            if echo "${exclude[@]}" | grep " $NAME " >/dev/null; then
                echo -n "$1 "
            else
                LIB="$(gcc $lib_path -print-file-name=lib"$NAME".a)"
                if [ "$LIB" == lib"$NAME".a ]; then
                    echo -n "$1 "
                else
                    echo -n "\"$LIB\" "
                fi
            fi
            ;;

        --exclude)
            shift
            exclude+=(" $1 ")
            ;;

        *) echo -n "$1 "
    esac

    shift
done

echo

For example:

mostlyStatic gcc -o test test.c -ldl -lpthread

on my system returns:

gcc -o test test.c "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libdl.a" "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"

or with an exclusion:

mostlyStatic --exclude dl gcc -o test test.c -ldl -lpthread

I then get:

gcc -o test test.c -ldl "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"

Returning a value from callback function in Node.js

Example code for node.js - async function to sync function:

var deasync = require('deasync');

function syncFunc()
{
    var ret = null;
    asyncFunc(function(err, result){
        ret = {err : err, result : result}
    });

    while((ret == null))
    {
         deasync.runLoopOnce();
    }

    return (ret.err || ret.result);
}

ngFor with index as value in attribute

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

R - argument is of length zero in if statement

The same error message results not only for null but also for e.g. factor(0). In this case, the query must be if(length(element) > 0 & otherCondition) or better check both cases with if(!is.null(element) & length(element) > 0 & otherCondition).

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

In PANDAS, how to get the index of a known value?

I think this may help you , both index and columns of the values.

value you are looking for is not duplicated:

poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()

you can get its index and column

duplicated:

matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]: 
   f    h
q  1  1.0
g  1  NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]

you will get a list

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Avoid using Xcode to rename files in a folder reference. If you rename a file using Xcode, it will be marked for commit. If you later delete it before the commit, you will end up with this error.

How to force Selenium WebDriver to click on element which is not currently visible?

I just solve this error by waiting element display property

waitFor() { element.displayed }

The SQL OVER() clause - when and why is it useful?

  • Also Called Query Petition Clause.
  • Similar to the Group By Clause

    • break up data into chunks (or partitions)
    • separate by partition bounds
    • function performs within partitions
    • re-initialised when crossing parting boundary

Syntax:
function (...) OVER (PARTITION BY col1 col3,...)

  • Functions

    • Familiar functions such as COUNT(), SUM(), MIN(), MAX(), etc
    • New Functions as well (eg ROW_NUMBER(), RATION_TO_REOIRT(), etc.)


More info with example : http://msdn.microsoft.com/en-us/library/ms189461.aspx

What are the dark corners of Vim your mom never told you about?

I use Vim for everything. When I'm editing an e-mail message, I use:

gqap (or gwap)

extensively to easily and correctly reformat on a paragraph-by-paragraph basis, even with quote leadin characters. In order to achieve this functionality, I also add:

-c 'set fo=tcrq' -c 'set tw=76'

to the command to invoke the editor externally. One noteworthy addition would be to add 'a' to the fo (formatoptions) parameter. This will automatically reformat the paragraph as you type and navigate the content, but may interfere or cause problems with errant or odd formatting contained in the message.

How to check whether a Storage item is set?

How can one test existence of an item in localStorage? this method works in internet explorer.

<script>
    try{
        localStorage.getItem("username");
    }catch(e){
        alert("we are in catch "+e.print);
    }
</script>

Java Calendar, getting current month value, clarification needed

Months in Java Calendar are 0-indexed. Calendar.JANUARY isn't a field so you shouldn't be passing it in to the get method.

How do I print a double value with full precision using cout?

Here is a function that works for any floating-point type, not just double, and also puts the stream back the way it was found afterwards. Unfortunately it won't interact well with threads, but that's the nature of iostreams. You'll need these includes at the start of your file:

#include <limits>
#include <iostream>

Here's the function, you could it in a header file if you use it a lot:

template <class T>
void printVal(std::ostream& os, T val)
{
    auto oldFlags = os.flags();
    auto oldPrecision = os.precision();

    os.flags(oldFlags & ~std::ios_base::floatfield);
    os.precision(std::numeric_limits<T>::digits10);
    os << val;
    
    os.flags(oldFlags);
    os.precision(oldPrecision);
}

Use it like this:

double d = foo();
float f = bar();
printVal(std::cout, d);
printVal(std::cout, f);

If you want to be able to use the normal insertion << operator, you can use this extra wrapper code:

template <class T>
struct PrintValWrapper { T val; };
template <class T>
std::ostream& operator<<(std::ostream& os, PrintValWrapper<T> pvw) {
    printVal(os, pvw.val);
    return os;
}
template <class T>
PrintValWrapper<T> printIt(T val) {
    return PrintValWrapper<T>{val};
}

Now you can use it like this:

double d = foo();
float f = bar();
std::cout << "The values are: " << printIt(d) << ", " << printIt(f) << '\n';

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

Maintain/Save/Restore scroll position when returning to a ListView

use this below code :

int index,top;

@Override
protected void onPause() {
    super.onPause();
    index = mList.getFirstVisiblePosition();

    View v = challengeList.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
}

and whenever your refresh your data use this below code :

adapter.notifyDataSetChanged();
mList.setSelectionFromTop(index, top);

Assign result of dynamic sql to variable

Sample to execute an SQL string within the stored procedure:

(I'm using this to compare the number of entries on each table as first check for a regression test, within a cursor loop)

select @SqlQuery1 = N'select @CountResult1 = (select isnull(count(*),0) from ' + @DatabaseFirst+'.dbo.'+@ObjectName + ')'

execute sp_executesql    @SqlQuery1 , N'@CountResult1 int OUTPUT',     @CountResult1 = @CountResult1 output;

Maven dependency for Servlet 3.0 API?

Try this code...

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0-alpha-1</version>
    </dependency>

Convert normal Java Array or ArrayList to Json Array in android

My code to convert array to Json

Code

List<String>a = new ArrayList<String>();
a.add("so 1");
a.add("so 2");
a.add("so 3");
JSONArray jray = new JSONArray(a);

System.out.println(jray.toString()); 

output

["so 1","so 2","so 3"]

How do I disable a Button in Flutter?

Enable and Disable functionality is same for most of the widgets.

Ex, button , switch, checkbox etc.

Just set the onPressed property as shown below

onPressed : null returns Disabled widget

onPressed : (){} or onPressed : _functionName returns Enabled widget

Write Array to Excel Range

You could put your data into a recordset and use Excel's CopyFromRecordset Method - it's much faster than populating cell-by-cell.

You can create a recordset from a dataset using this code. You will have to do some trials to see if using this method is faster than what you are currently doing.

I want to align the text in a <td> to the top

https://developer.mozilla.org/en/CSS/vertical-align

<table style="height: 275px; width: 188px">
    <tr>
        <td style="width: 259px; vertical-align:top">
            main page
        </td>
    </tr>
</table>

?

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Collision Detection between two images in Java

Use a rectangle to surround each player and enemy, the height and width of the rectangles should correspond to the object you're surrounding, imagine it being in a box only big enough to fit it.

Now, you move these rectangles the same as you do the objects, so they have a 'bounding box'

I'm not sure if Java has this, but it might have a method on the rectangle object called .intersects() so you'd do if(rectangle1.intersectS(rectangle2) to check to see if an object has collided with another.

Otherwise you can get the x and y co-ordinates of the boxes and using the height/width of them detect whether they've intersected yourself.

Anyway, you can use that to either do an event on intersection (make one explode, or whatever) or prevent the movement from being drawn. (revert to previous co-ordinates)

edit: here we go

boolean

intersects(Rectangle r) Determines whether or not this Rectangle and the specified Rectangle intersect.

So I would do (and don't paste this code, it most likely won't work, not done java for a long time and I didn't do graphics when I did use it.)

Rectangle rect1 = new Rectangle(player.x, player.y, player.width, player.height);

Rectangle rect2 = new Rectangle(enemy.x, enemy.y, enemy.width, enemy.height);

//detects when the two rectangles hit
if(rect1.intersects(rect2))
{

System.out.println("game over, g");
}

obviously you'd need to fit that in somewhere.

How to set the height of an input (text) field in CSS?

Try with padding and line-height -

input[type="text"]{ padding: 20px 10px; line-height: 28px; }

How can I remove item from querystring in asp.net using c#?

I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection, which the QueryString property actually is, unfortunately it is internal in the .NET framework. You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.

HttpValueCollection extends NameValueCollection, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString() method to later rebuild the query string from the underlying collection.

Text-align class for inside a table

The .text-align class is totally valid and more usable than having a .price-label and .price-value which are of no use any more.

I recommend going 100% with a custom utility class called

.text-right {
  text-align: right;
}

I like to do some magic, but that is up to you, like something:

span.pull-right {
  float: none;
  text-align: right;
}

Arduino IDE can't find ESP8266WiFi.h file

Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):

  • Start Arduino, go to File > Preferences
  • Add the following link to the Additional Boards Manager URLs: http://arduino.esp8266.com/stable/package_esp8266com_index.json and press OK button
  • Click Tools > Boards menu > Boards Manager, search for ESP8266 and install ESP8266 platform from ESP8266 community (and don't forget to select your ESP8266 boards from Tools > Boards menu after installation)

To install additional ESP8266WiFi library:

  • Click Sketch > Include Library > Manage Libraries, search for ESP8266WiFi and then install with the latest version.

After above steps, you should compile the sketch normally.

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

Find and replace with a newline in Visual Studio Code

A possible workaround would be to use the multi-cursor. select the >< part of your example use Ctrl+Shift+L or select all occurrences. Then use the arrow keys to move all the cursors between the tags and press enter to insert a newline everywhere.

This won't work in all situations.

You can also use Ctrl+D for select next match, which adds the next match to the selection and adds a cursor. And use Ctrl+K Ctrl+D to skip a selection.

How can I check Drupal log files?

Make sure drush is installed (you may also need to make sure the dblog module is enabled) and use:

drush watchdog-show --tail

Available in drush v8 and below.

This will give you a live look at the logs from your console.

I have never set any passwords to my keystore and alias, so how are they created?

All these answers and there is STILL just one missing. When you create your auth credential in the Google API section of the dev console, make sure (especially if it is your first one) that you have clicked on the 'consent screen' option. If you don't have the 'title' and any other required field filled out the call will fail with this option.

How can I get the value of a registry key from within a batch script?

For some reason Patrick Cuff's code doesn't work on my system (Windows 7) probably due to tryingToBeClever's comment. Modifying it a little did the trick:

@echo OFF

setlocal ENABLEEXTENSIONS
set KEY_NAME=HKEY_CURRENT_USER\Software\Microsoft\Command Processor
set VALUE_NAME=DefaultColor

FOR /F "tokens=1-3" %%A IN ('REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul') DO (
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C
)

if defined ValueName (
    @echo Value Name = %ValueName%
    @echo Value Type = %ValueType%
    @echo Value Value = %ValueValue%
) else (
    @echo %KEY_NAME%\%VALUE_NAME% not found.
)

How to create an Excel File with Nodejs?

I just figured a simple way out . This works -

Just create a file with Tabs as delimiters ( similar to CSV but replace comma with Tab ). Save it with extension .XLS . The file can be opened in Excel .

Some code to help --

var fs = require('fs');
var writeStream = fs.createWriteStream("file.xls");

var header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n";
var row1 = "0"+"\t"+" 21"+"\t"+"Rob"+"\n";
var row2 = "1"+"\t"+" 22"+"\t"+"bob"+"\n";

writeStream.write(header);
writeStream.write(row1);
writeStream.write(row2);

writeStream.close();

This creates the file in XLS file format . It doesnt work if you try XLSX instead of XLS .

Bootstrap: adding gaps between divs

I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>

Oracle SQL Query for listing all Schemas in a DB

Either of the following SQL will return all schema in Oracle DB.

  1. select owner FROM all_tables group by owner;
  2. select distinct owner FROM all_tables;

How to wrap text in LaTeX tables?

Another option is to insert a minipage in each cell where text wrapping is desired, e.g.:

\begin{table}[H]
\begin{tabular}{l}
\begin{minipage}[t]{0.8\columnwidth}%
a very long line a very long line a very long line a very long line
a very long line a very long line a very long line a very long line
a very long line a very long line a very long line %
\end{minipage}\tabularnewline
\end{tabular}
\end{table}

Visual Studio 2010 shortcut to find classes and methods?

Visual Studio 2010 has the "Navigate To" command, which might be what you are looking for. The default keyboard shortcut is CTRL + ,. Here is an overview of some of the options for navigating in Visual Studio 2010.

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

How can I make content appear beneath a fixed DIV element?

I liked grdevphl's Javascript answer best, but in my own use case, I found that using height() in the calculation still left a little overlap since it didn't take padding into account. If you run into the same issue, try outerHeight() instead to compensate for padding and border.

$(document).ready(function() {
    var contentPlacement = $('#header').position().top + $('#header').outerHeight();
    $('#content').css('margin-top',contentPlacement);
});

How to align 3 divs (left/center/right) inside another div?

The easiest solution is to crate a table with 3 columns and center that table.

html:

 <div id="cont">
        <table class="aa">
            <tr>
                <td>
                    <div id="left">
                        <h3 class="hh">Content1</h3>
                        </div>
                    </td>
                <td>
                    <div id="center">
                        <h3 class="hh">Content2</h3>
                        </div>
                 </td>
                <td>
                    <div id="right"><h3 class="hh">Content3</h3>
                        </div>
                </td>
            </tr>
        </table>
    </div>

css:

#cont 
{
  margin: 0px auto;    
  padding: 10px 10px;
}

#left
{    
  width: 200px;
  height: 160px;
  border: 5px solid #fff;
}

#center
{
  width: 200px;
  height: 160px;
  border: 5px solid #fff;
}

#right
{
  width: 200px;
  height: 160px;
  border: 5px solid #fff;
}

No visible cause for "Unexpected token ILLEGAL"

When running OS X, the filesystem creates hidden forks of basically all your files, if they are on a hard drive that doesn't support HFS+. This can sometimes (happened to me just now) lead to your JavaScript engine tries to run the data-fork instead of the code you intend it to run. When this happens, you will also receive

SyntaxError: Unexpected token ILLEGAL

because the data fork of your file will contain the Unicode U+200B character. Removing the data fork file will make your script run your actual, intended code, instead of a binary data fork of your code.

.whatever : These files are created on volumes that don't natively support full HFS file characteristics (e.g. ufs volumes, Windows fileshares, etc). When a Mac file is copied to such a volume, its data fork is stored under the file's regular name, and the additional HFS information (resource fork, type & creator codes, etc) is stored in a second file (in AppleDouble format), with a name that starts with ".". (These files are, of course, invisible as far as OS-X is concerned, but not to other OS's; this can sometimes be annoying...)

How to suppress scientific notation when printing float values?

In addition to SG's answer, you can also use the Decimal module:

from decimal import Decimal
x = str(Decimal(1) / Decimal(10000))

# x is a string '0.0001'

How to select the rows with maximum values in each group with dplyr?

This more verbose solution provides greater control on what happens in case of duplicate maximum value (in this example, it will take one of the corresponding rows randomly)

library(dplyr)
df %>% group_by(A, B) %>%
  mutate(the_rank  = rank(-value, ties.method = "random")) %>%
  filter(the_rank == 1) %>% select(-the_rank)

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

Is it possible to have SSL certificate for IP address, not domain name?

The answer is yes. In short, it is a subject alternative name (SAN) certificate that contains IPs where you would typically see DNS entries. The certificate type is not limited to Public IPs - that restriction is only imposed by a signing authority rather than the technology. I just wanted to clarify that point. I suspect you really just want to get rid of that pesky insecure prompt on your internal websites and devices without the cost and hassle of giving them DNS names then paying for a CA to issue a cert every year or two. You should NOT be trying to convince the world that your IP address is a reputable website and folks should feel comfortable providing their payment information. Now that we have established why no reputable organization wants to issue this type of certificate, lets just do it ourselves with a self signed SAN certificate. Internally I have a trusted certificate that is deployed to all of our hosts, then I sign this type of certificate with it and all devices become trusted. Doing that here is beyond the scope of the question but I think it relevant to the discussion as the question and solution go hand in hand. To be concise, here is how to generate an individual self signed SAN certificate with IP addresses. Expand the IP list to include your entire subnet and use one cert for everything.

#!/bin/bash
#using: OpenSSL 1.1.1c FIPS  28 May 2019 / CentOS Linux release 8.2.2004

C=US ; ST=Confusion ; L=Anywhere ; O=Private\ Subnet ; [email protected]
BITS=2048
CN=RFC1918
DOM=company.com
SUBJ="/C=$C/ST=$ST/L=$L/O=$O/CN=$CN.$DOM"

openssl genrsa -out ip.key $BITS

SAN='\n[SAN]\nsubjectAltName=IP:192.168.1.0,IP:192.168.1.1,IP:192.168.1.2,IP:192.168.1.3,IP:192.168.1.4,IP:192.168.1.5,IP:192.168.1.6,IP:192.168.1.7,IP:192.168.1.8,IP:192.168.1.9,IP:192.168.1.10'

cp /etc/pki/tls/openssl.cnf /tmp/openssl.cnf
echo -e "$SAN" >> /tmp/openssl.cnf

openssl req -subj "$SUBJ" -new -x509 -days 10950 \
    -key ip.key -out ip.crt -batch \
    -set_serial 168933982 \
    -config /tmp/openssl.cnf \
    -extensions SAN

openssl x509 -in ip.crt -noout -text

.NET Excel Library that can read/write .xls files

Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:

private DataTable LoadExcelData(string fileName)
{
  string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

  OleDbConnection con = new OleDbConnection(Connection);

  OleDbCommand command = new OleDbCommand();

  DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);

  myCommand.Fill(dt);

  Console.WriteLine(dt.Rows.Count);

  return dt;
}

You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.

How can I temporarily disable a foreign key constraint in MySQL?

To turn off foreign key constraint globally, do the following:

SET GLOBAL FOREIGN_KEY_CHECKS=0;

and remember to set it back when you are done

SET GLOBAL FOREIGN_KEY_CHECKS=1;

WARNING: You should only do this when you are doing single user mode maintenance. As it might resulted in data inconsistency. For example, it will be very helpful when you are uploading large amount of data using a mysqldump output.

How to export a Vagrant virtual machine to transfer it

My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:

  • I'm vagrant w/ virtualbox on a Mac
  • I'm using git

This is what worked for me:

1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine. 
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines. 
5.) `git clone my_project`
6.) `vagrant up`

I had a few problems with VB Guest additions.

enter image description here

I fixed them with this solution.

What is Mocking?

Mocking is generating pseudo-objects that simulate real objects behaviour for tests

Finding current executable's path without /proc/self/exe

You can use argv[0] and analyze the PATH environment variable. Look at : A sample of a program that can find itself

How do I count unique visitors to my site?

Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.

In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.

Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!


Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Apache server keeps crashing, "caught SIGTERM, shutting down"

Try to upgrade and install new packages

sudo apt-get update && sudo apt-get upgrade -y

Visual Studio : short cut Key : Duplicate Line

VS 2017 its Ctrl + D or Ctrl + C ; Ctrl + V they both work for me.

Quick Sort Vs Merge Sort

quicksort is named so for a reason ,

highlights : both are stable sorts,(simply an implementation nuisance ) , so lets just move on to complexities

its very confusing with just the big-oh notations being spilled and "abused" , both have average case complexity of 0(nlogn) ,

but merge sort is always 0(nlogn) , whereas quicksort for bad partitions, ie skewed partitions like 1 element-10 element (which can happen due to sorted or reverse sorted list ) can lead to a 0(n^2)..

.. and so we have randomized quicksort , where we pick the pivot randomly and avoid such skewed partitioning , thereby nullifying the whole n^2 scenario anyway even for moderately skewed partitioning like 3-4 , we have a nlog(7/4)n, ideally we want 1-1 partion , thus the whole 2 of O(nlog(2)n).

so it is O(nlogn) , almost always and unlike merge sort the constants hidden under the "big-oh" notation are better for quicksort than for mergesort ..and it doesnt use up extra space like merge sort.

but getting quicksort run perfectly requires tweaking ,rephrase , quicksort provides you opportunities to tweak ....

How to find and restore a deleted file in a Git repository

If you only made changes and deleted a file, but not commit it, and now you broke up with your changes

git checkout -- .

but your deleted files did not return, you simply do the following command:

git checkout <file_path>

And presto, your file is back.

What data is stored in Ephemeral Storage of Amazon EC2 instance?

Basically, root volume (your entire virtual system disk) is ephemeral, but only if you choose to create AMI backed by Amazon EC2 instance store.

If you choose to create AMI backed by EBS then your root volume is backed by EBS and everything you have on your root volume will be saved between reboots.

If you are not sure what type of volume you have, look under EC2->Elastic Block Store->Volumes in your AWS console and if your AMI root volume is listed there then you are safe. Also, if you go to EC2->Instances and then look under column "Root device type" of your instance and if it says "ebs", then you don't have to worry about data on your root device.

More details here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/RootDeviceStorage.html

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

How to implement Android Pull-to-Refresh

Finally, Google released an official version of the pull-to-refresh library!

It is called SwipeRefreshLayout, inside the support library, and the documentation is here:

  1. Add SwipeRefreshLayout as a parent of view which will be treated as a pull to refresh the layout. (I took ListView as an example, it can be any View like LinearLayout, ScrollView etc.)

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/pullToRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </android.support.v4.widget.SwipeRefreshLayout>
    
  2. Add a listener to your class

    protected void onCreate(Bundle savedInstanceState) {
        final SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
        pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData(); // your code
                pullToRefresh.setRefreshing(false);
            }
        });
    }
    

You can also call pullToRefresh.setRefreshing(true/false); as per your requirement.

UPDATE

Android support libraries have been deprecated and have been replaced by AndroidX. The link to the new library can be found here.

Also, you need to add the following dependency to your project:

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'

OR

You can go to Refactor>>Migrate to AndroidX and Android Studio will handle the dependencies for you.

How to make <input type="file"/> accept only these types?

The value of the accept attribute is, as per HTML5 LC, a comma-separated list of items, each of which is a specific media type like image/gif, or a notation like image/* that refers to all image types, or a filename extension like .gif. IE 10+ and Chrome support all of these, whereas Firefox does not support the extensions. Thus, the safest way is to use media types and notations like image/*, in this case

<input type="file" name="foo" accept=
"application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*">

if I understand the intents correctly. Beware that browsers might not recognize the media type names exactly as specified in the authoritative registry, so some testing is needed.

How to clear Route Caching on server: Laravel 5.2.37

For your case solution is :

php artisan cache:clear
php artisan route:cache

Optimizing Route Loading is a must on production :

If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:

php artisan route:cache

This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.

Laravel 5 clear cache from route, view, config and all cache data from application

I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.

Reoptimized class loader:

php artisan optimize

Clear Cache facade value:

php artisan cache:clear

Clear Route cache:

php artisan route:cache

Clear View cache:

php artisan view:clear

Clear Config cache:

php artisan config:cache

How to fast-forward a branch to head?

Doing:

git checkout master
git pull origin

will fetch and merge the origin/master branch (you may just say git pull as origin is the default).

Delete commits from a branch in Git

Forcefully Change History

Assuming you don't just want to delete the last commit, but you want to delete specific commits of the last n commits, go with:

git rebase -i HEAD~<number of commits to go back>, so git rebase -i HEAD~5 if you want to see the last five commits.

Then in the text editor change the word pick to drop next to every commit you would like to remove. Save and quit the editor. Voila!

Additively Change History

Try git revert <commit hash>. Revert will create a new commit that undoes the specified commit.

How can I pad an integer with zeros on the left?

You can use Google Guava:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

Note:

Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

Ref: GuavaExplained

Server.Transfer Vs. Response.Redirect

There are many differences as specified above. Apart from above all, there is one more difference. Response.Redirect() can be used to redirect user to any page which is not part of the application but Server.Transfer() can only be used to redirect user within the application.

//This will work.
Response.Redirect("http://www.google.com");

//This will not work.
Server.Transfer("http://www.google.com");

Read/Write 'Extended' file properties (C#)

Jerker's answer is little simpler. Here's sample code which works from MS:

var folder = new Shell().NameSpace(folderPath);
foreach (FolderItem2 item in folder.Items())
{
    var company = item.ExtendedProperty("Company");
    var author = item.ExtendedProperty("Author");
    // Etc.
}

For those who can't reference shell32 statically, you can invoke it dynamically like this:

var shellAppType = Type.GetTypeFromProgID("Shell.Application");
dynamic shellApp = Activator.CreateInstance(shellAppType);
var folder = shellApp.NameSpace(folderPath);
foreach (var item in folder.Items())
{
    var company = item.ExtendedProperty("Company");
    var author = item.ExtendedProperty("Author");
    // Etc.
}

Python Timezone conversion

I have found that the best approach is to convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects).

Then you can use astimezone to convert to the timezone of interest (reference).

from datetime import datetime
import pytz

utcmoment_naive = datetime.utcnow()
utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc)

# print "utcmoment_naive: {0}".format(utcmoment_naive) # python 2
print("utcmoment_naive: {0}".format(utcmoment_naive))
print("utcmoment:       {0}".format(utcmoment))

localFormat = "%Y-%m-%d %H:%M:%S"

timezones = ['America/Los_Angeles', 'Europe/Madrid', 'America/Puerto_Rico']

for tz in timezones:
    localDatetime = utcmoment.astimezone(pytz.timezone(tz))
    print(localDatetime.strftime(localFormat))

# utcmoment_naive: 2017-05-11 17:43:30.802644
# utcmoment:       2017-05-11 17:43:30.802644+00:00
# 2017-05-11 10:43:30
# 2017-05-11 19:43:30
# 2017-05-11 13:43:30

So, with the moment of interest in the local timezone (a time that exists), you convert it to utc like this (reference).

localmoment_naive = datetime.strptime('2013-09-06 14:05:10', localFormat)

localtimezone = pytz.timezone('Australia/Adelaide')

try:
    localmoment = localtimezone.localize(localmoment_naive, is_dst=None)
    print("Time exists")

    utcmoment = localmoment.astimezone(pytz.utc)

except pytz.exceptions.NonExistentTimeError as e:
    print("NonExistentTimeError")

How do I compare two strings in python?

If you want to know if both the strings are equal, you can simply do

print string1 == string2

But if you want to know if they both have the same set of characters and they occur same number of times, you can use collections.Counter, like this

>>> string1, string2 = "abc def ghi", "def ghi abc"
>>> from collections import Counter
>>> Counter(string1) == Counter(string2)
True

When is it appropriate to use UDP instead of TCP?

UDP does have less overhead and is good for doing things like streaming real time data like audio or video, or in any case where it is ok if data is lost.

Passing two command parameters using a WPF binding

About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
        return tuple;
    }      
} 

Then execution logic in Command could be like this

public void OnExecute(object parameter) 
{
    var param = (Tuple<object, object>) parameter;

    // e.g. for two TextBox object
    var txtZip = (System.Windows.Controls.TextBox)param.Item1;
    var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}

and multi-bind with converter to create the parameters (with two TextBox objects)

<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource YourConvert}">
            <Binding ElementName="txtZip"/>
            <Binding ElementName="txtCity"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

JavaScript Regular Expression Email Validation

I've been using this function for a while. it returns a boolean value.

// Validates email address of course.
function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search (filter) != -1;
}

How can I change the Bootstrap default font family using font from Google?

If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.

Set transparent background using ImageMagick and commandline prompt

I am using ImageMagick 6.6.9-7 on Ubuntu 12.04.
What worked for me was the following:

convert test.png -transparent white transparent.png

That changed all the white in the test.png to transparent.

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

How to create a RelativeLayout programmatically with two buttons one on top of the other?

public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {

    final int TOP_ID = 3;
    final int BOTTOM_ID = 4;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // create two layouts to hold buttons
        RelativeLayout top = new RelativeLayout(this);
        top.setId(TOP_ID);
        RelativeLayout bottom = new RelativeLayout(this);
        bottom.setId(BOTTOM_ID);

        // create buttons in a loop
        for (int i = 0; i < 2; i++) {
            Button button = new Button(this);
            button.setText("Button " + i);
            // R.id won't be generated for us, so we need to create one
            button.setId(i);

            // add our event handler (less memory than an anonymous inner class)
            button.setOnClickListener(this);

            // add generated button to view
            if (i == 0) {
                top.addView(button);
            }
            else {
                bottom.addView(button);
            }
        }

        RelativeLayout root = (RelativeLayout) findViewById(R.id.root_layout);

        // add generated layouts to root layout view
       // LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);

        root.addView(top);
        root.addView(bottom);
    }

    @Override
    public void onClick(View v) {
        // show a message with the button's ID
        Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
        toast.show();

        // get the parent layout and remove the clicked button
        RelativeLayout parentLayout = (RelativeLayout)v.getParent();
        parentLayout.removeView(v);



    }
}

tr:hover not working

I had the same problem. I found that if I use a DOCTYPE like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

it didn't work. But if I use:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">

it did work.

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

Using PI in python 2.7

Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793

Check out the Python tutorial on modules and how to use them.

As for the second part of your question, Python comes with batteries included, of course:

>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793

Adobe Reader Command Line Reference

Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n

string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe"; 
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();

Editing an item in a list<T>

class1 item = lst[index];
item.foo = bar;

Codeigniter - multiple database connections

If you need to connect to more than one database simultaneously you can do so as follows:

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to (or you can pass the connection values as indicated above).

By setting the second parameter to TRUE (boolean) the function will return the database object.

Visit https://www.codeigniter.com/userguide3/database/connecting.html for further information.

jQuery UI accordion that keeps multiple sections open?

I found a tricky solution. Lets call the same function twice but with different id.

JQuery Code

$(function() {
    $( "#accordion1" ).accordion({
        collapsible: true, active: false, heightStyle: "content"
    });
    $( "#accordion2" ).accordion({
        collapsible: true, active: false, heightStyle: "content"
    });
});

HTML Code

<div id="accordion1">
    <h3>Section 1</h3>
    <div>Section one Text</div>
</div>
<div id="accordion2">   
    <h3>Section 2</h3>
    <div>Section two Text</div>
</div>

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

UPDATE 20200825:

Added below "Conclusion" paragraph

I've went down the pipenv rabbit hole (it's a deep and dark hole indeed...) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I've found.

DISCLAIMER:

This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It's about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.

venv

As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: "Changed in version 3.5: The use of venv is now recommended for creating virtual environments".

pipenv

pipenv- like venv - can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt, pipenv delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile is to supplant requirements.txt.

HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.

Conflicting Standards:

So if settling on a virtual envelope solution wasn't difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.

Conflict Resolution:

The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:

prefer built-in venv: if the target python has venv we'll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)

Conclusion:

So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv- which uses virtualenv - varies materially from venv.

Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.

Update 20200825:

An oft repeated criticism of Pipenv I saw when producing this analysis was that it was not actively maintained. Indeed, what's the point of using a solution whose future could be seen questionable due to lack of continuous development? After a dry spell of about 18 months, Pipenv is once again being actively developed. Indeed, large and material updates have since been released.

Why Anaconda does not recognize conda command?

For Windows

Go to Control Panel\System and Security\System\Advanced System Settings then look for Environment Variables.

Your user variables should contain Path=Path\to\Anaconda3\Scripts.

You need to figure where your Anaconda3 folder is (i.e. the path to this folder) . Mine was in C:\Users.

For Linux

You need to add conda to PATH. To do so, type:

export PATH=/path/to/anaconda3/bin:$PATH.

Same thing, you need to figure the path to anaconda3 folder (Usually, the path is stored in $HOME)

If you don't want to do this everytime you start a session, you can also add conda to PATH in your .bashrc file:

echo 'export PATH=/path/to/anaconda3/bin:$PATH' >> ~/.bashrc

Get timezone from DateTime

You could use TimeZoneInfo class

The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:

  1. Retrieving a time zone that is already defined by the operating system.

  2. Enumerating the time zones that are available on a system.

  3. Converting times between different time zones.

  4. Creating a new time zone that is not already defined by the operating system.

    Serializing a time zone for later retrieval.

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

Parse an URL in JavaScript

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Worked for me. But the first var should be var url = window.location.href

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

Strangely, I didn't find anything about legends and labels in the Chart.js documentation. It seems like you can't do it with chart.js alone.

I used https://github.com/bebraw/Chart.js.legend which is extremely light, to generate the legends.

How can I check whether a option already exist in select by JQuery

Another way using jQuery:

var exists = false; 
$('#yourSelect  option').each(function(){
  if (this.value == yourValue) {
    exists = true;
  }
});

Difference between a virtual function and a pure virtual function

A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:

 Derived d;
 Base& rb = d;
 // if Base::f() is virtual and Derived overrides it, Derived::f() will be called
 rb.f();  

A pure virtual function is a virtual function whose declaration ends in =0:

class Base {
  // ...
  virtual void f() = 0;
  // ...

A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.

An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation. (What that's good for is debatable.)


Note that C++11 brought a new use for the delete and default keywords which looks similar to the syntax of pure virtual functions:

my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;

See this question and this one for more info on this use of delete and default.

Using Colormaps to set color of line in matplotlib

U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.

Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

example of 3:

Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.

How to generate classes from wsdl using Maven and wsimport?

Even though this is bit late response, may be helpful for someone. Look like you have used pluginManagement. If you use pluginManagement , it will not pick the plug-in execution.

It should be under

<build>
<plugins>           
        <plugin> 

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Using this did not work for me, but MyActivityName.this did. Hope this helps anyone who could not get this to work.

Comma separated results in SQL

If you're stuck with SQL Server <2017, you can use GroupConcat. The syntax and the performance is far better than the FOR XML PATH sollution.

Installation:

-- https://codeplexarchive.blob.core.windows.net/archive/projects/groupconcat/groupconcat.zip
create assembly [GroupConcat] from 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C01030058898C510000000000000000E00002210B010B00001E000000080000000000007E3D0000002000000040000000000010002000000002000004000000000000000400000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000243D000057000000004000003804000000000000000000000000000000000000006000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000841D000000200000001E000000020000000000000000000000000000200000602E7273726300000038040000004000000006000000200000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000002600000000000000000000000000004000004200000000000000000000000000000000603D0000000000004800000002000500C02C00006410000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003202731100000A7D010000042A0000001330040047000000010000110F01281200000A2D3D0F01281300000A0A027B01000004066F1400000A2C1A027B01000004250B06250C07086F1500000A17586F1600000A2A027B0100000406176F1700000A2A001B30050089000000020000110F017B010000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B01000004076F1400000A2C29027B01000004250D072513040911046F1500000A0F017B01000004076F1500000A586F1600000A2B19027B01000004070F017B01000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0000000110000002000D006D7A000E000000001B3003009B00000003000011027B010000043989000000027B010000046F1D00000A16317B731E00000A0A027B010000046F1800000A0D2B341203281900000A0B160C2B1E061201281A00000A6F1F00000A260672010000706F1F00000A260817580C081201282000000A32D81203281B00000A2DC3DE0E1203FE160300001B6F1C00000ADC06066F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A000110000002002B00416C000E00000000133003003900000004000011036F2500000A0A0206732600000A7D01000004160B2B1B027B01000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF2A0000001B3002005B0000000500001103027B010000046F1D00000A6F2800000A027B010000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0300000406282A00000A2C0702067D030000042A5E02731100000A7D02000004027E2B00000A7D030000042A133004004F000000010000110F01281200000A2D450F01281300000A0A027B02000004066F1400000A2C1B027B02000004250B06250C07086F1500000A17586F1600000A2B0D027B0200000406176F1700000A020428070000062A001B300500A300000002000011027B03000004282C00000A2C0D020F017B030000047D030000040F017B020000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B02000004076F1400000A2C29027B02000004250D072513040911046F1500000A0F017B02000004076F1500000A586F1600000A2B19027B02000004070F017B02000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0001100000020027006D94000E000000001B300300B300000003000011027B0200000439A1000000027B020000046F1D00000A163E90000000731E00000A0A027B020000046F1800000A0D2B351203281900000A0B160C2B1F061201281A00000A6F1F00000A2606027B030000046F1F00000A260817580C081201282000000A32D71203281B00000A2DC2DE0E1203FE160300001B6F1C00000ADC06066F2100000A027B030000046F2D00000A59027B030000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A000110000002002E004270000E00000000133003004500000004000011036F2500000A0A0206732600000A7D02000004160B2B1B027B02000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D030000042A0000001B300200670000000500001103027B020000046F1D00000A6F2800000A027B020000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B030000046F2900000A2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0500000406282A00000A2C0702067D050000042AEA027B060000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D060000042A7A02731100000A7D04000004027E2B00000A7D0500000402167D060000042A00001330040056000000010000110F01281200000A2D4C0F01281300000A0A027B04000004066F1400000A2C1B027B04000004250B06250C07086F1500000A17586F1600000A2B0D027B0400000406176F1700000A0204280E0000060205280F0000062A00001B300500B800000002000011027B05000004282C00000A2C0D020F017B050000047D05000004027B060000042D0D020F017B060000047D060000040F017B040000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B04000004076F1400000A2C29027B04000004250D072513040911046F1500000A0F017B04000004076F1500000A586F1600000A2B19027B04000004070F017B04000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0110000002003C006DA9000E000000001B300300D700000007000011027B0400000439C5000000027B040000046F1D00000A163EB4000000731E00000A0B027B06000004183313027B04000004731E000006733100000A0A2B0C027B04000004733200000A0A066F3300000A13042B351204283400000A0C160D2B1F071202281A00000A6F1F00000A2607027B050000046F1F00000A260917580D091202282000000A32D71204283500000A2DC2DE0E1204FE160600001B6F1C00000ADC07076F2100000A027B050000046F2D00000A59027B050000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A0001100000020052004294000E00000000133003005100000004000011036F2500000A0A0206732600000A7D04000004160B2B1B027B04000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D0500000402036F3600000A7D060000042A0000001B300200730000000500001103027B040000046F1D00000A6F2800000A027B040000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B050000046F2900000A03027B060000046F3700000A2A000110000002001D002F4C000E00000000EA027B080000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D080000042A4E02731100000A7D0700000402167D080000042A00133004004F000000010000110F01281200000A2D450F01281300000A0A027B07000004066F1400000A2C1B027B07000004250B06250C07086F1500000A17586F1600000A2B0D027B0700000406176F1700000A020428160000062A001B3005009E00000002000011027B080000042D0D020F017B080000047D080000040F017B070000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B07000004076F1400000A2C29027B07000004250D072513040911046F1500000A0F017B07000004076F1500000A586F1600000A2B19027B07000004070F017B07000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A000001100000020022006D8F000E000000001B300300C800000008000011027B0700000439B6000000027B070000046F1D00000A163EA5000000731E00000A0B027B08000004183313027B07000004731E000006733100000A0A2B0C027B07000004733200000A0A066F3300000A13052B3A1205283400000A0C1202281A00000A0D1613042B1A07096F1F00000A260772010000706F1F00000A2611041758130411041202282000000A32DB1205283500000A2DBDDE0E1205FE160600001B6F1C00000ADC07076F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A01100000020052004799000E00000000133003004500000004000011036F2500000A0A0206732600000A7D07000004160B2B1B027B07000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F3600000A7D080000042A0000001B300200670000000500001103027B070000046F1D00000A6F2800000A027B070000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B080000046F3700000A2A000110000002001D002F4C000E000000002204036F3800000A2A1E02283900000A2A00000042534A4201000100000000000C00000076322E302E35303732370000000005006C000000C4060000237E0000300700006405000023537472696E677300000000940C00006C00000023555300000D0000100000002347554944000000100D00005403000023426C6F6200000000000000020000015717A2090900000000FA253300160000010000002500000006000000080000001E0000001E0000000500000039000000180000000800000003000000040000000400000006000000010000000300000000000A00010000000000060081007A000A00B20097000600C3007A000600E500CA000600F100CA000A001F010A0106004E0144010600600144010A009C010A010A00CA01970006001702050206002E02050206004B02050206006A02050206008302050206009C0205020600B70205020600D202050206000A03EB0206001E030502060057033703060077033703060095037A000A00AB0397000A00CC0397000600D303EB020600E903EB0217002B04000006004404CA00060070047A0006009A048E040600EB047A00060014057A0006001E057A000E002D05CA0006004005CA008F002B0400000000000001000000000001000100092110001A00270005000100010009211000330027000500020007000921100042002700050004000E00092110005200270005000700160001001000610027000D0009001D000100FE0010000100FE0010000100730139000100FE001000010073013900010095014F000100FE001000010095014F005020000000008600050118000100602000000000860029011C000100B4200000000086003401220002005C210000000086003A0128000300142200000000E6015B012D0004005C2200000000E6016D0133000500D4220000000081087D011C00060004230000000086000501180007001C2300000000860029013C000700782300000000860034014400090038240000000086003A0128000A00082500000000E6015B012D000B005C2500000000E6016D0133000C00E0250000000081087D011C000D001026000000008108A40152000E004B26000000008600050118000F006C26000000008600290158000F00D026000000008600340162001200A4270000000086003A0128001300982800000000E6015B012D001400F82800000000E6016D01330015008829000000008108A40152001600C329000000008600050118001700D82900000000860029016D001700342A000000008600340175001900F02A0000000086003A0128001A00D42B00000000E6015B012D001B00282C00000000E6016D0133001C00AC2C00000000E601B6017B001D00B52C000000008618BE0118001F0000000100C40100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200EC0100000100DC0100000000000000000100E20100000100E40100000100E60100000100E60100000100C40100000200EC0100000300F60100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200F60100000100DC0100000000000000000100E20100000100E40100000100010200000200030202000900030009000400090005000900060006005100BE0118005900BE01BA006100BE01BA006900BE01BA007100BE01BA007900BE01BA008100BE01BA008900BE01BA009100BE01BA009900BE01BF00A100BE01BA00A900BE01C400B100BE011800B900BE011800C100BE01C900D100BE0142011400BE0118003100F4034F013100FF035301140009045701140015045D0114001E0464011400270464011400360477011C005304890124005F049B011C0067044F01F1007C04180014008404B701F900BE011800F900A804BB012400FF03C101F900AF04B701F900BA04C6011900C10453013100CA04CD013900D604B7011400BE01C4003900E004530141006D01C40041006D01BA000101F204F9010101000539000101060503020101AF04B7014900FF0308020901BE01BA00110126050C022C00BE0119022C00BE012C022C0036043902340053048901340067044F0139004E05080241006D0167020101570587021900BE01180024000B0081002E006B0035032E002B000E032E0013008C022E001B009D022E0023000E032E003B0014032E0033008C022E0043000E032E0053000E032E0063002C0343007B00CF0063007B00CF0064000B00940083007B00CF00A3007B00CF00E4000B00810004010B00A70044010B009400E4010B00810004020B00A70064020B009400E4020B00810044030B0094006C01A001D301E501EA01FF014D026C0203000100040002000500040000008B014A0000008B014A000000AF0168000000AF01680001000700030001000E00050001000F0007000100160009000A004801820194011102450204800000010000000D13F49F00000000000027000000020000000000000000000000010071000000000002000000000000000000000001008B000000000002000000000000000000000001007A000000000000000000003C4D6F64756C653E0047726F7570436F6E6361742E646C6C0047524F55505F434F4E4341540047726F7570436F6E6361740047524F55505F434F4E4341545F440047524F55505F434F4E4341545F44530047524F55505F434F4E4341545F530052657665727365436F6D7061726572006D73636F726C69620053797374656D0056616C7565547970650053797374656D2E44617461004D6963726F736F66742E53716C5365727665722E536572766572004942696E61727953657269616C697A65004F626A6563740053797374656D2E436F6C6C656374696F6E732E47656E657269630049436F6D706172657260310044696374696F6E61727960320076616C75657300496E69740053797374656D2E446174612E53716C54797065730053716C537472696E6700416363756D756C617465004D65726765005465726D696E6174650053797374656D2E494F0042696E61727952656164657200526561640042696E6172795772697465720057726974650064656C696D69746572007365745F44656C696D697465720044656C696D6974657200736F727442790053716C42797465007365745F536F7274427900536F7274427900436F6D70617265002E63746F720056414C55450053716C46616365744174747269627574650047726F7570007200770076616C75650044454C494D4954455200534F52545F4F52444552007800790053797374656D2E5265666C656374696F6E00417373656D626C795469746C6541747472696275746500417373656D626C794465736372697074696F6E41747472696275746500417373656D626C79436F6E66696775726174696F6E41747472696275746500417373656D626C79436F6D70616E7941747472696275746500417373656D626C7950726F6475637441747472696275746500417373656D626C79436F7079726967687441747472696275746500417373656D626C7954726164656D61726B41747472696275746500417373656D626C7943756C747572654174747269627574650053797374656D2E52756E74696D652E496E7465726F70536572766963657300436F6D56697369626C6541747472696275746500417373656D626C7956657273696F6E4174747269627574650053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650053657269616C697A61626C654174747269627574650053716C55736572446566696E656441676772656761746541747472696275746500466F726D6174005374727563744C61796F7574417474726962757465004C61796F75744B696E64006765745F49734E756C6C006765745F56616C756500436F6E7461696E734B6579006765745F4974656D007365745F4974656D0041646400456E756D657261746F7200476574456E756D657261746F72004B657956616C7565506169726032006765745F43757272656E74006765745F4B6579004D6F76654E6578740049446973706F7361626C6500446973706F7365006765745F436F756E740053797374656D2E5465787400537472696E674275696C64657200417070656E64006765745F4C656E6774680052656D6F766500546F537472696E67006F705F496D706C696369740052656164496E7433320052656164537472696E6700537472696E67006F705F496E657175616C69747900456D7074790049734E756C6C4F72456D70747900457863657074696F6E00436F6E7665727400546F4279746500536F7274656444696374696F6E6172796032004944696374696F6E617279603200526561644279746500436F6D70617265546F0000000000032C00006549006E00760061006C0069006400200053006F0072007400420079002000760061006C00750065003A00200075007300650020003100200066006F007200200041005300430020006F00720020003200200066006F007200200044004500530043002E0000008002D97266C26949A672EA780F71C8980008B77A5C561934E08905151211010E0706151215020E0803200001052001011119052001011108042000111905200101121D05200101122102060E072002011119111905200101110C04280011190206050520010111250920030111191119112505200101111004280011250720020111191125052001011114052002080E0E12010001005408074D617853697A65A00F000012010001005408074D617853697A65FFFFFFFF12010001005408074D617853697A6504000000042001010E0420010102042001010805200101116572010002000000050054080B4D61784279746553697A65FFFFFFFF5402124973496E76617269616E74546F4E756C6C73015402174973496E76617269616E74546F4475706C696361746573005402124973496E76617269616E74546F4F726465720154020D49734E756C6C4966456D7074790105200101116D06151215020E08032000020320000E0520010213000620011301130007200201130013010A07030E151215020E080E0A2000151171021300130106151171020E080A2000151175021300130106151175020E080420001300160705151175020E080E151171020E08151215020E080E03200008052001127D0E0420001301062002127D080805000111190E110704127D151175020E0808151171020E0804070208080E0702151175020E08151171020E08050002020E0E0307010E040001020E032000050400010505071512808D020E08122002011512809102130013011512110113000C2001011512809102130013010B20001511809502130013010715118095020E081907051512808D020E08127D151175020E080815118095020E0804200101051A07061512808D020E08127D151175020E080E0815118095020E08042001080E1001000B47726F7570436F6E63617400007001006B537472696E6720636F6E636174656E6174696F6E2061676772656761746520666F722053514C205365727665722E2044726F702D696E207265706C6163656D656E7420666F72206275696C742D696E204D7953514C2047524F55505F434F4E4341542066756E74696F6E2E000005010000000017010012436F7079726967687420C2A920203230313100000801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773014C3D000000000000000000006E3D0000002000000000000000000000000000000000000000000000603D00000000000000000000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000E00300000000000000000000E00334000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE0000010000000100F49F0D1300000100F49F0D133F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B00440030000010053007400720069006E006700460069006C00650049006E0066006F0000001C0300000100300030003000300030003400620030000000F0006C00010043006F006D006D0065006E0074007300000053007400720069006E006700200063006F006E0063006100740065006E006100740069006F006E002000610067006700720065006700610074006500200066006F0072002000530051004C0020005300650072007600650072002E002000440072006F0070002D0069006E0020007200650070006C006100630065006D0065006E007400200066006F00720020006200750069006C0074002D0069006E0020004D007900530051004C002000470052004F00550050005F0043004F004E004300410054002000660075006E00740069006F006E002E00000040000C000100460069006C0065004400650073006300720069007000740069006F006E0000000000470072006F007500700043006F006E00630061007400000040000F000100460069006C006500560065007200730069006F006E000000000031002E0030002E0034003800370037002E00340030003900340038000000000040001000010049006E007400650072006E0061006C004E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C0000004800120001004C006500670061006C0043006F007000790072006900670068007400000043006F0070007900720069006700680074002000A90020002000320030003100310000004800100001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C00000038000C000100500072006F0064007500630074004E0061006D00650000000000470072006F007500700043006F006E00630061007400000044000F000100500072006F006400750063007400560065007200730069006F006E00000031002E0030002E0034003800370037002E00340030003900340038000000000048000F00010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0030002E0034003800370037002E003400300039003400380000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C000000803D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 with permission_set = safe;
create aggregate [dbo].[GROUP_CONCAT]    (@VALUE [nvarchar](4000))                                                      returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT];
create aggregate [dbo].[GROUP_CONCAT_D]  (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4))                            returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_D];
create aggregate [dbo].[GROUP_CONCAT_DS] (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4), @SORT_ORDER [tinyint])     returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_DS];
create aggregate [dbo].[GROUP_CONCAT_S]  (@VALUE [nvarchar](4000), @SORT_ORDER [tinyint])                               returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_S];

go

Usage:

declare @liststr varchar(max)
select @liststr = dbo.group_concat_d(institutionname, ',')
from education
where studentnumber = '111'
group by studentnumber;
select @liststr

GroupConcat does not support ordering, though. You could use PIVOT, CTE's and windows functions if you need ordering:

drop table if exists #students;
create table #students (
    name        varchar(20),
    institution varchar(20),
    year        int -- order by year
)
go

insert into #students(name, institution, year)
values
    ('Simon', 'INSTITUTION1', 2005),
    ('Simon', 'INSTITUTION2', 2008);

with cte as (
    select name,
           institution,
           rn = row_number() over (partition by name order by year)
    from #students
)
select name,
       [1] +
       isnull((',' + [2]), '') +
       isnull((',' + [3]), '') +
       isnull((',' + [4]), '') +
       isnull((',' + [5]), '') +
       isnull((',' + [6]), '') +
       isnull((',' + [7]), '') +
       isnull((',' + [8]), '') +
       isnull((',' + [9]), '') +
       isnull((',' + [10]), '') +
       isnull((',' + [11]), '') +
       isnull((',' + [12]), '') +
       isnull((',' + [13]), '') +
       isnull((',' + [14]), '') +
       isnull((',' + [15]), '') +
       isnull((',' + [16]), '') +
       isnull((',' + [17]), '') +
       isnull((',' + [18]), '') +
       isnull((',' + [19]), '') +
       isnull((',' + [20]), '')
from cte
    pivot (
    max(institution)
    for rn in ([1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20])
    ) as piv

how does multiplication differ for NumPy Matrix vs Array classes?

Reference from http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html

..., the use of the numpy.matrix class is discouraged, since it adds nothing that cannot be accomplished with 2D numpy.ndarray objects, and may lead to a confusion of which class is being used. For example,

>>> import numpy as np
>>> from scipy import linalg
>>> A = np.array([[1,2],[3,4]])
>>> A
    array([[1, 2],
           [3, 4]])
>>> linalg.inv(A)
array([[-2. ,  1. ],
      [ 1.5, -0.5]])
>>> b = np.array([[5,6]]) #2D array
>>> b
array([[5, 6]])
>>> b.T
array([[5],
      [6]])
>>> A*b #not matrix multiplication!
array([[ 5, 12],
      [15, 24]])
>>> A.dot(b.T) #matrix multiplication
array([[17],
      [39]])
>>> b = np.array([5,6]) #1D array
>>> b
array([5, 6])
>>> b.T  #not matrix transpose!
array([5, 6])
>>> A.dot(b)  #does not matter for multiplication
array([17, 39])

scipy.linalg operations can be applied equally to numpy.matrix or to 2D numpy.ndarray objects.

CSS force new line

Use <br /> OR <br> -

<li>Post by<br /><a>Author</a></li>

OR

<li>Post by<br><a>Author</a></li>

or

make the a element display:block;

<li>Post by <a style="display:block;">Author</a></li>

Try

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

The serial communication manager library has many API and features targeted for the task you want. If the device is a USB-UART its VID/PID can be used. If the device is BT-SPP than platform specific APIs can be used. Take a look at this project for serial port programming: https://github.com/RishiGupta12/serial-communication-manager

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

Add the css

  <style type="text/css">
    textarea
    {

        border:1px solid #999999
        width:99%;
        margin:5px 0;
        padding:1%;
    }
</style>

Get a worksheet name using Excel VBA

Sub FnGetSheetsName()

    Dim mainworkBook As Workbook

    Set mainworkBook = ActiveWorkbook

    For i = 1 To mainworkBook.Sheets.Count

    'Either we can put all names in an array , here we are printing all the names in Sheet 2

    mainworkBook.Sheets("Sheet2").Range("A" & i) = mainworkBook.Sheets(i).Name

    Next i

End Sub

TSQL select into Temp table from dynamic sql

A working example.

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YourTableName'

EXECUTE ('SELECT * INTO #TEMP  FROM ' + @TableName +'; SELECT * FROM #TEMP;')

Second solution with accessible temp table

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YOUR_TABLE_NAME'

EXECUTE ('CREATE VIEW vTemp AS
        SELECT *
        FROM ' + @TableName)
SELECT * INTO #TEMP  FROM vTemp 

--DROP THE VIEW HERE      
DROP VIEW vTemp

/*START USING TEMP TABLE
************************/
--EX:
SELECT * FROM #TEMP


--DROP YOUR TEMP TABLE HERE
DROP TABLE #TEMP

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

(Xcode 5) Well, after spending an hour I solved my issue. Even if you re-generate the provisioning file in Xcode 5, you should manually update your account. I only changed provisioning file in the Organizer tab that did not work, Xcode kept build with old provisioning file.

So go to

Xcode > Preferences > Accounts > View Details (Select your account)

Then refresh your provisioning files.

Using Bootstrap Tooltip with AngularJS

Try the Tooltip (ui.bootstrap.tooltip). See Angular directives for Bootstrap

<button type="button" class="btn btn-default" tooltip-placement="bottom" uib-tooltip="tooltip message">Test</button>

It is recommended to avoid JavaScript code on the top of AngularJS

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

TL;DR

In several occasions, I've solved this kind of errors by just closing my terminal session and opening a new one before retrying the failing command.

Long explanation

In some SOs (such as MacOS) there is already a pre-installed, system-wide version of ruby. If you are using a version manager, such as rbenv or asdf, they work by playing with the environment of your current session so that the relevant commands point to the binaries installed by the version manager.

When installing a new binary, the version manager installs it in a special location, usually somewhere under the user's home directory. It then configures everything in your PATH so that you get the freshly installed binaries when you issue a command, instead of the ones that came with your system. However, if you don't restart the session (there are other ways of getting your environment updated, but that's the easiest one) you don't get the new configuration and you will be using the original installation.

How exactly does <script defer="defer"> work?

As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.

How to export a MySQL database to JSON?

THis is somthing that should be done in the application layer.

For example, in php it is a s simple as

Edit Added the db connection stuff. No external anything needed.

$sql = "select ...";
$db = new PDO ( "mysql:$dbname", $user, $password) ;
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

file_put_contents("output.txt", json_encode($result));

Concatenating bits in VHDL

You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:

process(b0,b1,b2,b3)
   variable bcat : std_logic_vector(0 to 3);
begin
   bcat := b0 & b1 & b2 & b3;
   case bcat is
      when "0000" => x <= 1;
      when others => x <= 2;
   end case;
end process;

MVC 4 - Return error message from Controller - Show in View

The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:

[HttpPost]
public ActionResult form_edit(FormModels model)
{          
   if(ModelState.IsValid())
   {
      --- operations 
      return Redirect("OtherAction", "SomeController");
   }

   // here you can use a little trick
   //fill the model property that holds the information for the dropdown with the data 

   // you haven't provided the get method but it should look something like this
   model.Countries = ... some data goes here;
   model.dd_value = ... some other data;
   model.dd_text = ... other data;

   ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
   return View(model);
}

and then in the view just use :

@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController


@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{

    <table>
    <tr>
    <td>       
    @Html.ValidationSummary(true)             
    </td>
    </tr>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")

    </th>
</tr>
</table>

<table>
<tr>
    <td>
        <input  type="submit" value="Submit" />
    </td>
</tr>
</table>
}

This should work okay.

If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.

other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:

[HttpPost]
public ActionResult form_edit(FormModels model)
{          
   TempData["error"] = "someErrorMessage";
   return RedirectToAction("form_Post", "Form");
}

[HttpGet]
public ActionResult form_edit()
{
    do stuff here ----
    ViewData["error"] = TempData["error"];
    return View();
}

@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController


@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{

    <table>
    <tr>
    <td>       
    <div>@ViewData["error"]</div>             
    </td>
    </tr>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")

    </th>
</tr>
</table>

<table>
<tr>
    <td>
        <input  type="submit" value="Submit" />
    </td>
</tr>
</table>
}

Why is Event.target not Element in Typescript?

JLRishe's answer is correct, so I simply use this in my event handler:

if (event.target instanceof Element) { /*...*/ }

How to remove &quot; from my Json in javascript?

Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from

result.replace(/&quot;/g,'"')

to

result.replace(/&#34;/g,'"')

Instead of this I use that:

result.replace(/(&quot\;)/g,"\"")

By this notation it works.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

Just delete the old build from the device and reinstall the same. Because device.keystore is already exist in the device so just uninstall the build and reinstall the APK thats all..

Thanks

Split pandas dataframe in two if it has more than 10 rows

def split_and_save_df(df, name, size, output_dir):
    """
    Split a df and save each chunk in a different csv file.

    Parameters:
        df : pandas df to be splitted
        name : name to give to the output file
        size : chunk size
        output_dir : directory where to write the divided df
    """
    import os
    for i in range(0, df.shape[0],size):
        start  = i
        end    = min(i+size-1, df.shape[0]) 
        subset = df.loc[start:end] 
        output_path = os.path.join(output_dir,f"{name}_{start}_{end}.csv")
        print(f"Going to write into {output_path}")
        subset.to_csv(output_path)
        output_size = os.stat(output_path).st_size
        print(f"Wrote {output_size} bytes")

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

How to make Google Fonts work in IE?

After my investigation, I came up to this solution:

//writing the below line into the top of my style.css file
@import url('https://fonts.googleapis.com/css?family=Assistant:200,300,400,600,700,800&subset=hebrew');

MUST OBSERVE: We must need to write the font-weight correctly of this font. For example: font-weight:900; will not work as we have not included 900 like 200,300,400,600,700,800 into the URL address while importing from Google with the above link. We can add or include 900 to the above URL, but that will work only if the above Google Font has this option while embedding.

How to prevent multiple definitions in C?

You shouldn't include other source files (*.c) in .c files. I think you want to have a header (.h) file with the DECLARATION of test function, and have it's DEFINITION in a separate .c file.

The error is caused by multiple definitions of the test function (one in test.c and other in main.c)

Implement an input with a mask

Input masks can be implemented using a combination of the keyup event, and the HTMLInputElement value, selectionStart, and selectionEnd properties. Here's a very simple implementation which does some of what you want. It's certainly not perfect, but works well enough to demonstrate the principle:

_x000D_
_x000D_
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);_x000D_
_x000D_
function applyDataMask(field) {_x000D_
    var mask = field.dataset.mask.split('');_x000D_
    _x000D_
    // For now, this just strips everything that's not a number_x000D_
    function stripMask(maskedData) {_x000D_
        function isDigit(char) {_x000D_
            return /\d/.test(char);_x000D_
        }_x000D_
        return maskedData.split('').filter(isDigit);_x000D_
    }_x000D_
    _x000D_
    // Replace `_` characters with characters from `data`_x000D_
    function applyMask(data) {_x000D_
        return mask.map(function(char) {_x000D_
            if (char != '_') return char;_x000D_
            if (data.length == 0) return char;_x000D_
            return data.shift();_x000D_
        }).join('')_x000D_
    }_x000D_
    _x000D_
    function reapplyMask(data) {_x000D_
        return applyMask(stripMask(data));_x000D_
    }_x000D_
    _x000D_
    function changed() {   _x000D_
        var oldStart = field.selectionStart;_x000D_
        var oldEnd = field.selectionEnd;_x000D_
        _x000D_
        field.value = reapplyMask(field.value);_x000D_
        _x000D_
        field.selectionStart = oldStart;_x000D_
        field.selectionEnd = oldEnd;_x000D_
    }_x000D_
    _x000D_
    field.addEventListener('click', changed)_x000D_
    field.addEventListener('keyup', changed)_x000D_
}
_x000D_
ISO Date: <input type="text" value="____-__-__" data-mask="____-__-__"/><br/>_x000D_
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>
_x000D_
_x000D_
_x000D_

(View in JSFiddle)

There are also a number of libraries out there which perform this function. Some examples include:

Can't create handler inside thread that has not called Looper.prepare()

Using lambda:

activity.runOnUiThread(() -> Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show());

How to Deep clone in javascript

my addition to all the answers

function deepCopy(arr) {
  if (typeof arr !== 'object') return arr
  if (Array.isArray(arr)) return [...arr].map(deepCopy)
  for (const prop in arr) 
    copy[prop] = deepCopy(arr[prop])
  return copy
}

how to use sqltransaction in c#

Well, I don't understand why are you used transaction in case when you make a select.

Transaction is useful when you make changes (add, edit or delete) data from database.

Remove transaction unless you use insert, update or delete statements

Chrome / Safari not filling 100% height of flex parent

Solution: Remove height: 100% in .item-inner and add display: flex in .item

Demo: https://codepen.io/tronghiep92/pen/NvzVoo

Class Not Found Exception when running JUnit test

Check if your project is opened as a Maven project and not just a regular Java project. Actually a no-brainer, but that is exactly the same reason why you might miss it.

Finding diff between current and last version

If last versions means last tag, and current versions means HEAD (current state), it's just a diff with the last tag:

Looking for tags:

$ git tag --list
...
v20.11.23.4
v20.11.25.1
v20.11.25.2
v20.11.25.351

The last tag would be:

$ git tag --list | tail -n 1
v20.11.25.351

Putting it together:

tag=$(git tag --list | tail -n 1)
git diff $tag

How to use HttpWebRequest (.NET) asynchronously?

public void GetResponseAsync (HttpWebRequest request, Action<HttpWebResponse> gotResponse)
    {
        if (request != null) { 
            request.BeginGetRequestStream ((r) => {
                try { // there's a try/catch here because execution path is different from invokation one, exception here may cause a crash
                    HttpWebResponse response = request.EndGetResponse (r);
                    if (gotResponse != null) 
                        gotResponse (response);
                } catch (Exception x) {
                    Console.WriteLine ("Unable to get response for '" + request.RequestUri + "' Err: " + x);
                }
            }, null);
        } 
    }

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

To attach the Java source code with Eclipse,

When you install the JDK, you must have selected the option to install the Java source files too. This will copy the src.zip file in the installation directory. In Eclipse, go to Window -> Preferences -> Java -> Installed JREs -> Add and choose the JDK you have in your system. Eclipse will now list the JARs found in the dialog box. There, select the rt.jar and choose Source Attachment. By default, this will be pointing to the correct src.zip. If not, choose the src.zip file which you have in your java installation directory. java source attach in eclipse Similarly, if you have the javadoc downloaded in your machine, you can configure that too in this dialog box.

How can I use a carriage return in a HTML tooltip?

I don't believe it is. Firefox 2 trims long link titles anyway and they should really only be used to convey a small amount of help text. If you need more explanation text I would suggest that it belongs in a paragraph associated with the link. You could then add the tooltip javascript code to hide those paragraphs and show them as tooltips on hover. That's your best bet for getting it to work cross-browser IMO.

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

How do I change UIView Size?

Swift 3 and Swift 4:

myView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)

How do you fix the "element not interactable" exception?

I have found that using Thread.sleep(milliseconds) helps almost all the time for me. It takes time for the element to load hence it is not interactable. So i put Thread.sleep() after selecting each value. So far this has helped me avoid the error.

try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}

        Select nationalityDropdown=new Select(driver.findElement(By.id("ContentPlaceHolderMain_ddlNationality")));

        nationalityDropdown.selectByValue("Indian");

        try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}     

Oracle client and networking components were not found

Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.

Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec executable, SSIS will not be able to find the Oracle client. The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.

AssertNull should be used or AssertNotNull

Use assertNotNull(obj). assert means must be.

Visual Studio 2012 Web Publish doesn't copy files

Had the same problem recently in VS 2013 for a MVC project in which I imported Umbraco CMS. I couldn't publish. The answer above helped, though I needed a while to figure out what I actually should do in VS. It needed some research e.g. on MS blogs to find out. I try to say it simple:

  • Choose in the VS toolbar a certain configuration e.g. Release and Any CPU. Run the project.
  • Afterwards right-click in the Solution Explorer on the solution in question, choose Publish. Create a new publishing profile or use a given one, but always make sure that in the settings the same configuration (e.g. Release and Any CPU) is chosen, as before you run the project the last time.
  • Additionally in my case it was necessary to delete the OBJ folder because here the settings from my last unsuccessful tries to publish got stuck, though I restarted VS and deleting all publishing profiles.

Inserting a text where cursor is using Javascript/jquery

using @quick_sliv answer:

function insertAtCaret(el, text) {
    var caretPos = el.selectionStart;
    var textAreaTxt = el.value;
    el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
};

MySQL WHERE: how to write "!=" or "not equals"?

DELETE FROM konta WHERE taken <> '';

Java: How to check if object is null?

DIY

private boolean isNull(Object obj) {
    return obj == null;
}

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
    drawable = getRandomDrawable();
}

Get Substring between two characters using javascript

This could be the possible solution

var str = 'RACK NO:Stock;PRODUCT TYPE:Stock Sale;PART N0:0035719061;INDEX NO:21A627 042;PART NAME:SPRING;';  
var newstr = str.split(':')[1].split(';')[0]; // return value as 'Stock'

console.log('stringvalue',newstr)

Converting between java.time.LocalDateTime and java.util.Date

Everything is here : http://blog.progs.be/542/date-to-java-time

The answer with "round-tripping" is not exact : when you do

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

if your system timezone is not UTC/GMT, you change the time !

GitLab git user password

I had this same problem when using a key of 4096 bits:

$ ssh-keygen -t rsa -C "GitLab" -b 4096
$ ssh -vT git@gitlabhost
...
debug1: Offering public key: /home/user/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/user/.ssh/id_dsa
debug1: Trying private key: /home/user/.ssh/id_ecdsa
debug1: Next authentication method: password
git@gitlabhost's password:
Connection closed by host

But with the 2048 bit key (the default size), ssh connects to gitlab without prompting for a password (after adding the new pub key to the user's gitlab ssh keys)

$ ssh-keygen -t rsa -C "GitLab"
$ ssh -vT git@gitlabhost
Welcome to GitLab, Joe User!

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

Map a network drive to be used by a service

ForcePush,

NOTE: The newly created mapped drive will now appear for ALL users of this system but they will see it displayed as "Disconnected Network Drive (Z:)". Do not let the name fool you. It may claim to be disconnected but it will work for everyone. That's how you can tell this hack is not supported by M$...

It all depends on the share permissions. If you have Everyone in the share permissions, this mapped drive will be accessible by other users. But if you have only some particular user whose credentials you used in your batch script and this batch script was added to the Startup scripts, only System account will have access to that share not even Administrator. So if you use, for example, a scheduled ntbackuo job, System account must be used in 'Run as'. If your service's 'Log on as: Local System account' it should work.

What I did, I didn't map any drive letter in my startup script, just used net use \\\server\share ... and used UNC path in my scheduled jobs. Added a logon script (or just add a batch file to the startup folder) with the mapping to the same share with some drive letter: net use Z: \\\... with the same credentials. Now the logged user can see and access that mapped drive. There are 2 connections to the same share. In this case the user doesn't see that annoying "Disconnected network drive ...". But if you really need access to that share by the drive letter not just UNC, map that share with the different drive letters, e.g. Y for System and Z for users.

Can you change what a symlink points to after it is created?

Yes, you can!

$ ln -sfn source_file_or_directory_name softlink_name

How can I make sticky headers in RecyclerView? (Without external lib)

The answer has already been here. If you don't want to use any library, you can follow these steps:

  1. Sort list with data by name
  2. Iterate via list with data, and in place when current's item first letter != first letter of next item, insert "special" kind of object.
  3. Inside your Adapter place special view when item is "special".

Explanation:

In onCreateViewHolder method we can check viewType and depending on the value (our "special" kind) inflate a special layout.

For example:

public static final int TITLE = 0;
public static final int ITEM = 1;

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (context == null) {
        context = parent.getContext();
    }
    if (viewType == TITLE) {
        view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_title, parent,false);
        return new TitleElement(view);
    } else if (viewType == ITEM) {
        view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_item, parent,false);
        return new ItemElement(view);
    }
    return null;
}

where class ItemElement and class TitleElement can look like ordinary ViewHolder :

public class ItemElement extends RecyclerView.ViewHolder {
//TextView text;

public ItemElement(View view) {
    super(view);
   //text = (TextView) view.findViewById(R.id.text);

}

So the idea of all of that is interesting. But i am interested if it's effectively, cause we need to sort the data list. And i think this will take the speed down. If any thoughts about it, please write me :)

And also the opened question : is how to hold the "special" layout on the top, while the items are recycling. Maybe combine all of that with CoordinatorLayout.

Checking if a string can be converted to float in Python

Python method to check for float:

def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False

Don't get bit by the goblins hiding in the float boat! DO UNIT TESTING!

What is, and is not a float may surprise you:

Command to parse                        Is it a float?  Comment
--------------------------------------  --------------- ------------
print(isfloat(""))                      False
print(isfloat("1234567"))               True 
print(isfloat("NaN"))                   True            nan is also float
print(isfloat("NaNananana BATMAN"))     False
print(isfloat("123.456"))               True
print(isfloat("123.E4"))                True
print(isfloat(".1"))                    True
print(isfloat("1,234"))                 False
print(isfloat("NULL"))                  False           case insensitive
print(isfloat(",1"))                    False           
print(isfloat("123.EE4"))               False           
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777"))              True            This is same as Inf
print(isfloat("-iNF"))                  True
print(isfloat("1.797693e+308"))         True
print(isfloat("infinity"))              True
print(isfloat("infinity and BEYOND"))   False
print(isfloat("12.34.56"))              False           Two dots not allowed.
print(isfloat("#56"))                   False
print(isfloat("56%"))                   False
print(isfloat("0E0"))                   True
print(isfloat("x86E0"))                 False
print(isfloat("86-5"))                  False
print(isfloat("True"))                  False           Boolean is not a float.   
print(isfloat(True))                    True            Boolean is a float
print(isfloat("+1e1^5"))                False
print(isfloat("+1e1"))                  True
print(isfloat("+1e1.3"))                False
print(isfloat("+1.3P1"))                False
print(isfloat("-+1"))                   False
print(isfloat("(1)"))                   False           brackets not interpreted

Get int from String, also containing letters, in Java

Replace all non-digit with blank: the remaining string contains only digits.

Integer.parseInt(s.replaceAll("[\\D]", ""))

This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.

If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:

s.matches("[\\d]+[A-Za-z]?")

Bulk Insert to Oracle using .NET

SQL Server's SQLBulkCopy is blindingly fast. Unfortunately, I found that OracleBulkCopy is far slower. Also it has problems:

  • You must be very sure that your input data is clean if you plan to use OracleBulkCopy. If a primary key violation occurs, an ORA-26026 is raised and it appears to be unrecoverable. Trying to rebuild the index does not help and any subsequent insert on the table fails, also normal inserts.
  • Even if the data is clean, I found that OracleBulkCopy sometimes gets stuck inside WriteToServer. The problem seems to depend on the batch size. In my test data, the problem would happen at the exact same point in my test when I repeat is. Use a larger or smaller batch size, and the problem does not happen. I see that the speed is more irregular on larger batch sizes, this points to problems related to memory management.

Actually System.Data.OracleClient.OracleDataAdapter is faster than OracleBulkCopy if you want to fill a table with small records but many rows. You need to tune the batch size though, the optimum BatchSize for OracleDataAdapter is smaller than for OracleBulkCopy.

I ran my test on a Windows 7 machine with an x86 executable and the 32 bits ODP.Net client 2.112.1.0. . The OracleDataAdapter is part of System.Data.OracleClient 2.0.0.0. My test set is about 600,000 rows with a record size of max. 102 bytes (average size 43 chars). Data source is a 25 MB text file, read in line by line as a stream.

In my test I built up the input data table to a fixed table size and then used either OracleBulkCopy or OracleDataAdapter to copy the data block to the server. I left BatchSize as 0 in OracleBulkCopy (so that the current table contents is copied as one batch) and set it to the table size in OracleDataAdapter (again that should create a single batch internally). Best results:

  • OracleBulkCopy: table size = 500, total duration 4'22"
  • OracleDataAdapter: table size = 100, total duration 3'03"

For comparison:

  • SqlBulkCopy: table size = 1000, total duration 0'15"
  • SqlDataAdapter: table size = 1000, total duration 8'05"

Same client machine, test server is SQL Server 2008 R2. For SQL Server, bulk copy is clearly the best way to go. Not only is it overall fastest, but server load is also lower than when using data adapter. It is a pity that OracleBulkCopy does not offer quite the same experience - the BulkCopy API is much easier to use than DataAdapter.

jQuery: how to find first visible input/select/textarea excluding buttons?

This is my summary of the above and works perfectly for me. Thanks for the info!

<script language='javascript' type='text/javascript'>
    $(document).ready(function () {
        var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
        if (firstInput != null) {
            firstInput.focus();
        }
    });
</script>

How do I create a unique ID in Java?

Here's my two cent's worth: I've previously implemented an IdFactory class that created IDs in the format [host name]-[application start time]-[current time]-[discriminator]. This largely guaranteed that IDs were unique across JVM instances whilst keeping the IDs readable (albeit quite long). Here's the code in case it's of any use:

public class IdFactoryImpl implements IdFactory {
  private final String hostName;
  private final long creationTimeMillis;
  private long lastTimeMillis;
  private long discriminator;

  public IdFactoryImpl() throws UnknownHostException {
    this.hostName = InetAddress.getLocalHost().getHostAddress();
    this.creationTimeMillis = System.currentTimeMillis();
    this.lastTimeMillis = creationTimeMillis;
  }

  public synchronized Serializable createId() {
    String id;
    long now = System.currentTimeMillis();

    if (now == lastTimeMillis) {
      ++discriminator;
    } else {
      discriminator = 0;
    }

    // creationTimeMillis used to prevent multiple instances of the JVM
    // running on the same host returning clashing IDs.
    // The only way a clash could occur is if the applications started at
    // exactly the same time.
    id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
    lastTimeMillis = now;

    return id;
  }

  public static void main(String[] args) throws UnknownHostException {
    IdFactory fact = new IdFactoryImpl();

    for (int i=0; i<1000; ++i) {
      System.err.println(fact.createId());
    }
  }
}