Programs & Examples On #Backing

How to use a client certificate to authenticate and authorize in a Web API

Update:

Example from Microsoft:

https://docs.microsoft.com/en-us/azure/app-service/app-service-web-configure-tls-mutual-auth#special-considerations-for-certificate-validation

Original

This is how I got client certification working and checking that a specific Root CA had issued it as well as it being a specific certificate.

First I edited <src>\.vs\config\applicationhost.config and made this change: <section name="access" overrideModeDefault="Allow" />

This allows me to edit <system.webServer> in web.config and add the following lines which will require a client certification in IIS Express. Note: I edited this for development purposes, do not allow overrides in production.

For production follow a guide like this to set up the IIS:

https://medium.com/@hafizmohammedg/configuring-client-certificates-on-iis-95aef4174ddb

web.config:

<security>
  <access sslFlags="Ssl,SslNegotiateCert,SslRequireCert" />
</security>

API Controller:

[RequireSpecificCert]
public class ValuesController : ApiController
{
    // GET api/values
    public IHttpActionResult Get()
    {
        return Ok("It works!");
    }
}

Attribute:

public class RequireSpecificCertAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            X509Certificate2 cert = actionContext.Request.GetClientCertificate();
            if (cert == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Client Certificate Required"
                };

            }
            else
            {
                X509Chain chain = new X509Chain();

                //Needed because the error "The revocation function was unable to check revocation for the certificate" happened to me otherwise
                chain.ChainPolicy = new X509ChainPolicy()
                {
                    RevocationMode = X509RevocationMode.NoCheck,
                };
                try
                {
                    var chainBuilt = chain.Build(cert);
                    Debug.WriteLine(string.Format("Chain building status: {0}", chainBuilt));

                    var validCert = CheckCertificate(chain, cert);

                    if (chainBuilt == false || validCert == false)
                    {
                        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                        {
                            ReasonPhrase = "Client Certificate not valid"
                        };
                        foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                        {
                            Debug.WriteLine(string.Format("Chain error: {0} {1}", chainStatus.Status, chainStatus.StatusInformation));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }

            base.OnAuthorization(actionContext);
        }
    }

    private bool CheckCertificate(X509Chain chain, X509Certificate2 cert)
    {
        var rootThumbprint = WebConfigurationManager.AppSettings["rootThumbprint"].ToUpper().Replace(" ", string.Empty);

        var clientThumbprint = WebConfigurationManager.AppSettings["clientThumbprint"].ToUpper().Replace(" ", string.Empty);

        //Check that the certificate have been issued by a specific Root Certificate
        var validRoot = chain.ChainElements.Cast<X509ChainElement>().Any(x => x.Certificate.Thumbprint.Equals(rootThumbprint, StringComparison.InvariantCultureIgnoreCase));

        //Check that the certificate thumbprint matches our expected thumbprint
        var validCert = cert.Thumbprint.Equals(clientThumbprint, StringComparison.InvariantCultureIgnoreCase);

        return validRoot && validCert;
    }
}

Can then call the API with client certification like this, tested from another web project.

[RoutePrefix("api/certificatetest")]
public class CertificateTestController : ApiController
{

    public IHttpActionResult Get()
    {
        var handler = new WebRequestHandler();
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ClientCertificates.Add(GetClientCert());
        handler.UseProxy = false;
        var client = new HttpClient(handler);
        var result = client.GetAsync("https://localhost:44331/api/values").GetAwaiter().GetResult();
        var resultString = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        return Ok(resultString);
    }

    private static X509Certificate GetClientCert()
    {
        X509Store store = null;
        try
        {
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

            var certificateSerialNumber= "?81 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);

            //Does not work for some reason, could be culture related
            //var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);

            //if (certs.Count == 1)
            //{
            //    var cert = certs[0];
            //    return cert;
            //}

            var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));

            return cert;
        }
        finally
        {
            store?.Close();
        }
    }
}

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

The problem is that the file name should be Dockerfile and not DockerFile or dockerfile it should be D capital followed by ockerfile in lower-case pls note

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Docker error : no space left on device

Clean Docker by using the following command:

docker images --no-trunc | grep '<none>' | awk '{ print $3 }' \
| xargs docker rmi

React-router: How to manually invoke Link?

React Router 4

You can easily invoke the push method via context in v4:

this.context.router.push(this.props.exitPath);

where context is:

static contextTypes = {
    router: React.PropTypes.object,
};

Property getters and setters

Setters/getters in Swift are quite different than ObjC. The property becomes a computed property which means it does not have a backing variable such as _x as it would in ObjC.

In the solution code below you can see the xTimesTwo does not store anything, but simply computes the result from x.

See Official docs on computed properties.

The functionality you want might also be Property Observers.

What you need is:

var x: Int

var xTimesTwo: Int {
    set {
       x = newValue / 2
    }
    get {
        return x * 2
    }
}

You can modify other properties within the setter/getters, which is what they are meant for.

The model backing the 'ApplicationDbContext' context has changed since the database was created

When I am developing, I prefer to use this practical class to configure Migrations.

Hope it helps.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        Database.SetInitializer(new StackOverflowInitializer());
    }

    public class StackOverflowInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
    {
        public StackOverflowInitializer()
        {
            // TODO NOTHING, COMMENT ALL

            // IF CHANGES, RECREATE
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());

            // CREATE ONLY NOT EXITS
            //Database.SetInitializer<Context>(new CreateDatabaseIfNotExists<ApplicationDbContext>());
        }

    }

    public System.Data.Entity.DbSet<stackoverflow.Models.Company> Companies { get; set; }

}

Model backing a DB Context has changed; Consider Code First Migrations

This error occurs when you have database is not in sync with your model and vice versa. To overcome this , follow the below steps -

a) Add a migration file using add-migration <{Migration File Name}> through the nuget package manager console. This migration file will have the script to sync anything not in sync between Db and code.

b) Update the database using update-database command. This will update the database with the latest changes in your model.

If this does not help, try these steps after adding the line of code in the Application_Start method of Global.asax.cs file -

Database.SetInitializer<VidlyDbContext>(new DropCreateDatabaseIfModelChanges<VidlyDbContext>());

Reference - http://robertgreiner.com/2012/05/unable-to-update-database-to-match-the-current-model-pending-changes/

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

@RequestParam is the HTTP GET or POST parameter sent by client, request mapping is a segment of URL which's variable:

http:/host/form_edit?param1=val1&param2=val2

var1 & var2 are request params.

http:/host/form/{params}

{params} is a request mapping. you could call your service like : http:/host/form/user or http:/host/form/firm where firm & user are used as Pathvariable.

Can I update a JSF component from a JSF backing bean method?

I also tried to update a component from a jsf backing bean/class

You need to do the following after manipulating the UI component:

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())

It is important to use the clientId instead of the (server-side) componentId!!

Performance differences between ArrayList and LinkedList

Ignore this answer for now. The other answers, particularly that of aix, are mostly correct. Over the long term they're the way to bet. And if you have enough data (on one benchmark on one machine, it seemed to be about one million entries) ArrayList and LinkedList do currently work as advertized. However, there are some fine points that apply in the early 21st century.

Modern computer technology seems, by my testing, to give an enormous edge to arrays. Elements of an array can be shifted and copied at insane speeds. As a result arrays and ArrayList will, in most practical situations, outperform LinkedList on inserts and deletes, often dramatically. In other words, ArrayList will beat LinkedList at its own game.

The downside of ArrayList is it tends to hang onto memory space after deletions, where LinkedList gives up space as it gives up entries.

The bigger downside of arrays and ArrayList is they fragment free memory and overwork the garbage collector. As an ArrayList expands, it creates new, bigger arrays, copies the old array to the new one, and frees the old one. Memory fills with big contiguous chunks of free memory that are not big enough for the next allocation. Eventually there's no suitable space for that allocation. Even though 90% of memory is free, no individual piece is big enough to do the job. The GC will work frantically to move things around, but if it takes too long to rearrange the space, it will throw an OutOfMemoryException. If it doesn't give up, it can still slow your program way down.

The worst of it is this problem can be hard to predict. Your program will run fine one time. Then, with a bit less memory available, with no warning, it slows or stops.

LinkedList uses small, dainty bits of memory and GC's love it. It still runs fine when you're using 99% of your available memory.

So in general, use ArrayList for smaller sets of data that are not likely to have most of their contents deleted, or when you have tight control over creation and growth. (For instance, creating one ArrayList that uses 90% of memory and using it without filling it for the duration of the program is fine. Continually creating and freeing ArrayList instances that use 10% of memory will kill you.) Otherwise, go with LinkedList (or a Map of some sort if you need random access). If you have very large collections (say over 100,000 elements), no concerns about the GC, and plan lots of inserts and deletes and no random access, run a few benchmarks to see what's fastest.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

If you are doing VANILLA plain JavaScript without jQuery, then you must use (Internet Explorer 9 or later):

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
});

Above is the equivalent of jQuery .ready:

$(document).ready(function() {
    console.log("Ready!");
});

Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs.

$(function() {
    console.log("ready!");
});

NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready):

DO NOT use an IIFE like this that is self executing:

 Example:

(function() {
   // Your page initialization code here  - WRONG
   // The DOM will be available here   - WRONG
})();

This IIFE will NOT wait for your DOM to load. (I'm even talking about latest version of Chrome browser!)

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Div not expanding even with content inside

Putting a <br clear="all" /> after the last floated div worked the best for me. Thanks to Brent Fiare & Paul Waite for the info that floated divs will not expand the height of the parent div! This has been driving me nuts! ;-}

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

The model backing the <Database> context has changed since the database was created

I had the same issue - re-adding the migration and updating the database didn't work and none of the answers above seemed right. Then inspiration hit me - I'm using multiple tiers (one web, one data, and one business). The data layer has the context and all the models. The web layer never threw this exception - it was the business layer (which I set as console application for testing and debugging). Turns out the business layer wasn't using the right connection string to get the db and make the context. So I added the connection string to the app config of the business layer (and the data layer) and viola it works. Putting this here for others who may encounter the same issue.

Heroku: How to push different local Git branches to Heroku/master

The safest command to push different local Git branches to Heroku/master.

git push -f heroku branch_name:master

Note: Although, you can push without using the -f, the -f (force flag) is recommended in order to avoid conflicts with other developers’ pushes.

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

How to backup a local Git repository?

The other offical way would be using git bundle

That will create a file that support git fetch and git pull in order to update your second repo.
Useful for incremental backup and restore.

But if you need to backup everything (because you do not have a second repo with some older content already in place), the backup is a bit more elaborate to do, as mentioned in my other answer, after Kent Fredric's comment:

$ git bundle create /tmp/foo master
$ git bundle create /tmp/foo-all --all
$ git bundle list-heads /tmp/foo
$ git bundle list-heads /tmp/foo-all

(It is an atomic operation, as opposed to making an archive from the .git folder, as commented by fantabolous)


Warning: I wouldn't recommend Pat Notz's solution, which is cloning the repo.
Backup many files is always more tricky than backing up or updating... just one.

If you look at the history of edits of the OP Yar answer, you would see that Yar used at first a clone --mirror, ... with the edit:

Using this with Dropbox is a total mess.
You will have sync errors, and you CANNOT ROLL A DIRECTORY BACK IN DROPBOX.
Use git bundle if you want to back up to your dropbox.

Yar's current solution uses git bundle.

I rest my case.

Select Multiple Fields from List in Linq

var selectedCategories =
    from value in
        (from data in listObject
        orderby data.category_name descending
        select new { ID = data.category_id, Name = data.category_name })
    group value by value.Name into g
    select g.First();

foreach (var category in selectedCategories) Console.WriteLine(category);

Edit: Made it more LINQ-ey!

Variables as commands in bash scripts

There is a point to only put commands and options in variables.

#! /bin/bash

if [ $# -ne 2 ]
then
    echo "Usage: `basename $0` DIRECTORY BACKUP_DIRECTORY"
    exit 1
fi

. standard_tools    

directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"

${tar_create} "${directory}" | ${openssl} | ${split_1024} "$backup_file"

You can relocate the commands to another file you source, so you can reuse the same commands and options across many scripts. This is very handy when you have a lot of scripts and you want to control how they all use tools. So standard_tools would contain:

export tar_create="tar cv"
export openssl="openssl des3 -salt"
export split_1024="split -b 1024m -"

Question mark characters displaying within text, why is this?

The following articles will be useful

http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html

http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html

After you connect to the database issue the following command:

SET NAMES 'utf8';

Ensure that your web page also uses the UTF-8 encoding:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

PHP also offers several function that will be useful for conversions:

http://us3.php.net/manual/en/function.iconv.php

http://us.php.net/mb_convert_encoding

SVN repository backup strategies

as others have said, hot-backup.py from the Subversion team has some nice features over just plain svnadmin hotcopy

I run a scheduled task on a python script that spiders for all my repositories on the machine, and uses hotbackup to keep several days worth of hotcopies (paranoid of corruption) and an svnadmin svndump on a remote machine. Restoration is really easy from that - so far.

Convert Uri to String and String to Uri

You can use Drawable instead of Uri.

   ImageView iv=(ImageView)findViewById(R.id.imageView1);
   String pathName = "/external/images/media/470939"; 
   Drawable image = Drawable.createFromPath(pathName);
   iv.setImageDrawable(image);

This would work.

setTimeout in React Native

const getData = () => {
// some functionality
}

const that = this;
   setTimeout(() => {
   // write your functions    
   that.getData()
},6000);

Simple, Settimout function get triggered after 6000 milliseonds

How to copy a directory structure but only include certain files (using windows batch files)

That's only two simple commands, but I wouldn't recommend this, unless the files that you DON'T need to copy are small. That's because this will copy ALL files and then remove the files that are not needed in the copy.

xcopy /E /I folder1 copy_of_folder1
for /F "tokens=1 delims=" %i in ('dir /B /S /A:-D copy_of_files ^| find /V "info.txt" ^| find /V "data.zip"') do del /Q "%i"

Sure, the second command is kind of long, but it works!

Also, this approach doesn't require you to download and install any third party tools (Windows 2000+ BATCH has enough commands for this).

Typescript: Type 'string | undefined' is not assignable to type 'string'

You could make use of Typescript's optional chaining. Example:

const name = person?.name;

If the property name exists on the person object you would get its value but if not it would automatically return undefined.

You could make use of this resource for a better understanding.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

How to allow only a number (digits and decimal point) to be typed in an input?

You could try this directive to stop any invalid characters from being entered into an input field. (Update: this relies on the directive having explicit knowledge of the model, which is not ideal for reusability, see below for a re-usable example)

app.directive('isNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope) {    
            scope.$watch('wks.number', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.wks.number = oldValue;
                }
            });
        }
    };
});

It also accounts for these scenarios:

  1. Going from a non-empty valid string to an empty string
  2. Negative values
  3. Negative decimal values

I have created a jsFiddle here so you can see how it works.

UPDATE

Following Adam Thomas' feedback regarding not including model references directly inside a directive (which I also believe is the best approach) I have updated my jsFiddle to provide a method which does not rely on this.

The directive makes use of bi-directional binding of local scope to parent scope. The changes made to variables inside the directive will be reflected in the parent scope, and vice versa.

HTML:

<form ng-app="myapp" name="myform" novalidate> 
    <div ng-controller="Ctrl">
        <number-only-input input-value="wks.number" input-name="wks.name"/>
    </div>
</form>

Angular code:

var app = angular.module('myapp', []);

app.controller('Ctrl', function($scope) {
    $scope.wks =  {number: 1, name: 'testing'};
});
app.directive('numberOnlyInput', function () {
    return {
        restrict: 'EA',
        template: '<input name="{{inputName}}" ng-model="inputValue" />',
        scope: {
            inputValue: '=',
            inputName: '='
        },
        link: function (scope) {
            scope.$watch('inputValue', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.inputValue = oldValue;
                }
            });
        }
    };
});

Opening a .ipynb.txt File

Try the following steps:

  1. Download the file open it in the Juypter Notebook.
  2. Go to File -> Rename and remove the .txt extension from the end; so now the file name has just .ipynb extension.
  3. Now reopen it from the Juypter Notebook.

Class has no objects member

This issue happend when I use pylint_runner

So what I do is open .pylintrc file and add this

# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=objects

How to disable auto-play for local video in iframe

What do you think about video tag ? If you don't have to use iframe tag you can use video tag instead.

<video width="500" height="345" src="hey.mp4"  />

You should not use autoplay attribute in your video tag to disable autoplay.

how to destroy an object in java?

Set to null. Then there are no references anymore and the object will become eligible for Garbage Collection. GC will automatically remove the object from the heap.

How to request a random row in SQL?

With SQL Server 2012+ you can use the OFFSET FETCH query to do this for a single random row

select  * from MyTable ORDER BY id OFFSET n ROW FETCH NEXT 1 ROWS ONLY

where id is an identity column, and n is the row you want - calculated as a random number between 0 and count()-1 of the table (offset 0 is the first row after all)

This works with holes in the table data, as long as you have an index to work with for the ORDER BY clause. Its also very good for the randomness - as you work that out yourself to pass in but the niggles in other methods are not present. In addition the performance is pretty good, on a smaller dataset it holds up well, though I've not tried serious performance tests against several million rows.

Android button background color

With version 1.2.0-alpha06 of material design library, now we can use android:background="..." on MaterialButton components:

<com.google.android.material.button.MaterialButton
    android:background="#fff"
    ...
/>

What port is a given program using?

TCPView can do what you asked for.

CMake does not find Visual C++ compiler

In my case the issue was that the parent project, which is including googletest via

add_subdirectory(gtest_dir)

was defined as

PROJECT( projname CXX )

Somehow, CMake does not recognize

PROJECT(sub_project_name CXX C)

since the C compiler is not set in the parent.

I solved the issue by using

PROJECT( projname CXX C)

in my main CMakeLists.txt file.

<ng-container> vs <template>

In my case it acts like a <div> or <span> however even <span> messes up with my AngularFlex styling but ng-container doesn't.

SVN: Is there a way to mark a file as "do not commit"?

Subversion does not have a built-in "do not commit" / "ignore on commit" feature, as of February 2016 / version 1.9. This answer is a non-ideal command-line workaround

As the OP states, TortoiseSVN has a built in changelist, "ignore-on-commit", which is automatically excluded from commits. The command-line client does not have this, so you need to use multiple changelists to accomplish this same behavior (with caveats):

  • one for work you want to commit [work]
  • one for things you want to ignore [ignore-on-commit]

Since there's precedent with TortoiseSVN, I use "ignore-on-commit" in my examples for the files I don't want to commit. I'll use "work" for the files I do, but you could pick any name you wanted.

First, add all files to a changelist named "work". This must be run from the root of your working copy:

svn cl work . -R

This will add all files in the working copy recursively to the changelist named "work". There is a disadvantage to this - as new files are added to the working copy, you'll need to specifically add the new files or they won't be included. Second, if you have to run this again you'll then need to re-add all of your "ignore-on-commit" files again. Not ideal - you could start maintaining your own 'ignore' list in a file as others have done.

Then, for the files you want to exclude:

svn cl ignore-on-commit path\to\file-to-ignore

Because files can only be in one changelist, running this addition after your previous "work" add will remove the file you want to ignore from the "work" changelist and put it in the "ignore-on-commit" changelist.

When you're ready to commit your modified files you do wish to commit, you'd then simply add "--cl work" to your commit:

svn commit --cl work -m "message"

Here's what a simple example looks like on my machine:

D:\workspace\trunk>svn cl work . -R
Skipped '.'
Skipped 'src'
Skipped 'src\conf'
A [work] src\conf\db.properties
Skipped 'src\java'
Skipped 'src\java\com'
Skipped 'src\java\com\corp'
Skipped 'src\java\com\corp\sample'
A [work] src\java\com\corp\sample\Main.java
Skipped 'src\java\com\corp\sample\controller'
A [work] src\java\com\corp\sample\controller\Controller.java
Skipped 'src\java\com\corp\sample\model'
A [work] src\java\com\corp\sample\model\Model.java
Skipped 'src\java\com\corp\sample\view'
A [work] src\java\com\corp\sample\view\View.java
Skipped 'src\resource'
A [work] src\resource\icon.ico
Skipped 'src\test'

D:\workspace\trunk>svn cl ignore-on-commit src\conf\db.properties
D [work] src\conf\db.properties
A [ignore-on-commit] src\conf\db.properties

D:\workspace\trunk>svn status

--- Changelist 'work':
        src\java\com\corp\sample\Main.java
        src\java\com\corp\sample\controller\Controller.java
        src\java\com\corp\sample\model\Model.java
M       src\java\com\corp\sample\view\View.java
        src\resource\icon.ico

--- Changelist 'ignore-on-commit':
M       src\conf\db.properties

D:\workspace\trunk>svn commit --cl work -m "fixed refresh issue"
Sending        src\java\com\corp\sample\view\View.java
Transmitting file data .done
Committing transaction...
Committed revision 9.

An alternative would be to simply add every file you wish to commit to a 'work' changelist, and not even maintain an ignore list, but this is a lot of work, too. Really, the only simple, ideal solution is if/when this gets implemented in SVN itself. There's a longstanding issue about this in the Subversion issue tracker, SVN-2858, in the event this changes in the future.

How to restrict the selectable date ranges in Bootstrap Datepicker?

Another possibility is to use the options with data attributes, like this(minimum date 1 week before):

<input class='datepicker' data-date-start-date="-1w">

More info: http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

How to split a string after specific character in SQL Server and update this value to specific column

SELECT SUBSTRING(ParentBGBU,0,CHARINDEX('-',ParentBGBU,0)) FROM dbo.tblHCMMaster;

How to view unallocated free space on a hard disk through terminal

While using the disk utility graphically, it shows disk space used by all filesystem and it uses commands in the terminal such as df -H. In other words, it uses powers of 1000, not 1024. (Note: there is difference between -h and -H.)

While also finding the unallocated space in a hard disk using command line # fdisk /dev/sda will display the total space and total cylinder value.

Now check the last cylinder value and subtract it from the total cylinder value. Hence the final value * 1000 gives you the unallocated disk space.

Note: the cylinder value shows up in df -H as a power of 1000 or it might also show up using df -h, a power of 1024.

C# Connecting Through Proxy

I am going to use an example to add to the answers above.

I ran into proxy issues while trying to install packages via Web Platform Installer

That too uses a config file which is WebPlatformInstaller.exe.config

I tried the edits suggest in this IIS forum which is

<?xml version="1.0" encoding="utf-8" ?>
<configuration>  
  <system.net>    
     <defaultProxy enabled="True" useDefaultCredentials="True"/>      
   </system.net>
</configuration>

and

<?xml version="1.0" encoding="utf-8" ?>
<configuration>  
   <system.net>    
     <defaultProxy>      
          <proxy 
               proxyaddress="http://yourproxy.company.com:80" 
               usesystemdefault="True"
               autoDetect="False" />    
     </defaultProxy>  
   </system.net>
</configuration>

None of these worked.

What worked for me was this -

<system.net>    
    <defaultProxy enabled="true" useDefaultCredentials="false">
      <module type="WebPI.Net.AuthenticatedProxy, WebPI.Net, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79a8d77199cbf3bc" />
    </defaultProxy>  
 </system.net>

The module needed to be registered with Web Platform Installer in order to use it.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

If you really want to match only the dot, then StringComparison.Ordinal would be fastest, as there is no case-difference.

"Ordinal" doesn't use culture and/or casing rules that are not applicable anyway on a symbol like a ..

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

In most of the cases, deleting all the node packages and then installing them again, solve the problem.

But In my case node_modules folder has not write permission.

How do I compare strings in GoLang?

The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like \n, \r, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.

How to iterate over the keys and values with ng-repeat in AngularJS?

I don't think there's a builtin function in angular for doing this, but you can do this by creating a separate scope property containing all the header names, and you can fill this property automatically like this:

var data = {
  foo: 'a',
  bar: 'b'
};

$scope.objectHeaders = [];

for ( property in data ) {
  $scope.objectHeaders.push(property); 
}

// Output: [ 'foo', 'bar' ]

Easiest way to convert month name to month number in JS ? (Jan = 01)

One more way to do the same

month1 = month1.toLowerCase();
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
month1 = months.indexOf(month1);

Timer function to provide time in nano seconds using C++

Here is a nice Boost timer that works well:

//Stopwatch.hpp

#ifndef STOPWATCH_HPP
#define STOPWATCH_HPP

//Boost
#include <boost/chrono.hpp>
//Std
#include <cstdint>

class Stopwatch
{
public:
    Stopwatch();
    virtual         ~Stopwatch();
    void            Restart();
    std::uint64_t   Get_elapsed_ns();
    std::uint64_t   Get_elapsed_us();
    std::uint64_t   Get_elapsed_ms();
    std::uint64_t   Get_elapsed_s();
private:
    boost::chrono::high_resolution_clock::time_point _start_time;
};

#endif // STOPWATCH_HPP


//Stopwatch.cpp

#include "Stopwatch.hpp"

Stopwatch::Stopwatch():
    _start_time(boost::chrono::high_resolution_clock::now()) {}

Stopwatch::~Stopwatch() {}

void Stopwatch::Restart()
{
    _start_time = boost::chrono::high_resolution_clock::now();
}

std::uint64_t Stopwatch::Get_elapsed_ns()
{
    boost::chrono::nanoseconds nano_s = boost::chrono::duration_cast<boost::chrono::nanoseconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(nano_s.count());
}

std::uint64_t Stopwatch::Get_elapsed_us()
{
    boost::chrono::microseconds micro_s = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(micro_s.count());
}

std::uint64_t Stopwatch::Get_elapsed_ms()
{
    boost::chrono::milliseconds milli_s = boost::chrono::duration_cast<boost::chrono::milliseconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(milli_s.count());
}

std::uint64_t Stopwatch::Get_elapsed_s()
{
    boost::chrono::seconds sec = boost::chrono::duration_cast<boost::chrono::seconds>(boost::chrono::high_resolution_clock::now() - _start_time);
    return static_cast<std::uint64_t>(sec.count());
}

How to remove element from ArrayList by checking its value?

Just use myList.remove(myObject).

It uses the equals method of the class. See http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)

BTW, if you have more complex things to do, you should check out the guava library that has dozen of utility to do that with predicates and so on.

What are all the possible values for HTTP "Content-Type" header?

I would aim at covering a subset of possible "Content-type" values, you question seems to focus on identifying known content types.

@Jeroen RFC 1341 reference is great, but for an fairly exhaustive list IANA keeps a web page of officially registered media types here.

Return Result from Select Query in stored procedure to a List

Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:

private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "it.hurts.when.IP";
            builder.UserID = "someDBUser";
            builder.Password = "someDBPassword";
            builder.InitialCatalog = "someDB";
            return new SqlConnection(builder.ConnectionString);
        }

        public static List<T> ExecuteSP<T>(string SPName, List<SqlParameter> Params)
        {
            try
            {
                DataTable dataTable = new DataTable();

                using (SqlConnection Connection = getConnectionString())
                {
                    // Open connection
                    Connection.Open();

                    // Create command from params / SP
                    SqlCommand cmd = new SqlCommand(SPName, Connection);

                    // Add parameters
                    cmd.Parameters.AddRange(Params.ToArray());
                    cmd.CommandType = CommandType.StoredProcedure;

                    // Make datatable for conversion
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dataTable);
                    da.Dispose();

                    // Close connection
                    Connection.Close();
                }

                // Convert to list of T
                var retVal = ConvertToList<T>(dataTable);
                return retVal;
            }
            catch (SqlException e)
            {
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

        /// <summary>
        /// Converts datatable to List<someType> if possible.
        /// </summary>
        public static List<T> ConvertToList<T>(DataTable dt)
        {
            try // Necesarry unfotunately.
            {
                var columnNames = dt.Columns.Cast<DataColumn>()
                    .Select(c => c.ColumnName)
                    .ToList();

                var properties = typeof(T).GetProperties();

                return dt.AsEnumerable().Select(row =>
                    {
                        var objT = Activator.CreateInstance<T>();

                        foreach (var pro in properties)
                        {
                            if (columnNames.Contains(pro.Name))
                            {
                                if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
                                else pro.SetValue(objT, row[pro.Name], null);
                            }
                        }

                        return objT;
                    }).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f

Good way of getting the user's location in Android

Skyhook (http://www.skyhookwireless.com/) has a location provider that is much faster than the standard one Google provides. It might be what you're looking for. I'm not affiliated with them.

How to display a pdf in a modal window?

You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.

Making text background transparent but not text itself

If you use RGBA for modern browsers you don't need let older IEs use only the non-transparent version of the given color with RGB.

If you don't stick to CSS-only solutions, give CSS3PIE a try. With this syntax you can see exactly the same result in older IEs that you see in modern browsers:

div {
    -pie-background: rgba(223,231,233,0.8);
    behavior: url(../PIE.htc);
}

Sum of Numbers C++

The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.

How do I compile the asm generated by GCC?

You can use GAS, which is gcc's backend assembler:

http://linux.die.net/man/1/as

Convert string with comma to integer

The following is another method that will work, although as with some of the other methods it will strip decimal places.

a = 1,112
b = a.scan(/\d+/).join().to_i => 1112

How to select the first element with a specific attribute using XPath

Use:

(/bookstore/book[@location='US'])[1]

This will first get the book elements with the location attribute equal to 'US'. Then it will select the first node from that set. Note the use of parentheses, which are required by some implementations.

Note, this is not the same as /bookstore/book[1][@location='US'] unless the first element also happens to have that location attribute.

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

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

There might be more than one index map to your value, it make more sense to return a list:

In [48]: a
Out[48]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [49]: a.c1[a.c1 == 8].index.tolist()
Out[49]: [4]

Can Android do peer-to-peer ad-hoc networking?

Although Android can't find and connect to ad-hoc networks it sure can connect to Access Points. So as a work-around you can turn your Wireless Card into an Access Point using, for example, Connectify.

How to create .pfx file from certificate and private key?

I got a link with your requirement.Combine CRT and KEY Files into a PFX with OpenSSL

Extracts from the above link:

First we need to extract the root CA certificate from the existing .crt file, because we need this later. So open up the .crt and click on the Certification Path tab.

Click the topmost certificate (In this case VeriSign) and hit View Certificate. Select the Details tab and hit Copy to File…

Select Base-64 encoded X.509 (.CER) certificate Save it as rootca.cer or something similar. Place it in the same folder as the other files.

Rename it from rootca.cer to rootca.crt Now we should have 3 files in our folder from which we can create a PFX file.

Here is where we need OpenSSL. We can either download and install it on Windows, or simply open terminal on OSX.

EDIT:

  1. There is a support link with step by step information on how to do install the certificate.

  2. After successfully install, export the certificate, choose .pfx format, include private key.

    Important Note: : To export the certificate in .pfx format you need to follow the steps on the same machine from which you have requested the certificate.

  3. The imported file can be uploaded to server.

Open source face recognition for Android

macgyver offers face detection programs via a simple to use API.

The program below takes a reference to a public image and will return an array of the coordinates and dimensions of any faces detected in the image.

https://askmacgyver.com/explore/program/face-location/5w8J9u4z

Setting an environment variable before a command in Bash is not working for the second command in a pipe

Use a shell script:

#!/bin/bash
# myscript
FOO=bar
somecommand someargs | somecommand2

> ./myscript

Undefined symbols for architecture x86_64 on Xcode 6.1

I solved the same issue by going to Xcode Build Settings and in Architectures, I changed the Xcode 6.1.1 standard architecture to:-

$(ARCHS_STANDARD_32_BIT)

How can I pad a String in Java?

Since Java 11, String.repeat(int) can be used to left/right pad a given string.

System.out.println("*".repeat(5)+"apple");
System.out.println("apple"+"*".repeat(5));

Output:

*****apple
apple*****

JavaScript require() on client side

I asked myself the very same questions. When I looked into it I found the choices overwhelming.

Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:

outputString = Regex.Replace(inputString, @"\W", "_");

Remember to add

using System.Text.RegularExpressions;

What are the differences between the urllib, urllib2, urllib3 and requests module?

urllib and urllib2 are both Python modules that do URL request related stuff but offer different functionalities.

1) urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL.

2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.

Requests - Requests’ is a simple, easy-to-use HTTP library written in Python.

1) Python Requests encodes the parameters automatically so you just pass them as simple arguments, unlike in the case of urllib, where you need to use the method urllib.encode() to encode the parameters before passing them.

2) It automatically decoded the response into Unicode.

3) Requests also has far more convenient error handling.If your authentication failed, urllib2 would raise a urllib2.URLError, while Requests would return a normal response object, as expected. All you have to see if the request was successful by boolean response.ok

How to close Browser Tab After Submitting a Form?

<?php    
    /* ... SQL EXECUTION TO UPDATE DB ... */

    echo "<script>window.close();</script>";
?>

and Remove the window.close() from the form onsubmit event

How to use an array list in Java?

A List is an ordered Collection of elements. You can add them with the add method, and retrieve them with the get(int index) method. You can also iterate over a List, remove elements, etc. Here are some basic examples of using a List:

List<String> names = new ArrayList<String>(3); // 3 because we expect the list 
    // to have 3 entries.  If we didn't know how many entries we expected, we
    // could leave this empty or use a LinkedList instead
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.get(2)); // prints "Charlie"
System.out.println(names); // prints the whole list
for (String name: names) {
    System.out.println(name);  // prints the names in turn.
}

Encode URL in JavaScript?

Here is a LIVE DEMO of encodeURIComponent() and decodeURIComponent() JS built in functions:

<!DOCTYPE html>
<html>
  <head>
    <style>
      textarea{
        width:30%;
        height:100px;
      }
    </style>
    <script>
      // encode string to base64
      function encode()
      {
        var txt = document.getElementById("txt1").value;
        var result = btoa(txt);
        document.getElementById("txt2").value = result;
      }
      // decode base64 back to original string
      function decode()
      {
        var txt = document.getElementById("txt3").value;
        var result = atob(txt);
        document.getElementById("txt4").value = result;
      }
    </script>
  </head>
  <body>
    <div>
      <textarea id="txt1">Some text to decode
      </textarea>
    </div>
    <div>
      <input type="button" id="btnencode" value="Encode" onClick="encode()"/>
    </div>
    <div>
      <textarea id="txt2">
      </textarea>
    </div>
    <br/>
    <div>
      <textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
      </textarea>
    </div>
    <div>
      <input type="button" id="btndecode" value="Decode" onClick="decode()"/>
    </div>
    <div>
      <textarea id="txt4">
      </textarea>
    </div>
  </body>
</html>

What does axis in pandas mean?

The designer of pandas, Wes McKinney, used to work intensively on finance data. Think of columns as stock names and index as daily prices. You can then guess what the default behavior is (i.e., axis=0) with respect to this finance data. axis=1 can be simply thought as 'the other direction'.

For example, the statistics functions, such as mean(), sum(), describe(), count() all default to column-wise because it makes more sense to do them for each stock. sort_index(by=) also defaults to column. fillna(method='ffill') will fill along column because it is the same stock. dropna() defaults to row because you probably just want to discard the price on that day instead of throw away all prices of that stock.

Similarly, the square brackets indexing refers to the columns since it's more common to pick a stock instead of picking a day.

Read a text file using Node.js?

You'll want to use the process.argv array to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file. For example:

// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
  console.log('Usage: node ' + process.argv[1] + ' FILENAME');
  process.exit(1);
}
// Read the file and print its contents.
var fs = require('fs')
  , filename = process.argv[2];
fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err;
  console.log('OK: ' + filename);
  console.log(data)
});

To break that down a little for you process.argv will usually have length two, the zeroth item being the "node" interpreter and the first being the script that node is currently running, items after that were passed on the command line. Once you've pulled a filename from argv then you can use the filesystem functions to read the file and do whatever you want with its contents. Sample usage would look like this:

$ node ./cat.js file.txt
OK: file.txt
This is file.txt!

[Edit] As @wtfcoder mentions, using the "fs.readFile()" method might not be the best idea because it will buffer the entire contents of the file before yielding it to the callback function. This buffering could potentially use lots of memory but, more importantly, it does not take advantage of one of the core features of node.js - asynchronous, evented I/O.

The "node" way to process a large file (or any file, really) would be to use fs.read() and process each available chunk as it is available from the operating system. However, reading the file as such requires you to do your own (possibly) incremental parsing/processing of the file and some amount of buffering might be inevitable.

how to change the dist-folder path in angular-cli after 'ng build'

Caution: Angular 6 and above!


For readers with an angular.json (not angular-cli.json) the key correct key is outputPath. I guess the angular configuration changed to angular.json in Angular 6, so if you are using version 6 or above you most likely have a angular.json file.

To change the output path you have to change outputPath und the build options.

example angular.json

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "version": 1,
    "projects": {
        "angular-app": {
            "projectType": "application",
            [...]
            "architect": {
                "build": {
                    "builder": "@angular-devkit/build-angular:browser",
                    "options": {
                        "outputPath": "dist/angular-app",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        [...]

I could not find any official docs on this (not included in https://angular.io/guide/workspace-config as I would have expected), maybe someone can link an official resource on this.

How to change port number for apache in WAMP

Just go to httpd.conf file, for ex. under WAMP environment its situated at:

C:\wamp\bin\apache\apache2.2.22\conf\httpd.conf

go to line no. 46 and edit Listen 80 to your requirement for ex.

Listen 8383

newer versions of WAMP uses these 2 lines:

Listen 0.0.0.0:8383  
Listen [::0]:8383

Next go to line no. 171 and edit ServerName localhost:80 to your requirement for ex.

ServerName localhost:8383

Restart Apache and its done !!

Now, you can access with your URL:

http://localhost:8383 or http://192.168.1.1:8383

Hope it helps to people looking for solution here.

box-shadow on bootstrap 3 container

http://jsfiddle.net/Y93TX/2/

     @import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");

.row {
    height: 100px;
    background-color: green;
}
.container {
    margin-top: 50px;
    box-shadow: 0 0 30px black;
    padding:0 15px 0 15px;
}



    <div class="container">
        <div class="row">one</div>
        <div class="row">two</div>
        <div class="row">three</div>
    </div>
</body>

Can I write or modify data on an RFID tag?

It depends on the type of chip you are using, but nowerdays most chips you can write. It also depends on how much power you give your RFID device. To read you dont need allot of power and very little line of sight. To right you need them full insight and longer insight

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

Access Form - Syntax error (missing operator) in query expression

Try making the field names legal by removing spaces. It's a long shot but it has actually helped me before.

What does "request for member '*******' in something not a structure or union" mean?

It may means that you forgot include a header file that define this struct/union. For example:

foo.h file:

typedef union
{
    struct
    {
        uint8_t FIFO_BYTES_AVAILABLE    : 4;
        uint8_t STATE                   : 3;
        uint8_t CHIP_RDY                : 1;
    };
    uint8_t status;
} RF_CHIP_STATUS_t;

RF_CHIP_STATUS_t getStatus();

main.c file:

.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the  #include "foo.h" */
.
.
.

Combining Two Images with OpenCV

For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.

To stack vertically (img1 over img2):

vis = np.concatenate((img1, img2), axis=0)

To stack horizontally (img1 to the left of img2):

vis = np.concatenate((img1, img2), axis=1)

To verify:

import cv2
import numpy as np
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)

The out.png image will contain img1 on the left and img2 on the right.

How to use jQuery to call an ASP.NET web service?

I use this method as a wrapper so that I can send parameters. Also using the variables in the top of the method allows it to be minimized at a higher ratio and allows for some code reuse if making multiple similar calls.

function InfoByDate(sDate, eDate){
    var divToBeWorkedOn = "#AjaxPlaceHolder";
    var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
    var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $(divToBeWorkedOn).html(msg.d);
        },
        error: function(e){
            $(divToBeWorkedOn).html("Unavailable");
        }
    });
}

I hope that helps.

Please note that this requires the 3.5 framework to expose JSON webmethods that can be consumed in this manner.

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Take a look at http://start.spring.io/ it basically gives you a kick starter with either maven or gradle build.

Note: This is a Spring Boot based archetype.

IntelliJ how to zoom in / out

Before User Shift + = or Shift - , you have to first set the key map as mentioned below enter image description here

How to check for an empty object in an AngularJS view

A good and effective way is to use a "json pipe" like the following in your HTML file:

   <pre>{{ yourObject | json }}</pre>

which allows you to see clearly if the object is empty or not.

I tried quite a few ways that are showed here, but none of them worked.

Python: How do I make a subclass from a superclass?

There is another way to make subclasses in python dynamically with a function type():

SubClass = type('SubClass', (BaseClass,), {'set_x': set_x})  # Methods can be set, including __init__()

You usually want to use this method when working with metaclasses. When you want to do some lower level automations, that alters way how python creates class. Most likely you will not ever need to do it in this way, but when you do, than you already will know what you are doing.

What are "res" and "req" parameters in Express functions?

Request and response.

To understand the req, try out console.log(req);.

Why is super.super.method(); not allowed in Java?

In C# you can call a method of any ancestor like this:

public class A
    internal virtual void foo()
...
public class B : A
    public new void foo()
...
public class C : B
    public new void foo() {
       (this as A).foo();
    }

Also you can do this in Delphi:

type
   A=class
      procedure foo;
      ...
   B=class(A)
     procedure foo; override;
     ...
   C=class(B)
     procedure foo; override;
     ...
A(objC).foo();

But in Java you can do such focus only by some gear. One possible way is:

class A {               
   int y=10;            

   void foo(Class X) throws Exception {  
      if(X!=A.class)
         throw new Exception("Incorrect parameter of "+this.getClass().getName()+".foo("+X.getName()+")");
      y++;
      System.out.printf("A.foo(%s): y=%d\n",X.getName(),y);
   }
   void foo() throws Exception { 
      System.out.printf("A.foo()\n");
      this.foo(this.getClass()); 
   }
}

class B extends A {     
   int y=20;            

   @Override
   void foo(Class X) throws Exception { 
      if(X==B.class) { 
         y++; 
         System.out.printf("B.foo(%s): y=%d\n",X.getName(),y);
      } else { 
         System.out.printf("B.foo(%s) calls B.super.foo(%s)\n",X.getName(),X.getName());
         super.foo(X);
      } 
   }
}

class C extends B {     
   int y=30;            

   @Override
   void foo(Class X) throws Exception { 
      if(X==C.class) { 
         y++; 
         System.out.printf("C.foo(%s): y=%d\n",X.getName(),y);
      } else { 
         System.out.printf("C.foo(%s) calls C.super.foo(%s)\n",X.getName(),X.getName());
         super.foo(X);
      } 
   }

   void DoIt() {
      try {
         System.out.printf("DoIt: foo():\n");
         foo();         
         Show();

         System.out.printf("DoIt: foo(B):\n");
         foo(B.class);  
         Show();

         System.out.printf("DoIt: foo(A):\n");
         foo(A.class);  
         Show();
      } catch(Exception e) {
         //...
      }
   }

   void Show() {
      System.out.printf("Show: A.y=%d, B.y=%d, C.y=%d\n\n", ((A)this).y, ((B)this).y, ((C)this).y);
   }
} 

objC.DoIt() result output:

DoIt: foo():
A.foo()
C.foo(C): y=31
Show: A.y=10, B.y=20, C.y=31

DoIt: foo(B):
C.foo(B) calls C.super.foo(B)
B.foo(B): y=21
Show: A.y=10, B.y=21, C.y=31

DoIt: foo(A):
C.foo(A) calls C.super.foo(A)
B.foo(A) calls B.super.foo(A)
A.foo(A): y=11
Show: A.y=11, B.y=21, C.y=31

How can I get query parameters from a URL in Vue.js?

You can get By Using this function.

console.log(this.$route.query.test)

If you can decode JWT, how are they secure?

The contents in a json web token (JWT) are not inherently secure, but there is a built-in feature for verifying token authenticity. A JWT is three hashes separated by periods. The third is the signature. In a public/private key system, the issuer signs the token signature with a private key which can only be verified by its corresponding public key.

It is important to understand the distinction between issuer and verifier. The recipient of the token is responsible for verifying it.

There are two critical steps in using JWT securely in a web application: 1) send them over an encrypted channel, and 2) verify the signature immediately upon receiving it. The asymmetric nature of public key cryptography makes JWT signature verification possible. A public key verifies a JWT was signed by its matching private key. No other combination of keys can do this verification, thus preventing impersonation attempts. Follow these two steps and we can guarantee with mathematical certainty the authenticity of a JWT.

More reading: How does a public key verify a signature?

Is it possible to set async:false to $.getJSON call

Both answers are wrong. You can. You need to call

$.ajaxSetup({
async: false
});

before your json ajax call. And you can set it to true after call retuns ( if there are other usages of ajax on page if you want them async )

Case in Select Statement

you can also use:

SELECT CASE
         WHEN upper(t.name) like 'P%' THEN
          'productive'
         WHEN upper(t.name) like 'T%' THEN
          'test'
         WHEN upper(t.name) like 'D%' THEN
          'development'
         ELSE
          'unknown'
       END as type
FROM table t

Load external css file like scripts in jquery which is compatible in ie also

I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:

$.ajax({
    url: href,
    dataType: 'text',
    success: function(data) {
        $('<style type="text/css">\n' + data + '</style>').appendTo("head");                    
    }                  
});

In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:

// Remove old style
$("head").children().each(function(index, ele) {
    if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
        $(ele).remove();
        return false;    // Stop iterating since we removed something
    }
});

Concatenate a list of pandas dataframes together

concat also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe

df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column

review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame

# Gets rows in df where IDs match in the userID column and combines them 

dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

How to write a UTF-8 file with Java?

The Java 7 Files utility type is useful for working with files:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;

public class WriteReadUtf8 {
  public static void main(String[] args) throws IOException {
    List<String> lines = Arrays.asList("These", "are", "lines");

    Path textFile = Paths.get("foo.txt");
    Files.write(textFile, lines, StandardCharsets.UTF_8);

    List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);

    System.out.println(lines.equals(read));
  }
}

The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

tl;dr

  • Use modern java.time classes.
  • Never use Date/Calendar/SimpleDateFormat classes.

Example:

ZonedDateTime                                // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now(                                        // Capture the current moment.
    ZoneId.of( "Africa/Tunis" )              // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
)
.truncatedTo(                                // Lop off finer part of this value.
    ChronoUnit.MILLIS                        // Specify level of truncation via `ChronoUnit` enum object.
)                                            // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
.format(                                     // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME    // This standard ISO 8601 format is close to your desired output.
)                                            // Returns a `String`.
.replace( "T" , " " )                        // Replace `T` in middle with a SPACE.

java.time

The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.

want current date and time

Capture the current moment in UTC using Instant.

Instant instant = Instant.now() ;

To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;

The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.

ZonedDateTime
.now( 
    ZoneId.of( "Pacific/Auckland" ) 
)
.truncatedTo(
    ChronoUnit.MILLIS
)

in “dd/MM/yyyy HH:mm:ss.SS” format

I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.

But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.

String output = 
    zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
    .replace( "T" , " " )  
;

sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");

Date date = sdf1.parse(strDate);

Never exchange date-time values using text intended for presentation to humans.

Instead, use the standard formats defined for this very purpose, found in ISO 8601.

The java.time use these ISO 8601 formats by default when parsing/generating strings.

Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.

Instant instant = zdt.toInstant() ;
String exchangeThisString = instant.toString() ;

2018-01-23T01:23:45.123456789Z

This ISO 8601 format uses a Z on the end to represent UTC, pronounced “Zulu”.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Importing from a relative path in Python

Funny enough, a same problem I just met, and I get this work in following way:

combining with linux command ln , we can make thing a lot simper:

1. cd Proj/Client
2. ln -s ../Common ./

3. cd Proj/Server
4. ln -s ../Common ./

And, now if you want to import some_stuff from file: Proj/Common/Common.py into your file: Proj/Client/Client.py, just like this:

# in Proj/Client/Client.py
from Common.Common import some_stuff

And, the same applies to Proj/Server, Also works for setup.py process, a same question discussed here, hope it helps !

Jackson with JSON: Unrecognized field, not marked as ignorable

Adding setters and getters solved the problem, what I felt is the actual issue was how to solve it but not how to suppress/ignore the error. I got the error "Unrecognized field.. not marked as ignorable.."

Though I use the below annotation on top of the class it was not able to parse the json object and give me the input

@JsonIgnoreProperties(ignoreUnknown = true)

Then I realized that I did not add setters and getters, after adding setters and getters to the "Wrapper" and to the "Student" it worked like a charm.

Get current language in CultureInfo

I tried {CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;} but it didn`t work for me, since my UI culture was different from my number/currency culture. So I suggest you to use:

CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;

This will give you the culture your UI is (texts on windows, message boxes, etc).

How to find the Number of CPU Cores via .NET/C#?

The the easyest way = Environment.ProcessorCount
Exemple from Environment.ProcessorCount Property

using System;

class Sample 
{
    public static void Main() 
    {
        Console.WriteLine("The number of processors " +
            "on this computer is {0}.", 
            Environment.ProcessorCount);
    }
}

Change a branch name in a Git repo

Assuming you're currently on the branch you want to rename:

git branch -m newname

This is documented in the manual for git-branch, which you can view using

man git-branch

or

git help branch

Specifically, the command is

git branch (-m | -M) [<oldbranch>] <newbranch>

where the parameters are:

   <oldbranch>
       The name of an existing branch to rename.

   <newbranch>
       The new name for an existing branch. The same restrictions as for <branchname> apply.

<oldbranch> is optional, if you want to rename the current branch.

In a Git repository, how to properly rename a directory?

Simply rename the folder. git is a "content-tracker", so the SHA1 hashes are the same and git knows, that you rename it. The only thing that changes is the tree-object.

rm <directory>
git add .
git commit

How do I serialize a C# anonymous type to a JSON string?

For those checking this around the year 2020:

Microsoft's System.Text.Json namespace is the new king in town. In terms of performance, it is the best as far as I can tell:

var model = new Model
{
    Name = "Test Name",
    Age = 5
};

string json = JsonSerializer.Serialize(model);

As some others have mentioned, NewtonSoft.Json is a very nice library as well.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Haskell

foldl (+) 0 [1,2,3,4,5]

Python

reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

How to declare a local variable in Razor?

I think you were pretty close, try this:

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
    <div>
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>
    </div>
}

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

Python copy files to a new directory and rename if file name already exists

Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
    for filename in files:
        # I use absolute path, case you want to move several dirs.
        old_name = os.path.join( os.path.abspath(root), filename )

        # Separate base from extension
        base, extension = os.path.splitext(filename)

        # Initial new name
        new_name = os.path.join(basedir, base, filename)

        # If folder basedir/base does not exist... You don't want to create it?
        if not os.path.exists(os.path.join(basedir, base)):
            print os.path.join(basedir,base), "not found" 
            continue    # Next filename
        elif not os.path.exists(new_name):  # folder exists, file does not
            shutil.copy(old_name, new_name)
        else:  # folder exists, file exists as well
            ii = 1
            while True:
                new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                if not os.path.exists(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1

When is it acceptable to call GC.Collect?

The best practise is to not force a garbage collection in most cases. (Every system I have worked on that had forced garbage collections, had underlining problems that if solved would have removed the need to forced the garbage collection, and speeded the system up greatly.)

There are a few cases when you know more about memory usage then the garbage collector does. This is unlikely to be true in a multi user application, or a service that is responding to more then one request at a time.

However in some batch type processing you do know more then the GC. E.g. consider an application that.

  • Is given a list of file names on the command line
  • Processes a single file then write the result out to a results file.
  • While processing the file, creates a lot of interlinked objects that can not be collected until the processing of the file have complete (e.g. a parse tree)
  • Does not keep match state between the files it has processed.

You may be able to make a case (after careful) testing that you should force a full garbage collection after you have process each file.

Another cases is a service that wakes up every few minutes to process some items, and does not keep any state while it’s asleep. Then forcing a full collection just before going to sleep may be worthwhile.

The only time I would consider forcing a collection is when I know that a lot of object had been created recently and very few objects are currently referenced.

I would rather have a garbage collection API when I could give it hints about this type of thing without having to force a GC my self.

See also "Rico Mariani's Performance Tidbits"

Notepad++ - How can I replace blank lines

This will remove any number of blank lines

CTRL + H to replace

Select Extended search mode

replace all \r\n with (space)

then switch to regular expression and replace all \s+ with \n

Attaching click to anchor tag in angular

You can use routerLink (which is an alternative of href for angular 2+) with click event as below to prevent from page reloading

<a [routerLink]="" (click)="onGoToPage2()">Go to page</a>

How to install and use "make" in Windows?

  1. Install Msys2 http://www.msys2.org
  2. Follow installation instructions
  3. Install make with $ pacman -S make gettext base-devel
  4. Add C:\msys64\usr\bin\ to your path

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

We're all working around some old bugs that haven't been fixed likely because it's "by design." I ran into the freezing problem @iwasrobbed described elsewhere when trying to nil the interactivePopGestureRecognizer's delegate which seemed like it should've worked. If you want swipe behavior reconsider using backBarButtonItem which you can customize.

I also ran into interactivePopGestureRecognizer not working when the UINavigationBar is hidden. If hiding the navigation bar is a concern for you, reconsider your design before implementing a workaround for a bug.

How do I make a delay in Java?

Use this:

public static void wait(int ms)
{
    try
    {
        Thread.sleep(ms);
    }
    catch(InterruptedException ex)
    {
        Thread.currentThread().interrupt();
    }
}

and, then you can call this method anywhere like:

wait(1000);

How do I cancel an HTTP fetch() request?

Let's polyfill:

if(!AbortController){
  class AbortController {
    constructor() {
      this.aborted = false;
      this.signal = this.signal.bind(this);
    }
    signal(abortFn, scope) {
      if (this.aborted) {
        abortFn.apply(scope, { name: 'AbortError' });
        this.aborted = false;
      } else {
        this.abortFn = abortFn.bind(scope);
      }
    }
    abort() {
      if (this.abortFn) {
        this.abortFn({ reason: 'canceled' });
        this.aborted = false;
      } else {
        this.aborted = true;
      }
    }
  }

  const originalFetch = window.fetch;

  const customFetch = (url, options) => {
    const { signal } = options || {};

    return new Promise((resolve, reject) => {
      if (signal) {
        signal(reject, this);
      }
      originalFetch(url, options)
        .then(resolve)
        .catch(reject);
    });
  };

  window.fetch = customFetch;
}

Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.

Why does Node.js' fs.readFile() return a buffer instead of string?

Async:

fs.readFile('test.txt', 'utf8', callback);

Sync:

var content = fs.readFileSync('test.txt', 'utf8');

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

How to re-index all subarray elements of a multidimensional array?

$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);

Array ( [0] => apple [1] => cherry )

//...
array_multisort($result, SORT_DESC);
//...

Array ( [0] => cherry [1] => apple )

What is the JavaScript version of sleep()?

If you right a sleep function like this

var sleep = function(period, decision, callback){
    var interval = setInterval(function(){
        if (decision()) {
            interval = clearInterval(interval);
            callback();
        }
    }, period);
}

and you have a asynchronous function to call multiple times

var xhr = function(url, callback){
    // make ajax request
    // call callback when request fulfills
}

And you setup your project like this:

var ready = false;

function xhr1(){
    xhr(url1, function(){ ready = true;});  
}
function xhr2(){
    xhr(url2, function(){ ready = true; }); 
}
function xhr3(){
    xhr(url3, function(){ ready = true; }); 
}

Then you can do this:

xhr1();
sleep(100, function(){ return done; }, xhr2);
sleep(100, function(){ return done; }, xhr3);
sleep(100, function(){ return done; }, function(){
    // do more
});

Instead of endless callback indentation like this:

xhr(url1, function(){
    xhr2(url2, function(){
        xhr3(url3, function(){
            // do more
        });
    });
});

laravel throwing MethodNotAllowedHttpException

I encountered this problem as well and the other answers here were helpful, but I am using a Route::resource which takes care of GET, POST, and other requests.

In my case I left my route as is:

Route::resource('file', 'FilesController');

And simply modified my form to submit to the store function in my FilesController

{{ Form::open(array('route' => 'file.store')) }}

This fixed the issue, and I thought it was worth pointing out as a separate answer since various other answers suggest adding a new POST route. This is an option but it's not necessary.

Disable double-tap "zoom" option in browser on touch devices

I just wanted to answer my question properly as some people do not read the comments below an answer. So here it is:

(function($) {
  $.fn.nodoubletapzoom = function() {
      $(this).bind('touchstart', function preventZoom(e) {
        var t2 = e.timeStamp
          , t1 = $(this).data('lastTouch') || t2
          , dt = t2 - t1
          , fingers = e.originalEvent.touches.length;
        $(this).data('lastTouch', t2);
        if (!dt || dt > 500 || fingers > 1) return; // not double-tap

        e.preventDefault(); // double tap - prevent the zoom
        // also synthesize click events we just swallowed up
        $(this).trigger('click').trigger('click');
      });
  };
})(jQuery);

I did not write this, i just modified it. I found the iOS-only version here: https://gist.github.com/2047491 (thanks Kablam)

SSRS Query execution failed for dataset

BIGHAP: A SIMPLE WORK AROUND FOR THIS ISSUE.

I ran into the same problem when working with SharePoint lists as the DataSource, and read the blogs above which were very helpful. I had made changes in both the DataSource and Data object names and query fields in Visual Studio and the query worked in visual Studio. I was able to deploy the report to SharePoint but when I tried to open it I received the same error.

I guessed that the issue was that I needed to redeploy both the DataSource and the DataSet to SharePoint so that that changes in the rendering tools were all synced.

I redeployed the DataSource, DataSet and the Report to sharePoint and it worked. As one of the blogs stated, although visual studio allowed the changes I made in the dataset and datasource, if you have not set visual studio to automatically redeploy datasource and dataset when you deploy the report(which can be dangerous, because this can affect other reports which share these objects) this error can occur.

So, of course the fix is that in this case you have to redeploy datasource, dataset and Report to resolve the issue.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

If using win7 64 bit OS:

After installing the latest JDK make sure you copy the jre folder from the install location {C:\Program Files\Java\jdk1.7.0_40} directly to your eclipse folder as even pathing it apparently does nothing on win7.

Mad

edit:

Actual jdk version number on folder name will vary as newer versions are released

how to rename an index in a cluster?

If you can't REINDEX a workaround is to use aliases. From the official documentation:

APIs in elasticsearch accept an index name when working against a specific index, and several indices when applicable. The index aliases API allow to alias an index with a name, with all APIs automatically converting the alias name to the actual index name. An alias can also be mapped to more than one index, and when specifying it, the alias will automatically expand to the aliases indices. An alias can also be associated with a filter that will automatically be applied when searching, and routing values. An alias cannot have the same name as an index.

Be aware that this solution does not work if you're using More Like This feature. https://github.com/elastic/elasticsearch/issues/16560

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

python - checking odd/even numbers and changing outputs on number size

Giving you the complete answer would have no point at all since this is homework, so here are a few pointers :

Even or Odd:

number % 2 == 0

definitely is a very good way to find whether your number is even.

In case you do not know %, this does modulo which is here the remainder of the division of number by 2. http://en.wikipedia.org/wiki/Modulo_operation

Printing the pyramid:

First advice: In order to print *****, you can do print "*" * 5.

Second advice: In order to center the asterisks, you need to find out how many spaces to write before the asterisks. Then you can print a bunch of spaces and asterisks with print " "*1 + "*"*3

How do I change db schema to dbo

I just posted this to a similar question: In sql server 2005, how do I change the "schema" of a table without losing any data?


A slight improvement to sAeid's excellent answer...

I added an exec to have this code self-execute, and I added a union at the top so that I could change the schema of both tables AND stored procedures:

DECLARE cursore CURSOR FOR 


select specific_schema as 'schema', specific_name AS 'name'
FROM INFORMATION_SCHEMA.routines
WHERE specific_schema <> 'dbo' 

UNION ALL

SELECT TABLE_SCHEMA AS 'schema', TABLE_NAME AS 'name'
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA <> 'dbo' 



DECLARE @schema sysname, 
 @tab sysname, 
 @sql varchar(500) 


OPEN cursore     
FETCH NEXT FROM cursore INTO @schema, @tab 

WHILE @@FETCH_STATUS = 0     
BEGIN 
 SET @sql = 'ALTER SCHEMA dbo TRANSFER [' + @schema + '].[' + @tab +']'    
 PRINT @sql   
 exec (@sql)  
 FETCH NEXT FROM cursore INTO @schema, @tab     
END 

CLOSE cursore     
DEALLOCATE cursore

I too had to restore a dbdump, and found that the schema wasn't dbo - I spent hours trying to get Sql Server management studio or visual studio data transfers to alter the destination schema... I ended up just running this against the restored dump on the new server to get things the way I wanted.

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

How to clear the interpreter console?

I am using Spyder (Python 2.7) and to clean the interpreter console I use either

%clear

that forces the command line to go to the top and I will not see the previous old commands.

or I click "option" on the Console environment and select "Restart kernel" that removes everything.

Why use multiple columns as primary keys (composite primary key)

Your second question

How many columns can be used together as a primary key in a given table?

is implementation specific: it's defined in the actual DBMS being used.[1],[2],[3] You have to inspect the technical specification of the database system you use. Some are very detailed, some are not. Searching the web about such limitations can be hard because the terminology varies. The term composite primary key should be mandatory ;)

If you cannot find explicit information, try creating a test database to ensure you can expect stable (and specific) handling of the limit violations (which are to be expected). Be careful to get the right information about this: sometimes the limits are accumulated, and you'll see different results with different database layouts.


Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

Convert string to hex-string in C#

First you'll need to get it into a byte[], so do this:

byte[] ba = Encoding.Default.GetBytes("sample");

and then you can get the string:

var hexString = BitConverter.ToString(ba);

now, that's going to return a string with dashes (-) in it so you can then simply use this:

hexString = hexString.Replace("-", "");

to get rid of those if you want.

NOTE: you could use a different Encoding if you needed to.

How to coerce a list object to type 'double'

You can also use list subsetting to select the element you want to convert. It would be useful if your list had more than 1 element.

as.numeric(a[[1]])

How to obtain image size using standard Python class (without using external library)?

While it's possible to call open(filename, 'rb') and check through the binary image headers for the dimensions, it seems much more useful to install PIL and spend your time writing great new software! You gain greater file format support and the reliability that comes from widespread usage. From the PIL documentation, it appears that the code you would need to complete your task would be:

from PIL import Image
im = Image.open('filename.png')
print 'width: %d - height: %d' % im.size # returns (width, height) tuple

As for writing code yourself, I'm not aware of a module in the Python standard library that will do what you want. You'll have to open() the image in binary mode and start decoding it yourself. You can read about the formats at:

XML Schema How to Restrict Attribute by Enumeration

<xs:element name="price" type="decimal">
<xs:attribute name="currency" type="xs:string" value="(euros|pounds|dollars)" /> 
</element> 

This would eliminate the need for enumeration completely. You could change type to double if required.

How to pass a textbox value from view to a controller in MVC 4?

your link is generated when the page loads therefore it will always have the original value in it. You will need to set the link via javascript

You could also just wrap that in a form and have hidden fields for id, productid, and unitrate

Here's a sample for ya.

HTML

<input type="text" id="ss" value="1"/>
<br/>
<input type="submit" id="go" onClick="changeUrl()"/>
<br/>
<a id="imgUpdate"  href="/someurl?quantity=1">click me</a>

JS

function changeUrl(){
   var url = document.getElementById("imgUpdate").getAttribute('href');
   var inputValue = document.getElementById('ss').value;
   var currentQ = GiveMeTheQueryStringParameterValue("quantity",url);
    url = url.replace("quantity=" + currentQ, "quantity=" + inputValue);
document.getElementById("imgUpdate").setAttribute('href',url)
}

    function GiveMeTheQueryStringParameterValue(parameterName, input) {
    parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + parameterName + "=([^&#]*)");
    var results = regex.exec(input);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

this could be cleaned up and expanded as you need it but the example works

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

Get Base64 encode file-data from Input Form

I used FileReader to display image on click of the file upload button not using any Ajax requests. Following is the code hope it might help some one.

$(document).ready(function($) {
    $.extend( true, jQuery.fn, {        
        imagePreview: function( options ){          
            var defaults = {};
            if( options ){
                $.extend( true, defaults, options );
            }
            $.each( this, function(){
                var $this = $( this );              
                $this.bind( 'change', function( evt ){

                    var files = evt.target.files; // FileList object
                    // Loop through the FileList and render image files as thumbnails.
                    for (var i = 0, f; f = files[i]; i++) {
                        // Only process image files.
                        if (!f.type.match('image.*')) {
                        continue;
                        }
                        var reader = new FileReader();
                        // Closure to capture the file information.
                        reader.onload = (function(theFile) {
                            return function(e) {
                                // Render thumbnail.
                                    $('#imageURL').attr('src',e.target.result);                         
                            };
                        })(f);
                        // Read in the image file as a data URL.
                        reader.readAsDataURL(f);
                    }

                });
            });
        }   
    });
    $( '#fileinput' ).imagePreview();
});

T-SQL split string based on delimiter

Try filtering out the rows that contain strings with the delimiter and work on those only like:

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE CHARINDEX('/', myColumn) > 0

Or

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE myColumn LIKE '%/%'

How to get current screen width in CSS?

Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.

Please refer to the below example. I'm here showing only one component.

login.component.html

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {

      cssProperty:any;
      constructor(private sanitizer: DomSanitizer) { 
        console.log(window.innerWidth);
        console.log(window.innerHeight);
        this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
        this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
      }

    ngOnInit() {

      }

    }

login.component.ts

<div class="home">
    <div class="container" [style]="cssProperty">
        <div class="card">
            <div class="card-header">Login</div>
            <div class="card-body">Please login</div>
            <div class="card-footer">Login</div>
        </div>
    </div>
</div>

login.component.css

.card {
    max-width: 400px;
}
.card .card-body {
    min-height: 150px;
}
.home {
    background-color: rgba(171, 172, 173, 0.575);
}

How to change maven java home

I have two Java versions on my Ubuntu server 14.04: java 1.7 and java 1.8.

I have a project that I need to build using java 1.8.

If I check my Java version using java -version

I get

java version "1.8.0_144"

But when I did mvn -version I get:

Java version: 1.7.0_79, vendor: Oracle Corporation

To set the mvn version to java8

I do this:

export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre/

Then when I do mvn -version I get:

Java version: 1.8.0_144, vendor: Oracle Corporation

kubectl apply vs kubectl create?

The explanation below from the official documentation helped me understand kubectl apply.

This command will compare the version of the configuration that you’re pushing with the previous version and apply the changes you’ve made, without overwriting any automated changes to properties you haven’t specified.

kubectl create on the other hand will create (should be non-existing) resources.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

I fixed this by making sure that that OpenSSL was installed on my machine and then adding this to my php.ini:

openssl.cafile=/usr/local/etc/openssl/cert.pem

What are the differences between a superkey and a candidate key?

Basically, a Candidate Key is a Super Key from which no more Attribute can be pruned.

A Super Key identifies uniquely rows/tuples in a table/relation of a database. It is composed by a set of attributes that combined can assume values unique over the rows/tuples of a table/relation. A Candidate Key is built by a Super Key, iteratively removing/pruning non-key attributes, keeping an invariant: the newly created Key still need to uniquely identifies the rows/tuples.

A Candidate Key might be seen as a minimal Super Key, in terms of attributes.

Candidate Keys can be used to reference uniquely rows/tuples but from the RDBMS engine perspective the burden to maintain indexes on them is far heavier.

How to remove the underline for anchors(links)?

<u>

is a deprecated tag.

Use...

<span class="underline">My text</span>

with a CSS file containing...

span.underline
{
    text-decoration: underline;
}  

or just...

<span style="text-decoration:underline">My Text</span>

Getting All Variables In Scope

As everyone noticed: you can't. But you can create a obj and assign every var you declare to that obj. That way you can easily check out your vars:

var v = {}; //put everything here

var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x;  //so on...

console.log(v); //it's all there

What is a clearfix?

If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.

It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.

  • display: inline-block - Better
  • Flexbox - Best (but limited browser support)

Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.

For a detailed browser list see: https://caniuse.com/flexbox.

(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)


A clearfix is a way for an element to automatically clear its child elements, so that you don't need to add additional markup. It's generally used in float layouts where elements are floated to be stacked horizontally.

The clearfix is a way to combat the zero-height container problem for floated elements

A clearfix is performed as follows:

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Or, if you don't require IE<8 support, the following is fine too:

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

Normally you would need to do something as follows:

<div>
    <div style="float: left;">Sidebar</div>
    <div style="clear: both;"></div> <!-- Clear the float -->
</div>

With clearfix, you only need the following:

<div class="clearfix">
    <div style="float: left;" class="clearfix">Sidebar</div>
    <!-- No Clearing div! -->
</div>

Read about it in this article - by Chris Coyer @ CSS-Tricks

CFNetwork SSLHandshake failed iOS 9

Another useful tool is nmap (brew install nmap)

nmap --script ssl-enum-ciphers -p 443 google.com

Gives output

Starting Nmap 7.12 ( https://nmap.org ) at 2016-08-11 17:25 IDT
Nmap scan report for google.com (172.217.23.46)
Host is up (0.061s latency).
Other addresses for google.com (not scanned): 2a00:1450:4009:80a::200e
PORT    STATE SERVICE
443/tcp open  https
| ssl-enum-ciphers: 
|   TLSv1.0: 
|     ciphers: 
|       TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
|     compressors: 
|       NULL
|     cipher preference: server
|   TLSv1.1: 
|     ciphers: 
|       TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
|     compressors: 
|       NULL
|     cipher preference: server
|   TLSv1.2: 
|     ciphers: 
|       TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|       TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (secp256r1) - A
|       TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
|       TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_AES_128_CBC_SHA256 (rsa 2048) - A
|       TLS_RSA_WITH_AES_128_GCM_SHA256 (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_CBC_SHA256 (rsa 2048) - A
|       TLS_RSA_WITH_AES_256_GCM_SHA384 (rsa 2048) - A
|     compressors: 
|       NULL
|     cipher preference: client
|_  least strength: C

Nmap done: 1 IP address (1 host up) scanned in 5.48 seconds

How do you strip a character out of a column in SQL Server?

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')

In your instance it would be

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')

Because there is no replacement (you want to get rid of it).

This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.

Input type=password, don't let browser remember the password

I've found the following works on Firefox and Chrome.

<form ... > <!-- more stuff -->
<input name="person" type="text" size=30 value="">
<input name="mypswd" type="password" size=6 value="" autocomplete="off">
<input name="userid" type="text" value="security" style="display:none">
<input name="passwd" type="password" value="faker" style="display:none">
<!-- more stuff --> </form>

All of these are within the forms section. "person" and "mypswd" are what you want, but the browser will save "userid" and "passwd" once, and never again since they don't change. You could eliminate the "person" field if you don't really need it. In that case, all you want is the "mypswd" field, which could change in some way known to the user of your web-page.

Adding a custom header to HTTP request using angular.js

And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.

In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.

The way you are adding headers is the right way to do it.

What's the difference between JavaScript and Java?

Take a look at the Wikipedia link

JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language was originally named "LiveScript" but was renamed in a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the Self and Scheme programming languages.

How to trigger a phone call when clicking a link in a web page on mobile phone

Most modern devices support the tel: scheme. So use <a href="tel:555-555-5555">555-555-5555</a> and you should be good to go.

If you want to use it for an image, the <a> tag can handle the <img/> placed in it just like other normal situations with : <a href="tel:555-555-5555"><img src="path/to/phone/icon.jpg" /></a>

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

Splitting comma separated string in a PL/SQL stored proc

Many good solutions have been provided already. However, if he text is provided in a very simple comma delimited format or similar, and speed is of importance, then I have for you a solution with a TABLE function (in PL/SQL). I have also provided a rundown of some other solutions.

Please see more on the Blog Entry on Parsing a CSV into multiple columns.

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

SQL update fields of one table from fields of another one

I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.

It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:

UPDATE B SET
     COLUMN1 = A.COLUMN1,
     COLUMN2 = A.COLUMN2,
     COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID

Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.

It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:

UPDATE B SET
    (COLUMN1, COLUMN2, COLUMN3) =
               (SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)

FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:

UPDATE B SET
     COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
     COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
     COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)

php foreach with multidimensional array

If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.

In this usage, I have this array with each element needing an appended comma and newline.

$some_array = [];

data in $some_array
0: "Some string in an array"
1: "Another string in an array"

Per php.net

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

array_walk_recursive($some_array, function (&$value, $key) {
    $value .= ",\n";
});

Result:
"Some string in an array,\n"
"Another string in an array,\n"

Here's the same concept using array_walk to prepend the database table name to the field.

$fields = [];

data in $fields:
0: "FirstName"
1: "LastName"

$tbl = "Employees"

array_walk($fields, 'prefixOnArray', $tbl.".");

function prefixOnArray(&$value, $key, $prefix) { 
    $value = $prefix.$value; 
}

Result:
"Employees.FirstName"
"Employees.LastName"


I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.

How to make a new List in Java

Using Eclipse Collections you can create a List like this:

List<String> list1 = Lists.mutable.empty();
List<String> list2 = Lists.mutable.of("One", "Two", "Three");

If you want an immutable list:

ImmutableList<String> list3 = Lists.immutable.empty();
ImmutableList<String> list4 = Lists.immutable.of("One", "Two", "Three");

You can avoid auto-boxing by using primitive lists. Here's how you'd create int lists:

MutableIntList list5 = IntLists.mutable.empty();
MutableIntList list6 = IntLists.mutable.of(1, 2, 3);

ImmutableIntList list7 = IntLists.immutable.empty();
ImmutableIntList list8 = IntLists.immutable.of(1, 2, 3);

There are variants for all 8 primitives.

MutableLongList longList       = LongLists.mutable.of(1L, 2L, 3L);
MutableCharList charList       = CharLists.mutable.of('a', 'b', 'c');
MutableShortList shortList     = ShortLists.mutable.of((short) 1, (short) 2, (short) 3);
MutableByteList byteList       = ByteLists.mutable.of((byte) 1, (byte) 2, (byte) 3);
MutableBooleanList booleanList = BooleanLists.mutable.of(true, false);
MutableFloatList floatList     = FloatLists.mutable.of(1.0f, 2.0f, 3.0f);
MutableDoubleList doubleList   = DoubleLists.mutable.of(1.0, 2.0, 3.0);

Note: I am a committer for Eclipse Collections.

How to run cron once, daily at 10pm

To run once, daily at 10PM you should do something like this:

0 22 * * *

enter image description here

Full size image: http://i.stack.imgur.com/BeXHD.jpg

Source: softpanorama.org

Quickly reading very large tables as dataframes

I didn't see this question initially and asked a similar question a few days later. I am going to take my previous question down, but I thought I'd add an answer here to explain how I used sqldf() to do this.

There's been little bit of discussion as to the best way to import 2GB or more of text data into an R data frame. Yesterday I wrote a blog post about using sqldf() to import the data into SQLite as a staging area, and then sucking it from SQLite into R. This works really well for me. I was able to pull in 2GB (3 columns, 40mm rows) of data in < 5 minutes. By contrast, the read.csv command ran all night and never completed.

Here's my test code:

Set up the test data:

bigdf <- data.frame(dim=sample(letters, replace=T, 4e7), fact1=rnorm(4e7), fact2=rnorm(4e7, 20, 50))
write.csv(bigdf, 'bigdf.csv', quote = F)

I restarted R before running the following import routine:

library(sqldf)
f <- file("bigdf.csv")
system.time(bigdf <- sqldf("select * from f", dbname = tempfile(), file.format = list(header = T, row.names = F)))

I let the following line run all night but it never completed:

system.time(big.df <- read.csv('bigdf.csv'))

How to determine whether a year is a leap year?

Your function doesn't return anything, so that's why when you use it with the print statement you get None. So either just call your function like this:

leapyr(1900)

or modify your function to return a value (by using the return statement), which then would be printed by your print statement.

Note: This does not address any possible problems you have with your leap year computation, but ANSWERS YOUR SPECIFIC QUESTION as to why you are getting None as a result of your function call in conjunction with your print.

Explanation:

Some short examples regarding the above:

def add2(n1, n2):
    print 'the result is:', n1 + n2  # prints but uses no *return* statement

def add2_New(n1, n2):
    return n1 + n2    # returns the result to caller

Now when I call them:

print add2(10, 5)

this gives:

the result is: 15
None

The first line comes form the print statement inside of add2(). The None from the print statement when I call the function add2() which does not have a return statement, causing the None to be printed. Incidentally, if I had just called the add2() function simply with (note, no print statement):

add2()

I would have just gotten the output of the print statement the result is: 15 without the None (which looks like what you are trying to do).

Compare this with:

print add2_New(10, 5)

which gives:

15

In this case the result is computed in the function add2_New() and no print statement, and returned to the caller who then prints it in turn.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I know this is an old question, but I had the same problem and solved it thanks to this answer.

I use Putty regularly and have never had any problems. I use and have always used public key authentication. Today I could not connect again to my server, without changing any settings.

Then I saw the answer and remembered that I inadvertently ran chmod 777 . in my user's home directory. I connected from somewhere else and simply ran chmod 755 ~. Everything was back to normal instantly, I didn't even have to restart sshd.

I hope I saved some time from someone

Script parameters in Bash

I needed to make sure that my scripts are entirely portable between various machines, shells and even cygwin versions. Further, my colleagues who were the ones I had to write the scripts for, are programmers, so I ended up using this:

for ((i=1;i<=$#;i++)); 
do

    if [ ${!i} = "-s" ] 
    then ((i++)) 
        var1=${!i};

    elif [ ${!i} = "-log" ];
    then ((i++)) 
        logFile=${!i};  

    elif [ ${!i} = "-x" ];
    then ((i++)) 
        var2=${!i};    

    elif [ ${!i} = "-p" ]; 
    then ((i++)) 
        var3=${!i};

    elif [ ${!i} = "-b" ];
    then ((i++)) 
        var4=${!i};

    elif [ ${!i} = "-l" ];
    then ((i++)) 
        var5=${!i}; 

    elif [ ${!i} = "-a" ];
    then ((i++)) 
        var6=${!i};
    fi

done;

Rationale: I included a launcher.sh script as well, since the whole operation had several steps which were quasi independent on each other (I'm saying "quasi", because even though each script could be run on its own, they were usually all run together), and in two days I found out, that about half of my colleagues, being programmers and all, were too good to be using the launcher file, follow the "usage", or read the HELP which was displayed every time they did something wrong and they were making a mess of the whole thing, running scripts with arguments in the wrong order and complaining that the scripts didn't work properly. Being the choleric I am I decided to overhaul all my scripts to make sure that they are colleague-proof. The code segment above was the first thing.

how to get selected row value in the KendoUI

If you want to select particular element use below code

var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void) is better because it explicitly says: no parameters allowed.

void foo() means you could (under some compilers) send parameters, at least if this is the declaration of your function rather than its definition.

How to call a web service from jQuery

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

Django database query: How to get object by id?

You can also do:

obj = ClassModel.get_by_id(object_id)

This works, but there may I'm not sure if it's supported in Django 2.

Pass an array of integers to ASP.NET Web API?

I addressed this issue this way.

I used a post message to the api to send the list of integers as data.

Then I returned the data as an ienumerable.

The sending code is as follows:

public override IEnumerable<Contact> Fill(IEnumerable<int> ids)
{
    IEnumerable<Contact> result = null;
    if (ids!=null&&ids.Count()>0)
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:49520/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                String _endPoint = "api/" + typeof(Contact).Name + "/ListArray";

                HttpResponseMessage response = client.PostAsJsonAsync<IEnumerable<int>>(_endPoint, ids).Result;
                response.EnsureSuccessStatusCode();
                if (response.IsSuccessStatusCode)
                {
                    result = JsonConvert.DeserializeObject<IEnumerable<Contact>>(response.Content.ReadAsStringAsync().Result);
                }

            }

        }
        catch (Exception)
        {

        }
    }
    return result;
}

The receiving code is as follows:

// POST api/<controller>
[HttpPost]
[ActionName("ListArray")]
public IEnumerable<Contact> Post([FromBody]IEnumerable<int> ids)
{
    IEnumerable<Contact> result = null;
    if (ids != null && ids.Count() > 0)
    {
        return contactRepository.Fill(ids);
    }
    return result;
}

It works just fine for one record or many records. The fill is an overloaded method using DapperExtensions:

public override IEnumerable<Contact> Fill(IEnumerable<int> ids)
{
    IEnumerable<Contact> result = null;
    if (ids != null && ids.Count() > 0)
    {
        using (IDbConnection dbConnection = ConnectionProvider.OpenConnection())
        {
            dbConnection.Open();
            var predicate = Predicates.Field<Contact>(f => f.id, Operator.Eq, ids);
            result = dbConnection.GetList<Contact>(predicate);
            dbConnection.Close();
        }
    }
    return result;
}

This allows you to fetch data from a composite table (the id list), and then return the records you are really interested in from the target table.

You could do the same with a view, but this gives you a little more control and flexibility.

In addition, the details of what you are seeking from the database are not shown in the query string. You also do not have to convert from a csv file.

You have to keep in mind when using any tool like the web api 2.x interface is that the get, put, post, delete, head, etc., functions have a general use, but are not restricted to that use.

So, while post is generally used in a create context in the web api interface, it is not restricted to that use. It is a regular html call that can be used for any purpose permitted by html practice.

In addition, the details of what is going on are hidden from those "prying eyes" we hear so much about these days.

The flexibility in naming conventions in the web api 2.x interface and use of regular web calling means you send a call to the web api that misleads snoopers into thinking you are really doing something else. You can use "POST" to really retrieve data, for example.

How can I use "e" (Euler's number) and power operation in python 2.7

math.e or from math import e (= 2.718281…)

The two expressions math.exp(x) and e**x are equivalent however:
Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x). docs.python

for power use ** (3**2 = 9), not " ^ "
" ^ " is a bitwise XOR operator (& and, | or), it works logicaly with bits. So for example 10^4=14 (maybe unexpectedly) ? consider the bitwise depiction:

(0000 1010 ^ 0000 0100 = 0000 1110) programiz

Reading a resource file from within jar

In my case I finally made it with

import java.lang.Thread;
import java.io.BufferedReader;
import java.io.InputStreamReader;

final BufferedReader in = new BufferedReader(new InputStreamReader(
      Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt"))
); // no initial slash in file.txt

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

Getting a link to go to a specific section on another page

To link from a page to another section just use

<a href="index.php#firstdiv">my first div</a>

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

In my xml file, the header looked like this:

<?xml version="1.0" encoding="utf-16"? />

In a test file, I was reading the file bytes and decoding the data as UTF-8 (not realizing the header in this file was utf-16) to create a string.

byte[] data = Files.readAllBytes(Paths.get(path));
String dataString = new String(data, "UTF-8");

When I tried to deserialize this string into an object, I was seeing the same error:

javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.

When I updated the second line to

String dataString = new String(data, "UTF-16");

I was able to deserialize the object just fine. So as Romain had noted above, the encodings need to match.

Rename a dictionary key

You can use this OrderedDict recipe written by Raymond Hettinger and modify it to add a rename method, but this is going to be a O(N) in complexity:

def rename(self,key,new_key):
    ind = self._keys.index(key)  #get the index of old key, O(N) operation
    self._keys[ind] = new_key    #replace old key with new key in self._keys
    self[new_key] = self[key]    #add the new key, this is added at the end of self._keys
    self._keys.pop(-1)           #pop the last item in self._keys

Example:

dic = OrderedDict((("a",1),("b",2),("c",3)))
print dic
dic.rename("a","foo")
dic.rename("b","bar")
dic["d"] = 5
dic.rename("d","spam")
for k,v in  dic.items():
    print k,v

output:

OrderedDict({'a': 1, 'b': 2, 'c': 3})
foo 1
bar 2
c 3
spam 5

How to disable an input type=text?

If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly attribute (or disabled, if you want to remove it from the form submission as well) to the <input>, like this:

<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />

How do I monitor the computer's CPU, memory, and disk usage in Java?

Have a look at this very detailled article: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime

To get the percentage of CPU used, all you need is some simple maths:

MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();

OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);

long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();

// Call an expensive task, or sleep if you are monitoring a remote process

long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();

long percent;
if (nanoAfter > nanoBefore)
 percent = ((cpuAfter-cpuBefore)*100L)/
   (nanoAfter-nanoBefore);
else percent = 0;

System.out.println("Cpu usage: "+percent+"%");

Note: You must import com.sun.management.OperatingSystemMXBean and not java.lang.management.OperatingSystemMXBean.

Ruby, remove last N characters from a string?

irb> 'now is the time'[0...-4]
=> "now is the "

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

How to destroy a JavaScript object?

While the existing answers have given solutions to solve the issue and the second half of the question, they do not provide an answer to the self discovery aspect of the first half of the question that is in bold:

"How can I see which variable causes memory overhead...?"

It may not have been as robust 3 years ago, but the Chrome Developer Tools "Profiles" section is now quite powerful and feature rich. The Chrome team has an insightful article on using it and thus also how garbage collection (GC) works in javascript, which is at the core of this question.

Since delete is basically the root of the currently accepted answer by Yochai Akoka, it's important to remember what delete does. It's irrelevant if not combined with the concepts of how GC works in the next two answers: if there's an existing reference to an object it's not cleaned up. The answers are more correct, but probably not as appreciated because they require more thought than just writing 'delete'. Yes, one possible solution may be to use delete, but it won't matter if there's another reference to the memory leak.

Another answer appropriately mentions circular references and the Chrome team documentation can provide much more clarity as well as the tools to verify the cause.

Since delete was mentioned here, it also may be useful to provide the resource Understanding Delete. Although it does not get into any of the actual solution which is really related to javascript's garbage collector.

Switch/toggle div (jQuery)

I think you want this:

$('#recover-password').show();

or

$('#recover-password').toggle();

This is made possible by jQuery.

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

How to count number of unique values of a field in a tab-delimited text file?

# COLUMN is integer column number
# INPUT_FILE is input file name

cut -f ${COLUMN} < ${INPUT_FILE} | sort -u | wc -l

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]

Convert HashBytes to VarChar

Contrary to what David Knight says, these two alternatives return the same response in MS SQL 2008:

SELECT CONVERT(VARCHAR(32),HashBytes('MD5', 'Hello World'),2)
SELECT UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('MD5', 'Hello World'), 1, 0))

So it looks like the first one is a better choice, starting from version 2008.

How to get the URL of the current page in C#

I guess its enough to return absolute path..

 Path.GetFileName( Request.Url.AbsolutePath )

using System.IO;

What exactly does += do in python?

In Python, += is sugar coating for the __iadd__ special method, or __add__ or __radd__ if __iadd__ isn't present. The __iadd__ method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's extend method does.

Here's a simple custom class that implements the __iadd__ special method. You initialize the object with an int, then can use the += operator to add a number. I've added a print statement in __iadd__ to show that it gets called. Also, __iadd__ is expected to return an object, so I returned the addition of itself plus the other number which makes sense in this case.

>>> class Adder(object):
        def __init__(self, num=0):
            self.num = num

        def __iadd__(self, other):
            print 'in __iadd__', other
            self.num = self.num + other
            return self.num

>>> a = Adder(2)
>>> a += 3
in __iadd__ 3
>>> a
5

Hope this helps.

Programmatically read from STDIN or input file in Perl

if(my $file = shift) { # if file is specified, read from that
  open(my $fh, '<', $file) or die($!);
  while(my $line = <$fh>) {
    print $line;
  }
}
else { # otherwise, read from STDIN
  print while(<>);
}

Ternary operation in CoffeeScript

a = if true then 5 else 10
a = if false then 5 else 10 

See documentation.

Count table rows

We have another way to find out the number of rows in a table without running a select query on that table.

Every MySQL instance has information_schema database. If you run the following query, it will give complete details about the table including the approximate number of rows in that table.

select * from information_schema.TABLES where table_name = 'table_name'\G

How to write std::string to file?

You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.

If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.

The following example reads one string from stdin, and then writes this string to the file output.txt.

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.

For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/

Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:

write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

Update multiple rows using select statement

None of above answers worked for me in MySQL, the following query worked though:

UPDATE
    Table1 t1
    JOIN
    Table2 t2 ON t1.ID=t2.ID 
SET
    t1.value =t2.value
WHERE
    ...

How to "perfectly" override a dict?

My requirements were a bit stricter:

  • I had to retain case info (the strings are paths to files displayed to the user, but it's a windows app so internally all operations must be case insensitive)
  • I needed keys to be as small as possible (it did make a difference in memory performance, chopped off 110 mb out of 370). This meant that caching lowercase version of keys is not an option.
  • I needed creation of the data structures to be as fast as possible (again made a difference in performance, speed this time). I had to go with a builtin

My initial thought was to substitute our clunky Path class for a case insensitive unicode subclass - but:

  • proved hard to get that right - see: A case insensitive string class in python
  • turns out that explicit dict keys handling makes code verbose and messy - and error prone (structures are passed hither and thither, and it is not clear if they have CIStr instances as keys/elements, easy to forget plus some_dict[CIstr(path)] is ugly)

So I had finally to write down that case insensitive dict. Thanks to code by @AaronHall that was made 10 times easier.

class CIstr(unicode):
    """See https://stackoverflow.com/a/43122305/281545, especially for inlines"""
    __slots__ = () # does make a difference in memory performance

    #--Hash/Compare
    def __hash__(self):
        return hash(self.lower())
    def __eq__(self, other):
        if isinstance(other, CIstr):
            return self.lower() == other.lower()
        return NotImplemented
    def __ne__(self, other):
        if isinstance(other, CIstr):
            return self.lower() != other.lower()
        return NotImplemented
    def __lt__(self, other):
        if isinstance(other, CIstr):
            return self.lower() < other.lower()
        return NotImplemented
    def __ge__(self, other):
        if isinstance(other, CIstr):
            return self.lower() >= other.lower()
        return NotImplemented
    def __gt__(self, other):
        if isinstance(other, CIstr):
            return self.lower() > other.lower()
        return NotImplemented
    def __le__(self, other):
        if isinstance(other, CIstr):
            return self.lower() <= other.lower()
        return NotImplemented
    #--repr
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__,
                                 super(CIstr, self).__repr__())

def _ci_str(maybe_str):
    """dict keys can be any hashable object - only call CIstr if str"""
    return CIstr(maybe_str) if isinstance(maybe_str, basestring) else maybe_str

class LowerDict(dict):
    """Dictionary that transforms its keys to CIstr instances.
    Adapted from: https://stackoverflow.com/a/39375731/281545
    """
    __slots__ = () # no __dict__ - that would be redundant

    @staticmethod # because this doesn't make sense as a global function.
    def _process_args(mapping=(), **kwargs):
        if hasattr(mapping, 'iteritems'):
            mapping = getattr(mapping, 'iteritems')()
        return ((_ci_str(k), v) for k, v in
                chain(mapping, getattr(kwargs, 'iteritems')()))
    def __init__(self, mapping=(), **kwargs):
        # dicts take a mapping or iterable as their optional first argument
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
    def __getitem__(self, k):
        return super(LowerDict, self).__getitem__(_ci_str(k))
    def __setitem__(self, k, v):
        return super(LowerDict, self).__setitem__(_ci_str(k), v)
    def __delitem__(self, k):
        return super(LowerDict, self).__delitem__(_ci_str(k))
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
        return type(self)(self)
    def get(self, k, default=None):
        return super(LowerDict, self).get(_ci_str(k), default)
    def setdefault(self, k, default=None):
        return super(LowerDict, self).setdefault(_ci_str(k), default)
    __no_default = object()
    def pop(self, k, v=__no_default):
        if v is LowerDict.__no_default:
            # super will raise KeyError if no default and key does not exist
            return super(LowerDict, self).pop(_ci_str(k))
        return super(LowerDict, self).pop(_ci_str(k), v)
    def update(self, mapping=(), **kwargs):
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
    def __contains__(self, k):
        return super(LowerDict, self).__contains__(_ci_str(k))
    @classmethod
    def fromkeys(cls, keys, v=None):
        return super(LowerDict, cls).fromkeys((_ci_str(k) for k in keys), v)
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__,
                                 super(LowerDict, self).__repr__())

Implicit vs explicit is still a problem, but once dust settles, renaming of attributes/variables to start with ci (and a big fat doc comment explaining that ci stands for case insensitive) I think is a perfect solution - as readers of the code must be fully aware that we are dealing with case insensitive underlying data structures. This will hopefully fix some hard to reproduce bugs, which I suspect boil down to case sensitivity.

Comments/corrections welcome :)

What is the strict aliasing rule?

According to the C89 rationale, the authors of the Standard did not want to require that compilers given code like:

int x;
int test(double *p)
{
  x=5;
  *p = 1.0;
  return x;
}

should be required to reload the value of x between the assignment and return statement so as to allow for the possibility that p might point to x, and the assignment to *p might consequently alter the value of x. The notion that a compiler should be entitled to presume that there won't be aliasing in situations like the above was non-controversial.

Unfortunately, the authors of the C89 wrote their rule in a way that, if read literally, would make even the following function invoke Undefined Behavior:

void test(void)
{
  struct S {int x;} s;
  s.x = 1;
}

because it uses an lvalue of type int to access an object of type struct S, and int is not among the types that may be used accessing a struct S. Because it would be absurd to treat all use of non-character-type members of structs and unions as Undefined Behavior, almost everyone recognizes that there are at least some circumstances where an lvalue of one type may be used to access an object of another type. Unfortunately, the C Standards Committee has failed to define what those circumstances are.

Much of the problem is a result of Defect Report #028, which asked about the behavior of a program like:

int test(int *ip, double *dp)
{
  *ip = 1;
  *dp = 1.23;
  return *ip;
}
int test2(void)
{
  union U { int i; double d; } u;
  return test(&u.i, &u.d);
}

Defect Report #28 states that the program invokes Undefined Behavior because the action of writing a union member of type "double" and reading one of type "int" invokes Implementation-Defined behavior. Such reasoning is nonsensical, but forms the basis for the Effective Type rules which needlessly complicate the language while doing nothing to address the original problem.

The best way to resolve the original problem would probably be to treat the footnote about the purpose of the rule as though it were normative, and made the rule unenforceable except in cases which actually involve conflicting accesses using aliases. Given something like:

 void inc_int(int *p) { *p = 3; }
 int test(void)
 {
   int *p;
   struct S { int x; } s;
   s.x = 1;
   p = &s.x;
   inc_int(p);
   return s.x;
 }

There's no conflict within inc_int because all accesses to the storage accessed through *p are done with an lvalue of type int, and there's no conflict in test because p is visibly derived from a struct S, and by the next time s is used, all accesses to that storage that will ever be made through p will have already happened.

If the code were changed slightly...

 void inc_int(int *p) { *p = 3; }
 int test(void)
 {
   int *p;
   struct S { int x; } s;
   p = &s.x;
   s.x = 1;  //  !!*!!
   *p += 1;
   return s.x;
 }

Here, there is an aliasing conflict between p and the access to s.x on the marked line because at that point in execution another reference exists that will be used to access the same storage.

Had Defect Report 028 said the original example invoked UB because of the overlap between the creation and use of the two pointers, that would have made things a lot more clear without having to add "Effective Types" or other such complexity.

Cannot find module '@angular/compiler'

In my case this was required:
npm install @angular/compiler --save
npm install @angular/cli --save-dev

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

What are some great online database modeling tools?

The DB Designer Fork project claims that it can generate FireBird sql scripts.

What's the difference between an id and a class?

A CLASS should be used for multiple elements that you want the same styling for. An ID should be for a unique element. See this tutorial.

You should refer to the W3C standards if you want to be a strict conformist, or if you want your pages to be validated to the standards.

How to check user is "logged in"?

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

How to export data as CSV format from SQL Server using sqlcmd?

Is this not bcp was meant for?

bcp "select col1, col2, col3 from database.schema.SomeTable" queryout  "c:\MyData.txt"  -c -t"," -r"\n" -S ServerName -T

Run this from your command line to check the syntax.

bcp /?

For example:

usage: bcp {dbtable | query} {in | out | queryout | format} datafile
  [-m maxerrors]            [-f formatfile]          [-e errfile]
  [-F firstrow]             [-L lastrow]             [-b batchsize]
  [-n native type]          [-c character type]      [-w wide character type]
  [-N keep non-text native] [-V file format version] [-q quoted identifier]
  [-C code page specifier]  [-t field terminator]    [-r row terminator]
  [-i inputfile]            [-o outfile]             [-a packetsize]
  [-S server name]          [-U username]            [-P password]
  [-T trusted connection]   [-v version]             [-R regional enable]
  [-k keep null values]     [-E keep identity values]
  [-h "load hints"]         [-x generate xml format file]
  [-d database name]

Please, note that bcp can not output column headers.

See: bcp Utility docs page.

Example from the above page:

bcp.exe MyTable out "D:\data.csv" -T -c -C 65001 -t , ...

Fail during installation of Pillow (Python module) in Linux

Thank you @mfitzp. In my case (CentOS) these libs are not available in the yum repo, but actually the solution was even easier. What I did:

sudo yum install python-devel
sudo yum install zlib-devel
sudo yum install libjpeg-turbo-devel

And now pillow's installation finishes successfully.

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

_x000D_
_x000D_
convertTime12to24 = (time12h) => {_x000D_
        const [time, modifier] = time12h.split(' ');_x000D_
        let [hours, minutes] = time.split(':');_x000D_
        (hours === '12' ? hours = '00' : ((modifier === 'PM' || modifier === 'pm') ? hours = parseInt(hours, 10) + 12 : ""));_x000D_
        return `${hours}:${minutes}`;_x000D_
      }_x000D_
      _x000D_
      _x000D_
       console.log(convertTime12to24('06:30 pm'));_x000D_
      
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.

Create mysql table directly from CSV file using the CSV Storage engine?

If you're ok with using Python, Pandas worked great for me (csvsql hanged forever for my case). Something like:

from sqlalchemy import create_engine
import pandas as pd

df = pd.read_csv('/PATH/TO/FILE.csv')
# Optional, set your indexes to get Primary Keys
df = df.set_index(['COL A', 'COL B'])

engine = create_engine('mysql://user:pass@host/db', echo=False)

df.to_sql(table_name, dwh_engine, index=False)

Also this doesn't solve the "using CSV engine" part which was part of the question but might me useful as well.

The network path was not found

Same problem with me. I solved this by adding @ before connection string (C# has a thing called 'String Literals') like so:

SqlConnection sconnection = new SqlConnection(@"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");

sconnection.Open();

Create normal zip file programmatically

Edit: if you're using .Net 4.5 or later this is built-in to the framework

For earlier versions or for more control you can use Windows' shell functions as outlined here on CodeProject by Gerald Gibson Jr.

I have copied the article text below as written (original license: public domain)

Compress Zip files with Windows Shell API and C

enter image description here

Introduction

This is a follow up article to the one that I wrote about decompressing Zip files. With this code you can use the Windows Shell API in C# to compress Zip files and do so without having to show the Copy Progress window shown above. Normally when you use the Shell API to compress a Zip file, it will show a Copy Progress window even when you set the options to tell Windows not to show it. To get around this, you move the Shell API code to a separate executable and then launch that executable using the .NET Process class being sure to set the process window style to 'Hidden'.

Background

Ever needed to compress Zip files and needed a better Zip than what comes with many of the free compression libraries out there? I.e. you needed to compress folders and subfolders as well as files. Windows Zipping can compress more than just individual files. All you need is a way to programmatically get Windows to silently compress these Zip files. Of course you could spend $300 on one of the commercial Zip components, but it's hard to beat free if all you need is to compress folder hierarchies.

Using the code

The following code shows how to use the Windows Shell API to compress a Zip file. First you create an empty Zip file. To do this create a properly constructed byte array and then save that array as a file with a '.zip' extension. How did I know what bytes to put into the array? Well I just used Windows to create a Zip file with a single file compressed inside. Then I opened the Zip with Windows and deleted the compressed file. That left me with an empty Zip. Next I opened the empty Zip file in a hex editor (Visual Studio) and looked at the hex byte values and converted them to decimal with Windows Calc and copied those decimal values into my byte array code. The source folder points to a folder you want to compress. The destination folder points to the empty Zip file you just created. This code as is will compress the Zip file, however it will also show the Copy Progress window. To make this code work, you will also need to set a reference to a COM library. In the References window, go to the COM tab and select the library labeled 'Microsoft Shell Controls and Automation'.

//Create an empty zip file
byte[] emptyzip = new byte[]{80,75,5,6,0,0,0,0,0, 
                  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

FileStream fs = File.Create(args[1]);
fs.Write(emptyzip, 0, emptyzip.Length);
fs.Flush();
fs.Close();
fs = null;

//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(args[0]);
Shell32.Folder DestFlder = sc.NameSpace(args[1]); 
Shell32.FolderItems items = SrcFlder.Items();
DestFlder.CopyHere(items, 20);

//Ziping a file using the Windows Shell API 
//creates another thread where the zipping is executed.
//This means that it is possible that this console app 
//would end before the zipping thread 
//starts to execute which would cause the zip to never 
//occur and you will end up with just
//an empty zip file. So wait a second and give 
//the zipping thread time to get started
System.Threading.Thread.Sleep(1000);

The sample solution included with this article shows how to put this code into a console application and then launch this console app to compress the Zip without showing the Copy Progress window.

The code below shows a button click event handler that contains the code used to launch the console application so that there is no UI during the compress:

private void btnUnzip_Click(object sender, System.EventArgs e)
{
    //Test to see if the user entered a zip file name
    if(txtZipFileName.Text.Trim() == "")
    {
        MessageBox.Show("You must enter what" + 
               " you want the name of the zip file to be");
        //Change the background color to cue the user to what needs fixed
        txtZipFileName.BackColor = Color.Yellow;
        return;
    }
    else
    {
        //Reset the background color
        txtZipFileName.BackColor = Color.White;
    }

    //Launch the zip.exe console app to do the actual zipping
    System.Diagnostics.ProcessStartInfo i =
        new System.Diagnostics.ProcessStartInfo(
        AppDomain.CurrentDomain.BaseDirectory + "zip.exe");
    i.CreateNoWindow = true;
    string args = "";

    
    if(txtSource.Text.IndexOf(" ") != -1)
    {
        //we got a space in the path so wrap it in double qoutes
        args += "\"" + txtSource.Text + "\"";
    }
    else
    {
        args += txtSource.Text;
    }

    string dest = txtDestination.Text;

    if(dest.EndsWith(@"\") == false)
    {
        dest += @"\";
    }

    //Make sure the zip file name ends with a zip extension
    if(txtZipFileName.Text.ToUpper().EndsWith(".ZIP") == false)
    {
        txtZipFileName.Text += ".zip";
    }

    dest += txtZipFileName.Text;

    if(dest.IndexOf(" ") != -1)
    {
        //we got a space in the path so wrap it in double qoutes
        args += " " + "\"" + dest + "\"";
    }
    else
    {
        args += " " + dest;
    }

    i.Arguments = args;
    

    //Mark the process window as hidden so 
    //that the progress copy window doesn't show
    i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;    
    System.Diagnostics.Process p = System.Diagnostics.Process.Start(i);
    p.WaitForExit();
    MessageBox.Show("Complete");
}

Create Table from JSON Data with angularjs and ng-repeat

To create HTML table using JSON, we will use ngRepeat directive of AngularJS.

Example

HTML

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border="1">
<tr ng-repeat="x in names">
<td>{{x.Name}}</td>
<td>{{x.City}}</td>
<td>{{x.Country}}</td></tr>
</table>
</div>
</body>
</html>

JavaScript

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
    $scope.names = [
      { "Name" : "Max Joe", "City" : "Lulea", "Country" : "Sweden" },
      { "Name" : "Manish", "City" : "Delhi", "Country" : "India" },
      { "Name" : "Koniglich", "City" : "Barcelona", "Country" : "Spain" },
      { "Name" : "Wolski", "City" : "Arhus", "Country" : "Denmark" }
    ];
});

In above example I have created table from json. I have taken reference from http://www.tutsway.com/create-html-table-using-json-in-angular-js.php

Mockito: Trying to spy on method is calling the original method

One way to make sure a method from a class is not called is to override the method with a dummy.

    WebFormCreatorActivity activity = spy(new WebFormCreatorActivity(clientFactory) {//spy(new WebFormCreatorActivity(clientFactory));
            @Override
            public void select(TreeItem i) {
                log.debug("SELECT");
            };
        });