Programs & Examples On #Structuremap

StructureMap is a Dependency Injection / Inversion of Control tool for .NET licensed under Apache 2. It can be found at http://structuremap.net

How do the major C# DI/IoC frameworks compare?

Disclaimer: As of early 2015, there is a great comparison of IoC Container features from Jimmy Bogard, here is a summary:

Compared Containers:

  • Autofac
  • Ninject
  • Simple Injector
  • StructureMap
  • Unity
  • Windsor

The scenario is this: I have an interface, IMediator, in which I can send a single request/response or a notification to multiple recipients:

public interface IMediator 
{ 
    TResponse Send<TResponse>(IRequest<TResponse> request);

    Task<TResponse> SendAsync<TResponse>(IAsyncRequest<TResponse> request);

    void Publish<TNotification>(TNotification notification)
        where TNotification : INotification;

    Task PublishAsync<TNotification>(TNotification notification)
        where TNotification : IAsyncNotification; 
}

I then created a base set of requests/responses/notifications:

public class Ping : IRequest<Pong>
{
    public string Message { get; set; }
}
public class Pong
{
    public string Message { get; set; }
}
public class PingAsync : IAsyncRequest<Pong>
{
    public string Message { get; set; }
}
public class Pinged : INotification { }
public class PingedAsync : IAsyncNotification { }

I was interested in looking at a few things with regards to container support for generics:

  • Setup for open generics (registering IRequestHandler<,> easily)
  • Setup for multiple registrations of open generics (two or more INotificationHandlers)

Setup for generic variance (registering handlers for base INotification/creating request pipelines) My handlers are pretty straightforward, they just output to console:

public class PingHandler : IRequestHandler<Ping, Pong> { /* Impl */ }
public class PingAsyncHandler : IAsyncRequestHandler<PingAsync, Pong> { /* Impl */ }

public class PingedHandler : INotificationHandler<Pinged> { /* Impl */ }
public class PingedAlsoHandler : INotificationHandler<Pinged> { /* Impl */ }
public class GenericHandler : INotificationHandler<INotification> { /* Impl */ }

public class PingedAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }
public class PingedAlsoAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }

Autofac

var builder = new ContainerBuilder();
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof (IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Ping).Assembly).AsImplementedInterfaces();
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, explicitly

Ninject

var kernel = new StandardKernel();
kernel.Components.Add<IBindingResolver, ContravariantBindingResolver>();
kernel.Bind(scan => scan.FromAssemblyContaining<IMediator>()
    .SelectAllClasses()
    .BindDefaultInterface());
kernel.Bind(scan => scan.FromAssemblyContaining<Ping>()
    .SelectAllClasses()
    .BindAllInterfaces());
kernel.Bind<TextWriter>().ToConstant(Console.Out);
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, with user-built extensions

Simple Injector

var container = new Container();
var assemblies = GetAssemblies().ToArray();
container.Register<IMediator, Mediator>();
container.Register(typeof(IRequestHandler<,>), assemblies);
container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
  • Open generics: yes, explicitly
  • Multiple open generics: yes, explicitly
  • Generic contravariance: yes, implicitly (with update 3.0)

StructureMap

var container = new Container(cfg =>
{
    cfg.Scan(scanner =>
    {
        scanner.AssemblyContainingType<Ping>();
        scanner.AssemblyContainingType<IMediator>();
        scanner.WithDefaultConventions();
        scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
        scanner.AddAllTypesOf(typeof(IAsyncRequestHandler<,>));
        scanner.AddAllTypesOf(typeof(INotificationHandler<>));
        scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler<>));
    });
});
  • Open generics: yes, explicitly
  • Multiple open generics: yes, explicitly
  • Generic contravariance: yes, implicitly

Unity

container.RegisterTypes(AllClasses.FromAssemblies(typeof(Ping).Assembly),
   WithMappings.FromAllInterfaces,
   GetName,
   GetLifetimeManager);

/* later down */

static bool IsNotificationHandler(Type type)
{
    return type.GetInterfaces().Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == typeof(INotificationHandler<>) || x.GetGenericTypeDefinition() == typeof(IAsyncNotificationHandler<>)));
}

static LifetimeManager GetLifetimeManager(Type type)
{
    return IsNotificationHandler(type) ? new ContainerControlledLifetimeManager() : null;
}

static string GetName(Type type)
{
    return IsNotificationHandler(type) ? string.Format("HandlerFor" + type.Name) : string.Empty;
}
  • Open generics: yes, implicitly
  • Multiple open generics: yes, with user-built extension
  • Generic contravariance: derp

Windsor

var container = new WindsorContainer();
container.Register(Classes.FromAssemblyContaining<IMediator>().Pick().WithServiceAllInterfaces());
container.Register(Classes.FromAssemblyContaining<Ping>().Pick().WithServiceAllInterfaces());
container.Kernel.AddHandlersFilter(new ContravariantFilter());
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, with user-built extension

Why do I need an IoC container as opposed to straightforward DI code?

you do not need a framework to achieve dependency injection. You can do this by core java concepts as well. http://en.wikipedia.org/wiki/Dependency_injection#Code_illustration_using_Java

Dependency Injection vs Factory Pattern

My thoughts:

Dependecy Injection: pass collaborators as parameters to the constructors. Dependency Injection Framework: a generic and configurable factory to create the objects to pass as parameters to the constructors.

Copy all values in a column to a new column in a pandas dataframe

Here is your dataframe:

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

Your answer is in the paragraph "Setting with enlargement" in the section on "Indexing and selecting data" in the documentation on Pandas.

It says:

A DataFrame can be enlarged on either axis via .loc.

So what you need to do is simply one of these two:

df.loc[:, 'D'] = df.loc[:, 'B']
df.loc[:, 'D'] = df['B']

What does "select count(1) from table_name" on any database tables mean?

This is similar to the difference between

SELECT * FROM table_name and SELECT 1 FROM table_name.  

If you do

SELECT 1 FROM table_name

it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)

Try catch statements in C

This can be done with setjmp/longjmp in C. P99 has a quite comfortable toolset for this that also is consistent with the new thread model of C11.

Iterating through a golang map

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                },
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
                },
        }
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)
                }

        }
}

And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000

Disable HttpClient logging

I was led to this post when searching for solution for similar problem. Tim's answer was very helpful. like Matt Baker, I just want to shut off httpClient log without too much configuration. As we were not sure which logging implementation underneath common-logging was used, My solution was to force it using log4j by throwing log4j jar file in the class path. Default setting of log4j configuration shuts off common-httpclient debug output. Of course, to make it more robust, you may create common-logging.properties and log4j.properties files to further define your logging configurations.

Correct way to pass multiple values for same parameter name in GET request

I am describing a simple method which worked very smoothly in Python (Django Framework).

1. While sending the request, send the request like this

http://server/action?id=a,b

2. Now in my backend, I split the value received with a split function which always creates a list.

id_filter = id.split(',')

Example: So if I send two values in the request,

http://server/action?id=a,b

then the filter on the data is

id_filter = ['a', 'b']

If I send only one value in the request,

http://server/action?id=a

then the filter outcome is

id_filter = ['a']

3. To actually filter the data, I simply use the 'in' function

queryset = queryset.filter(model_id__in=id_filter)

which roughly speaking performs the SQL equivalent of

WHERE model_id IN ('a', 'b')

with the first request and,

WHERE model_id IN ('a')

with the second request.

This would work with more than 2 parameter values in the request as well !

Setting cursor at the end of any text of a textbox

You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:

txtBox.CaretIndex=txtBox.Text.Length;

You need to set the caret index at the length, not length-1, because this would put the caret before the last character.

Upload file to FTP using C#

I have observed that -

  1. FtpwebRequest is missing.
  2. As the target is FTP, so the NetworkCredential required.

I have prepared a method that works like this, you can replace the value of the variable ftpurl with the parameter TargetDestinationPath. I had tested this method on winforms application :

private void UploadProfileImage(string TargetFileName, string TargetDestinationPath, string FiletoUpload)
        {
            //Get the Image Destination path
            string imageName = TargetFileName; //you can comment this
            string imgPath = TargetDestinationPath; 

            string ftpurl = "ftp://downloads.abc.com/downloads.abc.com/MobileApps/SystemImages/ProfileImages/" + imgPath;
            string ftpusername = krayknot_DAL.clsGlobal.FTPUsername;
            string ftppassword = krayknot_DAL.clsGlobal.FTPPassword;
            string fileurl = FiletoUpload;

            FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl);
            ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
            ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftpClient.UseBinary = true;
            ftpClient.KeepAlive = true;
            System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
            ftpClient.ContentLength = fi.Length;
            byte[] buffer = new byte[4097];
            int bytes = 0;
            int total_bytes = (int)fi.Length;
            System.IO.FileStream fs = fi.OpenRead();
            System.IO.Stream rs = ftpClient.GetRequestStream();
            while (total_bytes > 0)
            {
                bytes = fs.Read(buffer, 0, buffer.Length);
                rs.Write(buffer, 0, bytes);
                total_bytes = total_bytes - bytes;
            }
            //fs.Flush();
            fs.Close();
            rs.Close();
            FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
            string value = uploadResponse.StatusDescription;
            uploadResponse.Close();
        }

Let me know in case of any issue, or here is one more link that can help you:

https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx

PHP header() redirect with POST variables

It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

Python unexpected EOF while parsing

I'm using the follow code to get Python 2 and 3 compatibility

if sys.version_info < (3, 0):
    input = raw_input

Load JSON text into class object in c#

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

Logical XOR operator in C++?

For a true logical XOR operation, this will work:

if(!A != !B) {
    // code here
}

Note the ! are there to convert the values to booleans and negate them, so that two unequal positive integers (each a true) would evaluate to false.

What is the difference between Google App Engine and Google Compute Engine?

I'll explain it in a way that made sense to me:

  • Compute Engine: If you are do-it-yourself person or have an IT team and you just want to rent a computer on cloud that has specific OS (for example linux), you go for the Compute Engine. You have to do everything by yourself.

  • App Engine: If you are (for example) a python programmer and you want to rent a pre-configured computer on cloud that has Linux with a running web-server and the latest python 3 with necessary modules and some plug-ins to integrate with other external services, you go for the App Engine.

  • Serverless Container (Cloud Run): If you would like to deploy the exact image of your local setup environment (for example: python 3.7+flask+sklearn) but you do not want to deal with server, scaling, etc. You create a container on your local machine (through docker) and then deploy it to Google Run.

  • Serverless Microservice (Cloud Functions): If you want to write bunch of APIs (functions) that do specific job, you go for google Cloud Functions. You just focus on those specific functions, the rest of the job (server, maintenance, scaling, etc.) is done for you in order to expose your functions as microservices.

As you go deeper, you lose some flexibility but you are not worried about unnecessary technical aspects. You also pay a little more but you save time and cost (IT part): someone else (google) is doing it for you.

If you want to not care about load balancing, scaling, etc., it is crucial to split your app to bunch of "stateless" web services that writes anything persistent in a separate storage (database or blob storage). Then you will found how awesome is Cloud Run and Cloud Functions.

Personally, I found Google Cloud Run an awesome solution, absolute freedom in development (as long as stateless), expose it as a web service, docker your solution, deploy it with Cloud Run. Let google be your IT and DevOps, you do not need to care about scaling and maintenance.

I have tried all other options and each one is good for different purpose but Google Run is just awesome. To me, it is the real serverless without losing flexibility in development.

How to prevent caching of my Javascript file?

<script src="test.js?random=<?php echo uniqid(); ?>"></script>

EDIT: Or you could use the file modification time so that it's cached on the client.

<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>

What are the best JVM settings for Eclipse?

It is that time of year again: "eclipse.ini take 3" the settings strike back!

Eclipse Helios 3.6 and 3.6.x settings

alt text http://www.eclipse.org/home/promotions/friends-helios/helios.png

After settings for Eclipse Ganymede 3.4.x and Eclipse Galileo 3.5.x, here is an in-depth look at an "optimized" eclipse.ini settings file for Eclipse Helios 3.6.x:

(by "optimized", I mean able to run a full-fledge Eclipse on our crappy workstation at work, some old P4 from 2002 with 2Go RAM and XPSp3. But I have also tested those same settings on Windows7)

Eclipse.ini

alt text

WARNING: for non-windows platform, use the Sun proprietary option -XX:MaxPermSize instead of the Eclipse proprietary option --launcher.XXMaxPermSize.
That is: Unless you are using the latest jdk6u21 build 7. See the Oracle section below.

-data
../../workspace
-showlocation
-showsplash
org.eclipse.platform
--launcher.defaultAction
openFile
-vm
C:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Declipse.p2.unsignedPolicy=allow
-Xms128m
-Xmx384m
-Xss4m
-XX:PermSize=128m
-XX:MaxPermSize=384m
-XX:CompileThreshold=5
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+CMSIncrementalPacing
-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
-Dcom.sun.management.jmxremote
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons

Note:
Adapt the p2.reconciler.dropins.directory to an external directory of your choice.
See this SO answer. The idea is to be able to drop new plugins in a directory independently from any Eclipse installation.

The following sections detail what are in this eclipse.ini file.


The dreaded Oracle JVM 1.6u21 (pre build 7) and Eclipse crashes

Andrew Niefer did alert me to this situation, and wrote a blog post, about a non-standard vm argument (-XX:MaxPermSize) and can cause vms from other vendors to not start at all.
But the eclipse version of that option (--launcher.XXMaxPermSize) is not working with the new JDK (6u21, unless you are using the 6u21 build 7, see below).

The final solution is on the Eclipse Wiki, and for Helios on Windows with 6u21 pre build 7 only:

(eclipse_home)/plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.0.v20100503

That's it. No setting to tweak here (again, only for Helios on Windows with a 6u21 pre build 7).
For non-Windows platform, you need to revert to the Sun proprietary option -XX:MaxPermSize.

The issue is based one a regression: JVM identification fails due to Oracle rebranding in java.exe, and triggered bug 319514 on Eclipse.
Andrew took care of Bug 320005 - [launcher] --launcher.XXMaxPermSize: isSunVM should return true for Oracle, but that will be only for Helios 3.6.1.
Francis Upton, another Eclipse committer, reflects on the all situation.

Update u21b7, July, 27th:
Oracle have regressed the change for the next Java 6 release and won't implement it again until JDK 7.
If you use jdk6u21 build 7, you can revert to the --launcher.XXMaxPermSize (eclipse option) instead of -XX:MaxPermSize (the non-standard option).
The auto-detection happening in the C launcher shim eclipse.exe will still look for the "Sun Microsystems" string, but with 6u21b7, it will now work - again.

For now, I still keep the -XX:MaxPermSize version (because I have no idea when everybody will launch eclipse the right JDK).


Implicit `-startup` and `--launcher.library`

Contrary to the previous settings, the exact path for those modules is not set anymore, which is convenient since it can vary between different Eclipse 3.6.x releases:

  • startup: If not specified, the executable will look in the plugins directory for the org.eclipse.equinox.launcher bundle with the highest version.
  • launcher.library: If not specified, the executable looks in the plugins directory for the appropriate org.eclipse.equinox.launcher.[platform] fragment with the highest version and uses the shared library named eclipse_* inside.

Use JDK6

The JDK6 is now explicitly required to launch Eclipse:

-Dosgi.requiredJavaVersion = 1.6

This SO question reports a positive incidence for development on Mac OS.


+UnlockExperimentalVMOptions

The following options are part of some of the experimental options of the Sun JVM.

-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods

They have been reported in this blog post to potentially speed up Eclipse.
See all the JVM options here and also in the official Java Hotspot options page.
Note: the detailed list of those options reports that UseFastAccessorMethods might be active by default.

See also "Update your JVM":

As a reminder, G1 is the new garbage collector in preparation for the JDK 7, but already used in the version 6 release from u17.


Opening files in Eclipse from the command line

See the blog post from Andrew Niefer reporting this new option:

--launcher.defaultAction
openFile

This tells the launcher that if it is called with a command line that only contains arguments that don't start with "-", then those arguments should be treated as if they followed "--launcher.openFile".

eclipse myFile.txt

This is the kind of command line the launcher will receive on windows when you double click a file that is associated with eclipse, or you select files and choose "Open With" or "Send To" Eclipse.

Relative paths will be resolved first against the current working directory, and second against the eclipse program directory.

See bug 301033 for reference. Originally bug 4922 (October 2001, fixed 9 years later).


p2 and the Unsigned Dialog Prompt

If you are tired of this dialog box during the installation of your many plugins:

alt text

, add in your eclipse.ini:

-Declipse.p2.unsignedPolicy=allow

See this blog post from Chris Aniszczy, and the bug report 235526.

I do want to say that security research supports the fact that less prompts are better.
People ignore things that pop up in the flow of something they want to get done.

For 3.6, we should not pop up warnings in the middle of the flow - no matter how much we simplify, people will just ignore them.
Instead, we should collect all the problems, do not install those bundles with problems, and instead bring the user back to a point in the workflow where they can fixup - add trust, configure security policy more loosely, etc. This is called 'safe staging'.

---------- http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif

Additional options

Those options are not directly in the eclipse.ini above, but can come in handy if needed.


The `user.home` issue on Windows7

When eclipse starts, it will read its keystore file (where passwords are kept), a file located in user.home.
If for some reason that user.home doesn't resolve itself properly to a full-fledge path, Eclipse won't start.
Initially raised in this SO question, if you experience this, you need to redefine the keystore file to an explicit path (no more user.home to resolve at the start)

Add in your eclipse.ini:

-eclipse.keyring 
C:\eclipse\keyring.txt

This has been tracked by bug 300577, it has been solve in this other SO question.


Debug mode

Wait, there's more than one setting file in Eclipse.
if you add to your eclipse.ini the option:

-debug

, you enable the debug mode and Eclipse will look for another setting file: a .options file where you can specify some OSGI options.
And that is great when you are adding new plugins through the dropins folder.
Add in your .options file the following settings, as described in this blog post "Dropins diagnosis":

org.eclipse.equinox.p2.core/debug=true
org.eclipse.equinox.p2.core/reconciler=true

P2 will inform you what bundles were found in dropins/ folder, what request was generated, and what is the plan of installation. Maybe it is not detailed explanation of what actually happened, and what went wrong, but it should give you strong information about where to start:

  • was your bundle in the plan?
  • Was it installation problem (P2 fault)
  • or maybe it is just not optimal to include your feature?

That comes from Bug 264924 - [reconciler] No diagnosis of dropins problems, which finally solves the following issue like:

Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipse
Unzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5

This is a problematic configuration since OCL depends on EMF which is missing.
3.5M5 provides no diagnosis of this problem.

Start eclipse.
No obvious problems. Nothing in Error Log.

  • Help / About / Plugin details shows org.eclipse.ocl.doc, but not org.eclipse.ocl.
  • Help / About / Configuration details has no (diagnostic) mention of org.eclipse.ocl.
  • Help / Installation / Information Installed Software has no mention of org.eclipse.ocl.

Where are the nice error markers?


Manifest Classpath

See this blog post:

  • In Galileo (aka Eclipse 3.5), JDT started resolving manifest classpath in libraries added to project’s build path. This worked whether the library was added to project’s build path directly or via a classpath container, such as the user library facility provided by JDT or one implemented by a third party.
  • In Helios, this behavior was changed to exclude classpath containers from manifest classpath resolution.

That means some of your projects might no longer compile in Helios.
If you want to revert to Galileo behavior, add:

-DresolveReferencedLibrariesForContainers=true

See bug 305037, bug 313965 and bug 313890 for references.


IPV4 stack

This SO question mentions a potential fix when not accessing to plugin update sites:

-Djava.net.preferIPv4Stack=true

Mentioned here just in case it could help in your configuration.


JVM1.7x64 potential optimizations

This article reports:

For the record, the very fastest options I have found so far for my bench test with the 1.7 x64 JVM n Windows are:

-Xincgc 
-XX:-DontCompileHugeMethods 
-XX:MaxInlineSize=1024  
-XX:FreqInlineSize=1024 

But I am still working on it...

Delaying a jquery script until everything else has loaded

The following script ensures that my_finalFunction runs after your page has been fully loaded with images, stylesheets and external content:

<script>

    document.addEventListener("load", my_finalFunction, false);

    function my_finalFunction(e) {
        /* things to do after all has been loaded */
    }

</script>

A good explanation is provided by kirupa on running your code at the right time, see https://www.kirupa.com/html5/running_your_code_at_the_right_time.htm.

What does the @Valid annotation indicate in Spring?

Adding to above answers, take a look at following. AppointmentForm's date column is annotated with couple of annotations. By having @Valid annotation that triggers validations on the AppointmentForm (in this case @NotNull and @Future). These annotations could come from different JSR-303 providers (e.g, Hibernate, Spring..etc).

    @RequestMapping(value = "/appointments", method = RequestMethod.POST)
    public String add(@Valid AppointmentForm form, BindingResult result) {
        ....
    }

    static class AppointmentForm {

        @NotNull @Future
        private Date date;
    }

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

Since the question has been already answered i.e. the best way is to use the remove method of the iterator object, I would go into the specifics of the place where the error "java.util.ConcurrentModificationException" is thrown.

Every collection class has a private class which implements the Iterator interface and provides methods like next(), remove() and hasNext().

The code for next looks something like this...

public E next() {
    checkForComodification();
    try {
        E next = get(cursor);
        lastRet = cursor++;
        return next;
    } catch(IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
    }
}

Here the method checkForComodification is implemented as

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

So, as you can see, if you explicitly try to remove an element from the collection. It results in modCount getting different from expectedModCount, resulting in the exception ConcurrentModificationException.

How can I define colors as variables in CSS?

Do not use css3 variables due to support.

I would do the following if you want a pure css solution.

  1. Use color classes with semenatic names.

    .bg-primary   { background: #880000; }
    
    .bg-secondary { background: #008800; }
    
    .bg-accent    { background: #F5F5F5; }
    
  2. Separate the structure from the skin (OOCSS)

    /* Instead of */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
        color: #8000;
    }
    
    /* use this */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
    }
    
    .bg-primary {
        background: #880000;
    }
    
    /* This will allow you to reuse colors in your design */
    
  3. Put these inside a separate css file to change as needed.

getActionBar() returns null

One thing I wanted to add since I just ran into this, if you are trying to getActionBar() on an Activity that has a parent, it will return null. I am trying to refactor code where my Activity is contained inside an ActivityGroup, and it took a good few minutes for me to go "oh duh" after looking at the source of how an ActionBar gets created in source.

How do I grep for all non-ASCII characters?

It could be interesting to know how to search for one unicode character. This command can help. You only need to know the code in UTF8

grep -v $'\u200d'

What does the @ symbol before a variable name mean in C#?

It allows you to use a C# keyword as a variable. For example:

class MyClass
{
   public string name { get; set; }
   public string @class { get; set; }
}

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

What is tempuri.org?

Webservices require unique namespaces so they don't confuse each others schemas and whatever with each other. A URL (domain, subdomain, subsubdomain, etc) is a clever identifier as it's "guaranteed" to be unique, and in most circumstances you've already got one.

How to replace (or strip) an extension from a filename in Python?

Expanding on AnaPana's answer, how to remove an extension using pathlib (Python >= 3.4):

>>> from pathlib import Path

>>> filename = Path('/some/path/somefile.txt')

>>> filename_wo_ext = filename.with_suffix('')

>>> filename_replace_ext = filename.with_suffix('.jpg')

>>> print(filename)
/some/path/somefile.ext    

>>> print(filename_wo_ext)
/some/path/somefile

>>> print(filename_replace_ext)
/some/path/somefile.jpg

Check if the file exists using VBA

Very old post, but since it helped me after I made some modifications, I thought I'd share. If you're checking to see if a directory exists, you'll want to add the vbDirectory argument to the Dir function, otherwise you'll return 0 each time. (Edit: this was in response to Roy's answer, but I accidentally made it a regular answer.)

Private Function FileExists(fullFileName As String) As Boolean
    FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

What is the purpose of the single underscore "_" variable in Python?

_ has 3 main conventional uses in Python:

  1. To hold the result of the last executed expression(/statement) in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit

  2. For translation lookup in i18n (see the gettext documentation for example), as in code like

    raise forms.ValidationError(_("Please enter a correct username"))
    
  3. As a general purpose "throwaway" variable name:

    1. To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:

      label, has_label, _ = text.partition(':')
      
    2. As part of a function definition (using either def or lambda), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like:

      def callback(_):
          return True
      

      [For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]

    This use case can conflict with the translation lookup use case, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).

    Linters often recognize this use case. For example year, month, day = date() will raise a lint warning if day is not used later in the code. The fix, if day is truly not needed, is to write year, month, _ = date(). Same with lambda functions, lambda arg: 1.0 creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write lambda _: 1.0. An unused variable is often hiding a bug/typo (e.g. set day but use dya in the next line).

View markdown files offline

I frequently want portable applications. For this, I found

http://cloose.github.io/CuteMarkEd/ (I have just tried it briefly, and it seems to work fine).

http://markdownpad.com/faq.html#portable

How to capitalize the first letter of a String in Java?

String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);

How to create a fixed sidebar layout with Bootstrap 4?

something like this?

_x000D_
_x000D_
#sticky-sidebar {_x000D_
position:fixed;_x000D_
max-width: 20%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4">_x000D_
      <div class="col-xs-12" id="sticky-sidebar">_x000D_
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-xs-8" id="main">_x000D_
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
    </div>_x000D_
  </div>_x000D_
</div
_x000D_
_x000D_
_x000D_

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

I like live-server. It is fast and has a nice live reload feature, which is very convenient during developpement.

Usage is very simple:

cd ~/Sites/
live-server

By default it creates a server with IP 127.0.0.1 and port 8080.

http://127.0.0.1:8080/

If port 8080 is not free, it uses another port:

http://127.0.0.1:52749/

http://127.0.0.1:52858/

If you need to see the web server on other machines in your local network, you can check what is your IP and use:

live-server --host=192.168.1.121

And here is a script that automatically grab the IP address of the default interface. It works on macOS only.

If you put it in .bash_profile, the live-server command will automatically launch the server with the correct IP.

# **
# Get IP address of default interface
# *
function getIPofDefaultInterface()
{
    local  __resultvar=$1

    # Get default route interface
    if=$(route -n get 0.0.0.0 2>/dev/null | awk '/interface: / {print $2}')
    if [ -n "$if" ]; then
            # Get IP of the default route interface
            local __IP=$( ipconfig getifaddr $if )
            eval $__resultvar="'$__IP'"
    else
        # Echo "No default route found"
        eval $__resultvar="'0.0.0.0'"
    fi
}

alias getIP='getIPofDefaultInterface IP; echo $IP'

# **
# live-server
# https://www.npmjs.com/package/live-server
# *
alias live-server='getIPofDefaultInterface IP && live-server --host=$IP'

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Wildcard string comparison in Javascript

var searchArray = function(arr, str){
    // If there are no items in the array, return an empty array
    if(typeof arr === 'undefined' || arr.length === 0) return [];
    // If the string is empty return all items in the array
    if(typeof str === 'undefined' || str.length === 0) return arr;

    // Create a new array to hold the results.
    var res = [];

    // Check where the start (*) is in the string
    var starIndex = str.indexOf('*');

    // If the star is the first character...
    if(starIndex === 0) {

        // Get the string without the star.
        str = str.substr(1);
        for(var i = 0; i < arr.length; i++) {

            // Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
            // It doesn't necessarily mean it IS a string either.
            if(!arr[i].indexOf) continue;

            // Check if the string is at the end of each item.
            if(arr[i].indexOf(str) === arr[i].length - str.length) {                    
                // If it is, add the item to the results.
                res.push(arr[i]);
            }
        }
    }
    // Otherwise, if the star is the last character
    else if(starIndex === str.length - 1) {
        // Get the string without the star.
        str = str.substr(0, str.length - 1);
        for(var i = 0; i < arr.length; i++){
            // Check indexOf function                
            if(!arr[i].indexOf) continue;
            // Check if the string is at the beginning of each item
            if(arr[i].indexOf(str) === 0) {
                // If it is, add the item to the results.
                res.push(arr[i]);
            }
        }
    }
    // In any other case...
    else {            
        for(var i = 0; i < arr.length; i++){
            // Check indexOf function
            if(!arr[i].indexOf) continue;
            // Check if the string is anywhere in each item
            if(arr[i].indexOf(str) !== -1) {
                // If it is, add the item to the results
                res.push(arr[i]);
            }
        }
    }

    // Return the results as a new array.
    return res;
}

var birds = ['bird1','somebird','bird5','bird-big','abird-song'];

var res = searchArray(birds, 'bird*');
// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song

There is an long list of caveats to a method like this, and a long list of 'what ifs' that are not taken into account, some of which are mentioned in other answers. But for a simple use of star syntax this may be a good starting point.

Fiddle

require_once :failed to open stream: no such file or directory

You will need to link to the file relative to the file that includes eventManager.php (Page A)

Change your code from
require_once('../includes/dbconn.inc');

To
require_once('../mysite/php/includes/dbconn.inc');

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

I encountered an issue like this using the Maven Release Plugin. Resolving using relative paths (i.e. for the parent pom in the child module ../parent/pom.xml) did not seem to work in this scenario, it keeps looking for the released parent pom in the Nexus repository. Moving the parent pom to the parent folder of the module resolved this.

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

What is the default database path for MongoDB?

I have version 2.0.7 installed on Ubuntu and it defaulted to /var/lib/mongodb/ and that is also what was placed into my /etc/mongodb.conf file.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

you may need to check whether the settings.xml file is correct. such as user name, password, third party url.

When should I use a table variable vs temporary table in sql server?

Use a table variable if for a very small quantity of data (thousands of bytes)

Use a temporary table for a lot of data

Another way to think about it: if you think you might benefit from an index, automated statistics, or any SQL optimizer goodness, then your data set is probably too large for a table variable.

In my example, I just wanted to put about 20 rows into a format and modify them as a group, before using them to UPDATE / INSERT a permanent table. So a table variable is perfect.

But I am also running SQL to back-fill thousands of rows at a time, and I can definitely say that the temporary tables perform much better than table variables.

This is not unlike how CTE's are a concern for a similar size reason - if the data in the CTE is very small, I find a CTE performs as good as or better than what the optimizer comes up with, but if it is quite large then it hurts you bad.

My understanding is mostly based on http://www.developerfusion.com/article/84397/table-variables-v-temporary-tables-in-sql-server/, which has a lot more detail.

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:

plt.tight_layout()

before the show. Yielding:

neater side by side plot

To show error message without alert box in Java Script

You should use .value and not .innerHTML as it is a input type form element

<html>
  <head>
  <script type="text/javascript">
  function validate() {
  if(myform.fname.value.length==0)
  {
   document.getElementById("fname").value="this is invalid name ";
  }
  }
  </script>
  </head>
  <body>
  <form name="myform">
  First_Name
  <input type=text id=fname name=fname onblur="validate()"> </input>

  <br> <br>
  Last_Name
  <input type=text id=lname name=lname onblur="validate()"> </input>

  <br>
  <input type=button value=check> 

  </form>
  </body>
</html>

Difference between Fact table and Dimension table?

From my point of view,

  • Dimension table : Master Data
  • Fact table : Transactional Data

Importing files from different folder

Just use change dir function from os module:

os.chdir("Here new director")

than you can import normally More Info

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

 IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

Twitter Bootstrap date picker

Some people posted the link to this bootstrap-datepicker.js implementation. I used that one in the following way, it works with Bootstrap 3.

This is the markup I used:

<div class="input-group date col-md-3" data-date-format="dd-mm-yyyy" data-date="01-01-2014">                        
    <input id="txtHomeLoanStartDate" class="form-control" type="text" readonly="" value="01-01-2014" size="14" />
    <span class="input-group-addon add-on">
        <span class="glyphicon glyphicon-calendar"</span>
    </span>
</div>

This is the javascript:

$('.date').datepicker();

I also included the javascript file downloaded from the link above, along with it's css file, and of course, you should remove any bootstrap grid classes like the col-md-3 to suit your needs.

Take nth column in a text file

For the sake of completeness:

while read _ _ one _ two _; do
    echo "$one $two"
done < file.txt

Instead of _ an arbitrary variable (such as junk) can be used as well. The point is just to extract the columns.

Demo:

$ while read _ _ one _ two _; do echo "$one $two"; done < /tmp/file.txt
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

Flutter: Run method on Widget build complete

If you want to do this only once, then do it because The framework will call initState() method exactly once for each State object it creates.

 @override
  void initState() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => executeAfterBuildComplete(context));
  }

If you want to do this again and again like on back or navigate to a next screen and etc..., then do it because didChangeDependencies() Called when a dependency of this State object changes.

For example, if the previous call to build referenced an InheritedWidget that later changed, the framework would call this method to notify this object about the change.

This method is also called immediately after initState. It is safe to call BuildContext.dependOnInheritedWidgetOfExactType from this method.

 @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => executeAfterBuildComplete(context));
  }

This is the your Callback function

executeAfterBuildComplete([BuildContext context]){
    print("Build Process Complete");
  }

Converting java date to Sql timestamp

I suggest using DateUtils from apache.commons library.

long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );

Edit: Fixed Calendar.MILISECOND to Calendar.MILLISECOND

Current date and time as string

#include <chrono>
#include <iostream>

int main()
{
    std::time_t ct = std::time(0);
    char* cc = ctime(&ct);

    std::cout << cc << std::endl;
    return 0;
}

Get first and last day of month using threeten, LocalDate

YearMonth

For completeness, and more elegant in my opinion, see this use of YearMonth class.

YearMonth month = YearMonth.from(date);
LocalDate start = month.atDay(1);
LocalDate end   = month.atEndOfMonth();

For the first & last day of the current month, this becomes:

LocalDate start = YearMonth.now().atDay(1);
LocalDate end   = YearMonth.now().atEndOfMonth();

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:

  1. Suggest using c.sendall() instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call (see docs).
  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')
  3. For variables, you need to encode Unicode strings to byte strings (see below)

Best solution (should work w/both 2.x & 3.x):

output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))

Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.

Escape double quote character in XML

If you just need to try something out quickly, here's a quick and dirty solution. Use single quotes for the attribute value:

<parameter name='Quote = " '>

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

UPDATE 9 July 2012 - Looks like this is fixed in RTM.

  1. We already imply ^ and $ so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)
  2. This appears to be a bug in ASP.NET MVC 4/Preview/Beta. I've opened a bug

View source shows the following:

data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)"                  <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9&#32;.&amp;amp;&amp;#39;-]+)"      <-- MVC 4/Beta

It looks like we're double encoding.

How to run cron once, daily at 10pm

Here are some more examples

  • Run every 6 hours at 46 mins past the hour:

    46 */6 * * *

  • Run at 2:10 am:

    10 2 * * *

  • Run at 3:15 am:

    15 3 * * *

  • Run at 4:20 am:

    20 4 * * *

  • Run at 5:31 am:

    31 5 * * *

  • Run at 5:31 pm:

    31 17 * * *

How can I decrypt a password hash in PHP?

Use the password_verify() function

if (password_vertify($inputpassword, $row['password'])) {
  print "Logged in";
else {
    print "Password Incorrect";
}

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

Submit form without page reloading

The page will get reloaded if you don't want to use javascript

Code for Greatest Common Divisor in Python

I had to do something like this for a homework assignment using while loops. Not the most efficient way, but if you don't want to use a function this works:

num1 = 20
num1_list = []
num2 = 40
num2_list = []
x = 1
y = 1
while x <= num1:
    if num1 % x == 0:
        num1_list.append(x)
    x += 1
while y <= num2:
    if num2 % y == 0:
        num2_list.append(y)
    y += 1
xy = list(set(num1_list).intersection(num2_list))
print(xy[-1])

What is the difference between display: inline and display: inline-block?

A visual answer

Imagine a <span> element inside a <div>. If you give the <span> element a height of 100px and a red border for example, it will look like this with

display: inline

display: inline

display: inline-block

display: inline-block

display: block

enter image description here

Code: http://jsfiddle.net/Mta2b/

Elements with display:inline-block are like display:inline elements, but they can have a width and a height. That means that you can use an inline-block element as a block while flowing it within text or other elements.

Difference of supported styles as summary:

  • inline: only margin-left, margin-right, padding-left, padding-right
  • inline-block: margin, padding, height, width

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

How do you delete a column by name in data.table?

Very simple option in case you have many individual columns to delete in a data table and you want to avoid typing in all column names #careadviced

dt <- dt[, -c(1,4,6,17,83,104)]

This will remove columns based on column number instead.

It's obviously not as efficient because it bypasses data.table advantages but if you're working with less than say 500,000 rows it works fine

How to exclude a directory from ant fileset, based on directories contents

I think one way is first to check whether your file exists and if it exists to exclude the folder from copy:

<target name="excludeLocales">

    <property name="de-DE.file" value="${basedir}/locale/de-DE/incompelte.flag"/>
    <available property="de-DE.file.exists" file="${de-DE.file}" />

    <copy todir="C:/temp/">
        <fileset dir="${basedir}/locale">
            <exclude name="de-DE/**" if="${de-DE.file.exists}"/>
            <include name="xy/**"/>
        </fileset>
    </copy>
</target>

This should work also for the other languages.

Verify External Script Is Loaded

If the script creates any variables or functions in the global space you can check for their existance:

External JS (in global scope) --

var myCustomFlag = true;

And to check if this has run:

if (typeof window.myCustomFlag == 'undefined') {
    //the flag was not found, so the code has not run
    $.getScript('<external JS>');
}

Update

You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:

//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
    return ($(this).attr('src') == '<external JS>');
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript('<external JS>');
}

Or you can just bake this .filter() functionality right into the selector:

var len = $('script[src="<external JS>"]').length;

Closure in Java 7

Please see this wiki page for definition of closure.

And this page for closure in Java 8: http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html

Also look at this Q&A: Closures in Java 7

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

There are many answers here but no answer helps to manipulate the css of :before or :after , not even the accepted one.

Here is how I propose to do it. Lets suppose your HTML is like this:

<div id="something">Test</div>

And then you are setting its :before in CSS and designing it like:

#something:before{
   content:"1st";
   font-size:20px;
   color:red;
}
#something{
  content:'1st';
}

Please notice I also set content attribute in element itself so that you can take it out easily later. Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:

Define a css with your required style on some class .activeS :

.activeS:before{
   color:green !important;
   font-size:30px !important;
 }

Now you can change :before style by adding the class to your :before element as follows:

<button id="changeBefore">Change</button>
<script>
    $('#changeBefore').click(function(){
        $('#something').addClass('activeS');
    });
</script>

If you just want to get content of :before, it can be done as:

<button id="getContent">Get Content</button>
<script>
    $('#getContent').click(function(){
        console.log($('#something').css('content'));//will print '1st'
    });
</script>

Ultimately if you want to dynamically change :before content by jQuery, You can achieve that as follows:

<button id="changeBefore">Change</button>
<script>
    var newValue = '22';//coming from somewhere
    var add = '<style>#something:before{content:"'+newValue+'"!important;}</style>';
    $('#changeBefore').click(function(){
        $('body').append(add);
    });
</script>

Clicking on above "changeBefore" button will change :before content of #something into '22' which is a dynamic value.

I hope it helps

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is Linux specific and is an environment variable pointing to directories where the dynamic loader should look for shared libraries.

Try to add the directory where your .dll is in the PATH variable. Windows will automatically look in the directories listet in this environment variable. LD_LIBRARY_PATH probably won't solve the problem (unless the JVM uses it - I do not know about that).

AssertNull should be used or AssertNotNull

The assertNotNull() method means "a passed parameter must not be null": if it is null then the test case fails.
The assertNull() method means "a passed parameter must be null": if it is not null then the test case fails.

String str1 = null;
String str2 = "hello";              

// Success.
assertNotNull(str2);

// Fail.
assertNotNull(str1);

// Success.
assertNull(str1);

// Fail.
assertNull(str2);

Could not open input file: composer.phar

First try this: dont use the php composer.phar [parameters] simply use composer [parameters] if this doesn't work for you than try the rest. Hope it helps.

Can I run CUDA on Intel's integrated graphics processor?

Intel HD Graphics is usually the on-CPU graphics chip in newer Core i3/i5/i7 processors.

As far as I know it doesn't support CUDA (which is a proprietary NVidia technology), but OpenCL is supported by NVidia, ATi and Intel.

MySql server startup error 'The server quit without updating PID file '

Simple....

Fix the 2002 MySQL Socket error

Fix the looming 2002 socket error – which is linking where MySQL places the socket and where OSX thinks it should be, MySQL puts it in /tmp and OSX looks for it in /var/mysql the socket is a type of file that allows mysql client/server communication.

sudo mkdir /var/mysql

sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

Well Done : )

This Help me A LOT! i took this guide from the guys on http://coolestguidesontheplanet.com/

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

Iif equivalent in C#

C# has the ? ternary operator, like other C-style languages. However, this is not perfectly equivalent to IIf(); there are two important differences.

To explain the first difference, the false-part argument for this IIf() call causes a DivideByZeroException, even though the boolean argument is True.

IIf(true, 1, 1/0)

IIf() is just a function, and like all functions all the arguments must be evaluated before the call is made. Put another way, IIf() does not short circuit in the traditional sense. On the other hand, this ternary expression does short-circuit, and so is perfectly fine:

(true)?1:1/0;

The other difference is IIf() is not type safe. It accepts and returns arguments of type Object. The ternary operator is type safe. It uses type inference to know what types it's dealing with. Note you can fix this very easily with your own generic IIF(Of T)() implementation, but out of the box that's not the way it is.

If you really want IIf() in C#, you can have it:

object IIf(bool expression, object truePart, object falsePart) 
{return expression?truePart:falsePart;}

or a generic/type-safe implementation:

T IIf<T>(bool expression, T truePart, T falsePart) 
{return expression?truePart:falsePart;}

On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new If() operator that works like C#'s ternary operator. It uses type inference to know what it's returning, and it really is an operator rather than a function. This means there's no issues from pre-evaluating expressions, even though it has function semantics.

How to increase the timeout period of web service in asp.net?

1 - You can set a timeout in your application :

var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite

It is in milliseconds.

2 - Also you can increase timeout value in httpruntime tag in web/app.config :

<configuration>
     <system.web>
          <httpRuntime executionTimeout="<<**seconds**>>" />
          ...
     </system.web>
</configuration>

For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source

Is it a bad practice to use an if-statement without curly braces?

I prefer using braces. Adding braces makes it easier to read and modify.

Here are some links for the use of braces:

How to do a deep comparison between 2 objects with lodash?

I took a stab a Adam Boduch's code to output a deep diff - this is entirely untested but the pieces are there:

function diff (obj1, obj2, path) {
    obj1 = obj1 || {};
    obj2 = obj2 || {};

    return _.reduce(obj1, function(result, value, key) {
        var p = path ? path + '.' + key : key;
        if (_.isObject(value)) {
            var d = diff(value, obj2[key], p);
            return d.length ? result.concat(d) : result;
        }
        return _.isEqual(value, obj2[key]) ? result : result.concat(p);
    }, []);
}

diff({ foo: 'lol', bar: { baz: true }}, {}) // returns ["foo", "bar.baz"]

What should be in my .gitignore for an Android Studio project?

To circumvent the import of all files, where Android Studio ignores the "Ignored Files" list, but still leverage Android Studio VCS, I did the following: This will use the "Ignored Files" list from Android Studio (after import! not during) AND avoid having to use the cumbersome way Tortoise SVN sets the svn:ignore list.

  1. Use the Tortoise SVN repository browser to create a new project folder directly in the repository.
  2. Use Tortoise SVN to checkout the new folder over the top of the folder you want to import. You will get a warning that the local folder is not empty. Ignore the warning. Now you have a versioned top level folder with unversioned content.
  3. Open your project from the local working directory. VCS should now be enabled automatically
  4. Set your file exceptions in File -> Settings -> Version Control -> Ignored Files
  5. Add files to SVN from Android Studio: select 'App' in Project Structure -> VCS -> Add to VCS (this will add all files, except "Ignored Files")
  6. Commit Changes

Going forward, "Ignored Files" will be ignored and you can still manage VCS from Android Studio.

Cheers, -Joost

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

The problem happens because in same hibernate session you are trying to save two objects with same identifier.There are two solutions:-

  1. This is happening because you have not configured your mapping.xml file correctly for id fields as below:-

    <id name="id">
      <column name="id" sql-type="bigint" not-null="true"/>
      <generator class="hibernateGeneratorClass"</generator>
    </id>
    
  2. Overload the getsession method to accept a Parameter like isSessionClear, and clear the session before returning the current session like below

    public static Session getSession(boolean isSessionClear) {
        if (session.isOpen() && isSessionClear) {
            session.clear();
            return session;
        } else if (session.isOpen()) {
            return session;
        } else {
            return sessionFactory.openSession();
        }
    }
    

This will cause existing session objects to be cleared and even if hibernate doesn't generate a unique identifier ,assuming you have configured your database properly for a primary key using something like Auto_Increment,it should work for you.

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

Eclipse Workspaces: What for and why?

The whole point of a workspace is to group a set of related projects together that usually make up an application. The workspace framework comes down to the eclipse.core.resources plugin and it naturally by design makes sense.

Projects have natures, builders are attached to specific projects and as you change resources in one project you can see in real time compile or other issues in projects that are in the same workspace. So the strategy I suggest is have different workspaces for different projects you work on but without a workspace in eclipse there would be no concept of a collection of projects and configurations and after all it's an IDE tool.

If that does not make sense ask how Net Beans or Visual Studio addresses this? It's the same theme. Maven is a good example, checking out a group of related maven projects into a workspace lets you develop and see errors in real time. If not a workspace what else would you suggest? An RCP application can be a different beast depending on what its used for but in the true IDE sense I don't know what would be a better solution than a workspace or context of projects. Just my thoughts. - Duncan

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

How to insert text at beginning of a multi-line selection in vi/Vim

This replaces the beginning of each line with "//":

:%s!^!//!

This replaces the beginning of each selected line (use visual mode to select) with "//":

:'<,'>s!^!//!

Note that gv (in normal mode) restores the last visual selection, this comes in handy from time to time.

How to add an image to the "drawable" folder in Android Studio?

My way of exporting/importing image assets. I use Sketch design.

Step 1. Sketch: export using Android preset

Sketch

Step 2. Finder: Go to the export folder > Cmd+C Finder

Step 3. Finder: Go to your project's /res folder > Cmd+V > Apply to all > Merge Finder

OK, the images are in your project now.

iPhone is not available. Please reconnect the device

After trying all of the previous answers, the only thing that worked for me iOS 14.2 was to run Xcode 12.2 beta, and then switch back to Xcode 12.0.1 production.

Convert Time DataType into AM PM Format:

Multiple functions, but this will give you what you need (tested on SQL Server 2008)

Edit: The following works not only for a time type, but for a datetime as well.

SELECT SUBSTRING(CONVERT(varchar(20),StartTime,22), 10, 11) AS Start, SUBSTRING(CONVERT(varchar(20),EndTime,22), 10, 11) AS End FROM [TableA];

Countdown timer in React

You have to setState every second with the seconds remaining (every time the interval is called). Here's an example:

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { time: {}, seconds: 5 };_x000D_
    this.timer = 0;_x000D_
    this.startTimer = this.startTimer.bind(this);_x000D_
    this.countDown = this.countDown.bind(this);_x000D_
  }_x000D_
_x000D_
  secondsToTime(secs){_x000D_
    let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
    let divisor_for_minutes = secs % (60 * 60);_x000D_
    let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
    let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
    let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
    let obj = {_x000D_
      "h": hours,_x000D_
      "m": minutes,_x000D_
      "s": seconds_x000D_
    };_x000D_
    return obj;_x000D_
  }_x000D_
_x000D_
  componentDidMount() {_x000D_
    let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
    this.setState({ time: timeLeftVar });_x000D_
  }_x000D_
_x000D_
  startTimer() {_x000D_
    if (this.timer == 0 && this.state.seconds > 0) {_x000D_
      this.timer = setInterval(this.countDown, 1000);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  countDown() {_x000D_
    // Remove one second, set state so a re-render happens._x000D_
    let seconds = this.state.seconds - 1;_x000D_
    this.setState({_x000D_
      time: this.secondsToTime(seconds),_x000D_
      seconds: seconds,_x000D_
    });_x000D_
    _x000D_
    // Check if we're at zero._x000D_
    if (seconds == 0) { _x000D_
      clearInterval(this.timer);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
      <div>_x000D_
        <button onClick={this.startTimer}>Start</button>_x000D_
        m: {this.state.time.m} s: {this.state.time.s}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
_x000D_
_x000D_

Cropping an UIImage

Looks a little bit strange but works great and takes into consideration image orientation:

var image:UIImage = ...

let img = CIImage(image: image)!.imageByCroppingToRect(rect)
image = UIImage(CIImage: img, scale: 1, orientation: image.imageOrientation)

How to select where ID in Array Rails ActiveRecord without exception

To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.

begin
  current_user.comments.find(ids)
rescue
  #do something in case of exception found
end

Here's more info on exceptions in ruby.

How to do a LIKE query with linq?

var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();

User can use this of like query in Linq and fill the student model.

How to write an ArrayList of Strings into a text file?

If you want to serialize the ArrayList object to a file so you can read it back in again later use ObjectOuputStream/ObjectInputStream writeObject()/readObject() since ArrayList implements Serializable. It's not clear to me from your question if you want to do this or just write each individual item. If so then Andrey's answer will do that.

How do I change a TCP socket to be non-blocking?

Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2), poll(2) or some other system calls available on your system.

See The C10K problem for the comparison of approaches to scalable IO multiplexing.

How do I define and use an ENUM in Objective-C?

This is how Apple does it for classes like NSString:

In the header file:

enum {
    PlayerStateOff,
    PlayerStatePlaying,
    PlayerStatePaused
};

typedef NSInteger PlayerState;

Refer to Coding Guidelines at http://developer.apple.com/

how to Call super constructor in Lombok

Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:

@AllArgsConstructor 
public class Parent {   
     private String a; 
}

public class Child extends Parent {
  private String b;

  @Builder
  public Child(String a, String b){
    super(a);
    this.b = b;   
  } 
} 

As a result you can then use the generated builder like this:

Child.builder().a("testA").b("testB").build(); 

The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.

I also found this works nicely with Spring Data JPA.

$(document).click() not working correctly on iPhone. jquery

Change this:

$(document).click( function () {

To this

$(document).on('click touchstart', function () {

Maybe this solution don't fit on your work and like described on the replies this is not the best solution to apply. Please, check another fixes from another users.

Why is my toFixed() function not working?

Your conversion data is response[25] and follow the below steps.

var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34

Setting Authorization Header of HttpClient

BaseWebApi.cs

public abstract class BaseWebApi
{
    //Inject HttpClient from Ninject
    private readonly HttpClient _httpClient;
    public BaseWebApi(HttpClient httpclient)
    {
        _httpClient = httpClient;
    }

    public async Task<TOut> PostAsync<TOut>(string method, object param, Dictionary<string, string> headers, HttpMethod httpMethod)
    {
        //Set url

        HttpResponseMessage response;
        using (var request = new HttpRequestMessage(httpMethod, url))
        {
            AddBody(param, request);
            AddHeaders(request, headers);
            response = await _httpClient.SendAsync(request, cancellationToken);
        }

        if(response.IsSuccessStatusCode)
        {
             return await response.Content.ReadAsAsync<TOut>();
        }
        //Exception handling
    }

    private void AddHeaders(HttpRequestMessage request, Dictionary<string, string> headers)
    {
        request.Headers.Accept.Clear();
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        if (headers == null) return;

        foreach (var header in headers)
        {
            request.Headers.Add(header.Key, header.Value);
        }
    }

    private static void AddBody(object param, HttpRequestMessage request)
    {
        if (param != null)
        {
            var content = JsonConvert.SerializeObject(param);
            request.Content = new StringContent(content);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }

SubWebApi.cs

public sealed class SubWebApi : BaseWebApi
{
    public SubWebApi(HttpClient httpClient) : base(httpClient) {}

    public async Task<StuffResponse> GetStuffAsync(int cvr)
    {
        var method = "get/stuff";
        var request = new StuffRequest 
        {
            query = "GiveMeStuff"
        }
        return await PostAsync<StuffResponse>(method, request, GetHeaders(), HttpMethod.Post);
    }
    private Dictionary<string, string> GetHeaders()
    {
        var headers = new Dictionary<string, string>();
        var basicAuth = GetBasicAuth();
        headers.Add("Authorization", basicAuth);
        return headers;
    }

    private string GetBasicAuth()
    {
        var byteArray = Encoding.ASCII.GetBytes($"{SystemSettings.Username}:{SystemSettings.Password}");
        var authString = Convert.ToBase64String(byteArray);
        return $"Basic {authString}";
    }
}

How do I pass multiple attributes into an Angular.js attribute directive?

The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.

Template:

<div example-directive example-number="99" example-function="exampleCallback()"></div>

Directive:

app.directive('exampleDirective ', function () {
    return {
        restrict: 'A',   // 'A' is the default, so you could remove this line
        scope: {
            callback : '&exampleFunction',
        },
        link: function (scope, element, attrs) {
            var num = scope.$eval(attrs.exampleNumber);
            console.log('number=',num);
            scope.callback();  // calls exampleCallback()
        }
    };
});

fiddle

If the value of attribute example-number will be hard-coded, I suggest using $eval once, and storing the value. Variable num will have the correct type (a number).

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

Repeat a task with a time delay?

Using kotlin and its Coroutine its quite easy, first declare a job in your class (better in your viewModel) like this:

private var repeatableJob: Job? = null

then when you want to create and start it do this:

repeatableJob = viewModelScope.launch {
    while (isActive) {
         delay(5_000)
         loadAlbums(iImageAPI, titleHeader, true)
    }
}
repeatableJob?.start()

and if you want to finish it:

repeatableJob?.cancel()

PS: viewModelScope is only available in view models, you can use other Coroutine scopes such as withContext(Dispatchers.IO)

More information: Here

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

Changing fonts in ggplot2

Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.

How to make this Header/Content/Footer layout using CSS?

Try This

<!DOCTYPE html>

<html>

<head>

<title>Sticky Header and Footer</title>

<style type="text/css">

/* Reset body padding and margins */

body {
    margin:0;

    padding:0;
}

/* Make Header Sticky */

#header_container {

    background:#eee;

    border:1px solid #666;

    height:60px;

    left:0;

    position:fixed;

    width:100%;

    top:0;
}

#header {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;
}

/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/

#container {

    margin:0 auto;

    overflow:auto;

    padding:80px 0;

    width:940px;

}

#content {

}

/* Make Footer Sticky */

#footer_container {

    background:#eee;

    border:1px solid #666;

    bottom:0;

    height:60px;

    left:0;

    position:fixed;

    width:100%;
}

#footer {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;

}

</style>

</head>

<body>

<!-- BEGIN: Sticky Header -->
<div id="header_container">

    <div id="header">
        Header Content
    </div>

</div>
<!-- END: Sticky Header -->

<!-- BEGIN: Page Content -->
<div id="container">

    <div id="content">

            content
        <br /><br />
            blah blah blah..
        ...
    </div>

</div>
<!-- END: Page Content -->

<!-- BEGIN: Sticky Footer -->
<div id="footer_container">

    <div id="footer">

        Footer Content

    </div>

</div>

<!-- END: Sticky Footer -->

</body>

</html>

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

When should I use UNSIGNED and SIGNED INT in MySQL?

If you know the type of numbers you are going to store, your can choose accordingly. In this case your have 'id' which can never be negative. So you can use unsigned int. Range of signed int: -n/2 to +n/2 Range of unsigned int: 0 to n So you have twice the number of positive numbers available. Choose accordingly.

"Cannot GET /" with Connect on Node.js

The easiest way to serve static files is to use "harp". It can be found here. You can serve up your files from the location you want via node is:

var harp = require("harp")
harp.server(projectPath [,args] [,callback])

Hope this helps.

Cross-browser bookmark/add to favorites JavaScript

function bookmark(title, url) {
  if (window.sidebar) { 
    // Firefox
    window.sidebar.addPanel(title, url, '');
  } 
  else if (window.opera && window.print) 
  { 
    // Opera
    var elem = document.createElement('a');
    elem.setAttribute('href', url);
    elem.setAttribute('title', title);
    elem.setAttribute('rel', 'sidebar');
    elem.click(); //this.title=document.title;
  } 
  else if (document.all) 
  { 
    // ie
    window.external.AddFavorite(url, title);
  }
}

I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!

C/C++ switch case with string

The best way is to use source generation, so that you could use

if (hash(str) == HASH("some string") ..

in your main source, and an pre-build step would convert the HASH(const char*) expression to an integer value.

allowing only alphabets in text box using java script

:::::HTML:::::

<input type="text" onkeypress="return lettersValidate(event)" />

Only letters no spaces

::::JS::::::::

// ===================== Allow - Only Letters ===============================================================

function lettersValidate(key) {
    var keycode = (key.which) ? key.which : key.keyCode;

    if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))  
    {     
           return true;    
    }
    else
    {
        return false;
    }
         
}
 

PHPExcel - set cell type before writing a value in it

The same way as you'd set the type (number format mask) after writing a value to it:

$objPHPExcel->getActiveSheet()
    ->getStyle('A1')
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_GENERAL
    );

or

$objPHPExcel->getActiveSheet()
    ->getStyle('A1')
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_TEXT
    );

Though "Number" isn't a valid format mask.

You can find a list of pre-defined format masks in Classes/PHPExcel/Style/NumberFormat.php or set the value to any valid Excel number format masking string.

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

An App ID with Identifier '' is not available. Please enter a different string

I had a similar issue. I check all settings in Xcode all were proper. When I tried to upload app using Archive it was giving an error

"An App ID with Identifier 'com.myappname.yyy' is not available. Please enter a different string".

Then after I tried to upload app via "Application Loader" and got success!

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. Click on Start menu > Programs > Microsoft Sql Server > Configuration Tools

  2. Select Sql Server Surface Area Configuration.

  3. Now click on Surface Area configuration for services and connections

  4. On the left pane of pop up window click on Remote Connections and Select Local and Remote connections radio button.

  5. Select Using both TCP/IP and named pipes radio button.

  6. click on apply and ok.

Now when try to connect to sql server using sql username and password u'll get the error mentioned below

Cannot connect to SQLEXPRESS.

ADDITIONAL INFORMATION:

Login failed for user 'username'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) ation To fix this error follow steps mentioned below

  1. connect to sql server using window authentication.

  2. Now right click on your server name at the top in left pane and select properties.

  3. Click on security and select sql server and windows authentication mode radio button.

  4. Click on OK.

  5. restart sql server servive by right clicking on server name and select restart.

Now your problem should be fixed and u'll be able to connect using sql server username and password.

Have fun. Ateev Gupta

java: ArrayList - how can I check if an index exists?

While you got a dozen suggestions about using the size of your list, which work for lists with linear entries, no one seemed to read your question.

If you add entries manually at different indexes none of these suggestions will work, as you need to check for a specific index.

Using if ( list.get(index) == null ) will not work either, as get() throws an exception instead of returning null.

Try this:

try {
    list.get( index );
} catch ( IndexOutOfBoundsException e ) {
    list.add( index, new Object() );
}

Here a new entry is added if the index does not exist. You can alter it to do something different.

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

Run a single migration file

Method 1 :

rake db:migrate:up VERSION=20080906120000

Method 2:

In Rails Console 1. Copy paste the migration class in console (say add_name_to_user.rb) 2. Then in console, type the following

Sharding.run_on_all_shards{AddNameToUser.up}

It is done!!

How to add icon to mat-icon-button

the above CSS can be written in SASS as follows (and it actually includes all button types, instead of just button.mat-button)

button,
a {
    &.mat-button,
    &.mat-raised-button,
    &.mat-flat-button,
    &.mat-stroked-button {
        .mat-icon {
            vertical-align: top;
            font-size: 1.25em;
        }
    }
}

How do I pass a class as a parameter in Java?

This kind of thing is not easy. Here is a method that calls a static method:

public static Object callStaticMethod(
    // class that contains the static method
    final Class<?> clazz,
    // method name
    final String methodName,
    // optional method parameters
    final Object... parameters) throws Exception{
    for(final Method method : clazz.getMethods()){
        if(method.getName().equals(methodName)){
            final Class<?>[] paramTypes = method.getParameterTypes();
            if(parameters.length != paramTypes.length){
                continue;
            }
            boolean compatible = true;
            for(int i = 0; i < paramTypes.length; i++){
                final Class<?> paramType = paramTypes[i];
                final Object param = parameters[i];
                if(param != null && !paramType.isInstance(param)){
                    compatible = false;
                    break;
                }

            }
            if(compatible){
                return method.invoke(/* static invocation */null,
                    parameters);
            }
        }
    }
    throw new NoSuchMethodException(methodName);
}

Update: Wait, I just saw the gwt tag on the question. You can't use reflection in GWT

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

Unix command-line JSON parser?

You could try jsawk as suggested in this answer.

Really you could whip up a quick python script to do this though.

Find a string between 2 known values

For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.

    public static string[] GetStringInBetween(string strBegin,
        string strEnd, string strSource,
        bool includeBegin, bool includeEnd)           
    {
        string[] result ={ "", "" };
        int iIndexOfBegin = strSource.IndexOf(strBegin);
        if (iIndexOfBegin != -1)
        {
            // include the Begin string if desired
            if (includeBegin)
                iIndexOfBegin -= strBegin.Length;
            strSource = strSource.Substring(iIndexOfBegin
                + strBegin.Length);
            int iEnd = strSource.IndexOf(strEnd);
            if (iEnd != -1)
            {
                // include the End string if desired
                if (includeEnd)
                    iEnd += strEnd.Length;
                result[0] = strSource.Substring(0, iEnd);
                // advance beyond this segment
                if (iEnd + strEnd.Length < strSource.Length)
                    result[1] = strSource.Substring(iEnd
                        + strEnd.Length);
            }
        }
        else
            // stay where we are
            result[1] = strSource;
        return result;
    }

How to check null objects in jQuery

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!

Instead try this:

if($("#something") !== null){
  // do something
}

or

if($("#something") === null){
  // don't do something
}

What's the difference between HEAD^ and HEAD~ in Git?

Simply put, for the first level of parentage (ancestry, inheritance, lineage, etc.) HEAD^ and HEAD~ both point to the same commit, which is (located) one parent above the HEAD (commit).

Furthermore, HEAD^ = HEAD^1 = HEAD~ = HEAD~1. But HEAD^^ != HEAD^2 != HEAD~2. Yet HEAD^^ = HEAD~2. Read on.

Beyond the first level of parentage, things get trickier, especially if the working branch/master branch has had merges (from other branches). There is also the matter of syntax with the caret, HEAD^^ = HEAD~2 (they're equivalent) BUT HEAD^^ != HEAD^2 (they're two different things entirely).

Each/the caret refers to the HEAD's first parent, which is why carets stringed together are equivalent to tilde expressions, because they refer to the first parent's (first parent's) first parents, etc., etc. based strictly on the number on connected carets or on the number following the tilde (either way, they both mean the same thing), i.e. stay with the first parent and go up x generations.

HEAD~2 (or HEAD^^) refers to the commit that is two levels of ancestry up/above the current commit (the HEAD) in the hierarchy, meaning the HEAD's grandparent commit.

HEAD^2, on the other hand, refers NOT to the first parent's second parent's commit, but simply to the second parent's commit. That is because the caret means the parent of the commit, and the number following signifies which/what parent commit is referred to (the first parent, in the case when the caret is not followed by a number [because it is shorthand for the number being 1, meaning the first parent]). Unlike the caret, the number that follows afterwards does not imply another level of hierarchy upwards, but rather it implies how many levels sideways, into the hierarchy, one needs to go find the correct parent (commit). Unlike the number in a tilde expression, it is only one parent up in the hierarchy, regardless of the number (immediately) proceeding the caret. Instead of upward, the caret's trailing number counts sideways for parents across the hierarchy [at a level of parents upwards that is equivalent to the number of consecutive carets].

So HEAD^3 is equal to the third parent of the HEAD commit (NOT the great-grandparent, which is what HEAD^^^ AND HEAD~3 would be...).

Fixed page header overlaps in-page anchors

You can do this with jQuery:

var offset = $('.target').offset();
var scrollto = offset.top - 50; // fixed_top_bar_height = 50px
$('html, body').animate({scrollTop:scrollto}, 0);

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Uncomment the line extension=php_mysql.dll in your "php.ini" file and restart Apache.

Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.

See more about installing MySQL extension in manual.

P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).

Validation of file extension before uploading file

check that if file is selected or not

       if (document.myform.elements["filefield"].value == "")
          {
             alert("You forgot to attach file!");
             document.myform.elements["filefield"].focus();
             return false;  
         }

check the file extension

  var res_field = document.myform.elements["filefield"].value;   
  var extension = res_field.substr(res_field.lastIndexOf('.') + 1).toLowerCase();
  var allowedExtensions = ['doc', 'docx', 'txt', 'pdf', 'rtf'];
  if (res_field.length > 0)
     {
          if (allowedExtensions.indexOf(extension) === -1) 
             {
               alert('Invalid file Format. Only ' + allowedExtensions.join(', ') + ' are allowed.');
               return false;
             }
    }

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

MAVEN_HOME, MVN_HOME or M2_HOME

I have solved same issue with following:

export M2_HOME=/usr/share/maven

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

Reading binary file and looping over each byte

This post itself is not a direct answer to the question. What it is instead is a data-driven extensible benchmark that can be used to compare many of the answers (and variations of utilizing new features added in later, more modern, versions of Python) that have been posted to this question — and should therefore be helpful in determining which has the best performance.

In a few cases I've modified the code in the referenced answer to make it compatible with the benchmark framework.

First, here are the results for what currently are the latest versions of Python 2 & 3:

Fastest to slowest execution speeds with 32-bit Python 2.7.16
  numpy version 1.16.5
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1                  Tcll (array.array) :   3.8943 secs, rel speed   1.00x,   0.00% slower (262.95 KiB/sec)
2  Vinay Sajip (read all into memory) :   4.1164 secs, rel speed   1.06x,   5.71% slower (248.76 KiB/sec)
3            codeape + iter + partial :   4.1616 secs, rel speed   1.07x,   6.87% slower (246.06 KiB/sec)
4                             codeape :   4.1889 secs, rel speed   1.08x,   7.57% slower (244.46 KiB/sec)
5               Vinay Sajip (chunked) :   4.1977 secs, rel speed   1.08x,   7.79% slower (243.94 KiB/sec)
6           Aaron Hall (Py 2 version) :   4.2417 secs, rel speed   1.09x,   8.92% slower (241.41 KiB/sec)
7                     gerrit (struct) :   4.2561 secs, rel speed   1.09x,   9.29% slower (240.59 KiB/sec)
8                     Rick M. (numpy) :   8.1398 secs, rel speed   2.09x, 109.02% slower (125.80 KiB/sec)
9                           Skurmedel :  31.3264 secs, rel speed   8.04x, 704.42% slower ( 32.69 KiB/sec)

Benchmark runtime (min:sec) - 03:26

Fastest to slowest execution speeds with 32-bit Python 3.8.0
  numpy version 1.17.4
  Test file size: 1,024 KiB
  100 executions, best of 3 repetitions

1  Vinay Sajip + "yield from" + "walrus operator" :   3.5235 secs, rel speed   1.00x,   0.00% slower (290.62 KiB/sec)
2                       Aaron Hall + "yield from" :   3.5284 secs, rel speed   1.00x,   0.14% slower (290.22 KiB/sec)
3         codeape + iter + partial + "yield from" :   3.5303 secs, rel speed   1.00x,   0.19% slower (290.06 KiB/sec)
4                      Vinay Sajip + "yield from" :   3.5312 secs, rel speed   1.00x,   0.22% slower (289.99 KiB/sec)
5      codeape + "yield from" + "walrus operator" :   3.5370 secs, rel speed   1.00x,   0.38% slower (289.51 KiB/sec)
6                          codeape + "yield from" :   3.5390 secs, rel speed   1.00x,   0.44% slower (289.35 KiB/sec)
7                                      jfs (mmap) :   4.0612 secs, rel speed   1.15x,  15.26% slower (252.14 KiB/sec)
8              Vinay Sajip (read all into memory) :   4.5948 secs, rel speed   1.30x,  30.40% slower (222.86 KiB/sec)
9                        codeape + iter + partial :   4.5994 secs, rel speed   1.31x,  30.54% slower (222.64 KiB/sec)
10                                        codeape :   4.5995 secs, rel speed   1.31x,  30.54% slower (222.63 KiB/sec)
11                          Vinay Sajip (chunked) :   4.6110 secs, rel speed   1.31x,  30.87% slower (222.08 KiB/sec)
12                      Aaron Hall (Py 2 version) :   4.6292 secs, rel speed   1.31x,  31.38% slower (221.20 KiB/sec)
13                             Tcll (array.array) :   4.8627 secs, rel speed   1.38x,  38.01% slower (210.58 KiB/sec)
14                                gerrit (struct) :   5.0816 secs, rel speed   1.44x,  44.22% slower (201.51 KiB/sec)
15                 Rick M. (numpy) + "yield from" :  11.8084 secs, rel speed   3.35x, 235.13% slower ( 86.72 KiB/sec)
16                                      Skurmedel :  11.8806 secs, rel speed   3.37x, 237.18% slower ( 86.19 KiB/sec)
17                                Rick M. (numpy) :  13.3860 secs, rel speed   3.80x, 279.91% slower ( 76.50 KiB/sec)

Benchmark runtime (min:sec) - 04:47

I also ran it with a much larger 10 MiB test file (which took nearly an hour to run) and got performance results which were comparable to those shown above.

Here's the code used to do the benchmarking:

from __future__ import print_function
import array
import atexit
from collections import deque, namedtuple
import io
from mmap import ACCESS_READ, mmap
import numpy as np
from operator import attrgetter
import os
import random
import struct
import sys
import tempfile
from textwrap import dedent
import time
import timeit
import traceback

try:
    xrange
except NameError:  # Python 3
    xrange = range


class KiB(int):
    """ KibiBytes - multiples of the byte units for quantities of information. """
    def __new__(self, value=0):
        return 1024*value


BIG_TEST_FILE = 1  # MiBs or 0 for a small file.
SML_TEST_FILE = KiB(64)
EXECUTIONS = 100  # Number of times each "algorithm" is executed per timing run.
TIMINGS = 3  # Number of timing runs.
CHUNK_SIZE = KiB(8)
if BIG_TEST_FILE:
    FILE_SIZE = KiB(1024) * BIG_TEST_FILE
else:
    FILE_SIZE = SML_TEST_FILE  # For quicker testing.

# Common setup for all algorithms -- prefixed to each algorithm's setup.
COMMON_SETUP = dedent("""
    # Make accessible in algorithms.
    from __main__ import array, deque, get_buffer_size, mmap, np, struct
    from __main__ import ACCESS_READ, CHUNK_SIZE, FILE_SIZE, TEMP_FILENAME
    from functools import partial
    try:
        xrange
    except NameError:  # Python 3
        xrange = range
""")


def get_buffer_size(path):
    """ Determine optimal buffer size for reading files. """
    st = os.stat(path)
    try:
        bufsize = st.st_blksize # Available on some Unix systems (like Linux)
    except AttributeError:
        bufsize = io.DEFAULT_BUFFER_SIZE
    return bufsize

# Utility primarily for use when embedding additional algorithms into benchmark.
VERIFY_NUM_READ = """
    # Verify generator reads correct number of bytes (assumes values are correct).
    bytes_read = sum(1 for _ in file_byte_iterator(TEMP_FILENAME))
    assert bytes_read == FILE_SIZE, \
           'Wrong number of bytes generated: got {:,} instead of {:,}'.format(
                bytes_read, FILE_SIZE)
"""

TIMING = namedtuple('TIMING', 'label, exec_time')

class Algorithm(namedtuple('CodeFragments', 'setup, test')):

    # Default timeit "stmt" code fragment.
    _TEST = """
        #for b in file_byte_iterator(TEMP_FILENAME):  # Loop over every byte.
        #    pass  # Do stuff with byte...
        deque(file_byte_iterator(TEMP_FILENAME), maxlen=0)  # Data sink.
    """

    # Must overload __new__ because (named)tuples are immutable.
    def __new__(cls, setup, test=None):
        """ Dedent (unindent) code fragment string arguments.
        Args:
          `setup` -- Code fragment that defines things used by `test` code.
                     In this case it should define a generator function named
                     `file_byte_iterator()` that will be passed that name of a test file
                     of binary data. This code is not timed.
          `test` -- Code fragment that uses things defined in `setup` code.
                    Defaults to _TEST. This is the code that's timed.
        """
        test =  cls._TEST if test is None else test  # Use default unless one is provided.

        # Uncomment to replace all performance tests with one that verifies the correct
        # number of bytes values are being generated by the file_byte_iterator function.
        #test = VERIFY_NUM_READ

        return tuple.__new__(cls, (dedent(setup), dedent(test)))


algorithms = {

    'Aaron Hall (Py 2 version)': Algorithm("""
        def file_byte_iterator(path):
            with open(path, "rb") as file:
                callable = partial(file.read, 1024)
                sentinel = bytes() # or b''
                for chunk in iter(callable, sentinel):
                    for byte in chunk:
                        yield byte
    """),

    "codeape": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                while True:
                    chunk = f.read(chunksize)
                    if chunk:
                        for b in chunk:
                            yield b
                    else:
                        break
    """),

    "codeape + iter + partial": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                for chunk in iter(partial(f.read, chunksize), b''):
                    for b in chunk:
                        yield b
    """),

    "gerrit (struct)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                fmt = '{}B'.format(FILE_SIZE)  # Reads entire file at once.
                for b in struct.unpack(fmt, f.read()):
                    yield b
    """),

    'Rick M. (numpy)': Algorithm("""
        def file_byte_iterator(filename):
            for byte in np.fromfile(filename, 'u1'):
                yield byte
    """),

    "Skurmedel": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                byte = f.read(1)
                while byte:
                    yield byte
                    byte = f.read(1)
    """),

    "Tcll (array.array)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                arr = array.array('B')
                arr.fromfile(f, FILE_SIZE)  # Reads entire file at once.
                for b in arr:
                    yield b
    """),

    "Vinay Sajip (read all into memory)": Algorithm("""
        def file_byte_iterator(filename):
            with open(filename, "rb") as f:
                bytes_read = f.read()  # Reads entire file at once.
            for b in bytes_read:
                yield b
    """),

    "Vinay Sajip (chunked)": Algorithm("""
        def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
            with open(filename, "rb") as f:
                chunk = f.read(chunksize)
                while chunk:
                    for b in chunk:
                        yield b
                    chunk = f.read(chunksize)
    """),

}  # End algorithms

#
# Versions of algorithms that will only work in certain releases (or better) of Python.
#
if sys.version_info >= (3, 3):
    algorithms.update({

        'codeape + iter + partial + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    for chunk in iter(partial(f.read, chunksize), b''):
                        yield from chunk
        """),

        'codeape + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while True:
                        chunk = f.read(chunksize)
                        if chunk:
                            yield from chunk
                        else:
                            break
        """),

        "jfs (mmap)": Algorithm("""
            def file_byte_iterator(filename):
                with open(filename, "rb") as f, \
                     mmap(f.fileno(), 0, access=ACCESS_READ) as s:
                    yield from s
        """),

        'Rick M. (numpy) + "yield from"': Algorithm("""
            def file_byte_iterator(filename):
            #    data = np.fromfile(filename, 'u1')
                yield from np.fromfile(filename, 'u1')
        """),

        'Vinay Sajip + "yield from"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    chunk = f.read(chunksize)
                    while chunk:
                        yield from chunk  # Added in Py 3.3
                        chunk = f.read(chunksize)
        """),

    })  # End Python 3.3 update.

if sys.version_info >= (3, 5):
    algorithms.update({

        'Aaron Hall + "yield from"': Algorithm("""
            from pathlib import Path

            def file_byte_iterator(path):
                ''' Given a path, return an iterator over the file
                    that lazily loads the file.
                '''
                path = Path(path)
                bufsize = get_buffer_size(path)

                with path.open('rb') as file:
                    reader = partial(file.read1, bufsize)
                    for chunk in iter(reader, bytes()):
                        yield from chunk
        """),

    })  # End Python 3.5 update.

if sys.version_info >= (3, 8, 0):
    algorithms.update({

        'Vinay Sajip + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk  # Added in Py 3.3
        """),

        'codeape + "yield from" + "walrus operator"': Algorithm("""
            def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
                with open(filename, "rb") as f:
                    while chunk := f.read(chunksize):
                        yield from chunk
        """),

    })  # End Python 3.8.0 update.update.


#### Main ####

def main():
    global TEMP_FILENAME

    def cleanup():
        """ Clean up after testing is completed. """
        try:
            os.remove(TEMP_FILENAME)  # Delete the temporary file.
        except Exception:
            pass

    atexit.register(cleanup)

    # Create a named temporary binary file of pseudo-random bytes for testing.
    fd, TEMP_FILENAME = tempfile.mkstemp('.bin')
    with os.fdopen(fd, 'wb') as file:
         os.write(fd, bytearray(random.randrange(256) for _ in range(FILE_SIZE)))

    # Execute and time each algorithm, gather results.
    start_time = time.time()  # To determine how long testing itself takes.

    timings = []
    for label in algorithms:
        try:
            timing = TIMING(label,
                            min(timeit.repeat(algorithms[label].test,
                                              setup=COMMON_SETUP + algorithms[label].setup,
                                              repeat=TIMINGS, number=EXECUTIONS)))
        except Exception as exc:
            print('{} occurred timing the algorithm: "{}"\n  {}'.format(
                    type(exc).__name__, label, exc))
            traceback.print_exc(file=sys.stdout)  # Redirect to stdout.
            sys.exit(1)
        timings.append(timing)

    # Report results.
    print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
            64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
    print('  numpy version {}'.format(np.version.full_version))
    print('  Test file size: {:,} KiB'.format(FILE_SIZE // KiB(1)))
    print('  {:,d} executions, best of {:d} repetitions'.format(EXECUTIONS, TIMINGS))
    print()

    longest = max(len(timing.label) for timing in timings)  # Len of longest identifier.
    ranked = sorted(timings, key=attrgetter('exec_time')) # Sort so fastest is first.
    fastest = ranked[0].exec_time
    for rank, timing in enumerate(ranked, 1):
        print('{:<2d} {:>{width}} : {:8.4f} secs, rel speed {:6.2f}x, {:6.2f}% slower '
              '({:6.2f} KiB/sec)'.format(
                    rank,
                    timing.label, timing.exec_time, round(timing.exec_time/fastest, 2),
                    round((timing.exec_time/fastest - 1) * 100, 2),
                    (FILE_SIZE/timing.exec_time) / KiB(1),  # per sec.
                    width=longest))
    print()
    mins, secs = divmod(time.time()-start_time, 60)
    print('Benchmark runtime (min:sec) - {:02d}:{:02d}'.format(int(mins),
                                                               int(round(secs))))

main()

VB.NET - How to move to next item a For Each Loop?

For Each I As Item In Items
    If I = x Then Continue For

    ' Do something
Next

What is a lambda expression in C++11?

Answers

Q: What is a lambda expression in C++11?

A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining.

Q: When would I use one?

A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you.

Q: What class of problem do they solve that wasn't possible prior to their introduction?

A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so)

Example of usage

auto x = [=](int arg1){printf("%i", arg1); };
void(*f)(int) = x;
f(1);
x(1);

Extras about lambdas, not covered by question. Ignore this section if you're not interest

1. Captured values. What you can to capture

1.1. You can reference to a variable with static storage duration in lambdas. They all are captured.

1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure).

[captureVar1,captureVar2](int arg1){}

1.3. You can capture be reference. & -- in this context mean reference, not pointers.

   [&captureVar1,&captureVar2](int arg1){}

1.4. It exists notation to capture all non-static vars by value, or by reference

  [=](int arg1){} // capture all not-static vars by value

  [&](int arg1){} // capture all not-static vars by reference

1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2

[=,&Param2](int arg1){} 

Capture all not-static vars by reference, but by value capture Param2

[&,Param2](int arg1){} 

2. Return type deduction

2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it.

[=](int arg1)->trailing_return_type{return trailing_return_type();}

If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions

3. Captured values. What you can not capture

3.1. You can capture only local vars, not member variable of the object.

4. ?onversions

4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer.

p.s.

  1. More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88

  2. In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members:

    auto toFloat = [](int value) { return float(value);};
    auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);};
    

How do I create directory if it doesn't exist to create a file?

You can use following code

  DirectoryInfo di = Directory.CreateDirectory(path);

How can I auto hide alert box after it showing it?

impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl

How can I use grep to find a word inside a folder?

The answer you selected is fine, and it works, but it isn't the correct way to do it, because:

grep -nr yourString* .

This actually searches the string "yourStrin" and "g" 0 or many times.

So the proper way to do it is:

grep -nr \w*yourString\w* .

This command searches the string with any character before and after on the current folder.

Python circular importing?

I was using the following:

from module import Foo

foo_instance = Foo()

but to get rid of circular reference I did the following and it worked:

import module.foo

foo_instance = foo.Foo()

Is there an opposite to display:none?

A true opposite to display: none there is not (yet).

But display: unset is very close and works in most cases.

From MDN (Mozilla Developer Network):

The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.

(source: https://developer.mozilla.org/docs/Web/CSS/unset)

Note also that display: revert is currently being developed. See MDN for details.

How to use regex in String.contains() method in Java

If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -

    private static final validPattern =   "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
    Pattern pattern = Pattern.compile(validPattern);
    Matcher matcher = pattern.matcher(inputString);
    System.out.print(matcher.find()); // should print true or false.

Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.

C++ Compare char array with string

Use strcmp() to compare the contents of strings:

if (strcmp(var1, "dev") == 0) {
}

Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

Showing percentages above bars on Excel column graph

You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.

Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.

Here is a working code I have written for you:

https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27

In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.

I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file): Percentage (%) = 100 x partial value / total value

It automatically calculates the total and pourcentage even if you add more categories.

I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:

var trace1 = {
    x: xValue, 
    y: data,
    type: 'bar',
    text: yValue,
    textposition: 'auto',
    hoverinfo: 'none',
    marker: {
    color: 'yellow',
    opacity: 0.6,
    line: {
      color: 'yellow',
      width: 1.5
    }
  }
};

It is rather self explanatory, the text is where you put the percentage.

Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:

final

I know it is an old post but I hope it helps people with the same problem !

Disclosure : I’m a developer of funfun

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

General sibling combinator

The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.

More info

Have nginx access_log and error_log log to STDOUT and STDERR of master process

In docker image of PHP-FPM, i've see such approach:

# cat /usr/local/etc/php-fpm.d/docker.conf
[global]
error_log = /proc/self/fd/2

[www]
; if we send this to /proc/self/fd/1, it never appears
access.log = /proc/self/fd/2

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Edit file: '/usr/share/phpmyadmin/libraries/sql.lib.php'

Replace: (count($analyzed_sql_results['select_expr'] == 1)

With: (count($analyzed_sql_results['select_expr']) == 1

this worked for me

Modifying the "Path to executable" of a windows service

You could also do it with PowerShell:

Get-WmiObject win32_service -filter "Name='My Service'" `
    | Invoke-WmiMethod -Name Change `
    -ArgumentList @($null,$null,$null,$null,$null, `
    "C:\Program Files (x86)\My Service\NewName.EXE")

Or:

Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\My Service" `
    -Name ImagePath -Value "C:\Program Files (x86)\My Service\NewName.EXE"

What is @RenderSection in asp.net MVC

If

(1) you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()

    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    @RenderSection("scripts", required: false)
</html>

(2) you have Contacts.cshtml

@section Scripts{
    <script type="text/javascript" src="~/lib/contacts.js"></script>

}
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

(3) you have About.cshtml

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.

    <html>
        <body><div>About<div>             
        </body>
        <script type="text/javascript" src="~/lib/layout.js"></script>
    </html>

if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.

<html>
    <body><div>About<div>             
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    <script type="text/javascript" src="~/lib/contacts.js"></script>
</html>

IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

How return error message in spring mvc @Controller

Here is an alternative. Create a generic exception that takes a status code and a message. Then create an exception handler. Use the exception handler to retrieve the information out of the exception and return to the caller of the service.

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()}
     *                method.
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

Then use an exception handler to retrieve the information and return it to the service caller.

@ControllerAdvice
public class ExceptionHandlerAdvice { 

    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        // log exception 
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }         
} 

Then create an exception when you need to.

throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");

Find Process Name by its Process ID

Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:

for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )

Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:

wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath

Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:

for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )

Check if my SSL Certificate is SHA1 or SHA2

I had to modify this slightly to be used on a Windows System. Here's the one-liner version for a windows box.

openssl.exe s_client -connect yoursitename.com:443 > CertInfo.txt && openssl x509 -text -in CertInfo.txt | find "Signature Algorithm" && del CertInfo.txt /F

Tested on Server 2012 R2 using http://iweb.dl.sourceforge.net/project/gnuwin32/openssl/0.9.8h-1/openssl-0.9.8h-1-bin.zip

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Full examples of using pySerial package

import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port

use https://pythonhosted.org/pyserial/ for more examples

TypeError: Missing 1 required positional argument: 'self'

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example -

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

python filter list of dictionaries based on key value

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

SQL keys, MUL vs PRI vs UNI

For Mul, this was also helpful documentation to me - http://grokbase.com/t/mysql/mysql/9987k2ew41/key-field-mul-newbie-question

"MUL means that the key allows multiple rows to have the same value. That is, it's not a UNIque key."

For example, let's say you have two models, Post and Comment. Post has a has_many relationship with Comment. It would make sense then for the Comment table to have a MUL key(Post id) because many comments can be attributed to the same Post.

Best way to make a shell script daemon?

If I had a script.sh and i wanted to execute it from bash and leave it running even when I want to close my bash session then I would combine nohup and & at the end.

example: nohup ./script.sh < inputFile.txt > ./logFile 2>&1 &

inputFile.txt can be any file. If your file has no input then we usually use /dev/null. So the command would be:

nohup ./script.sh < /dev/null > ./logFile 2>&1 &

After that close your bash session,open another terminal and execute: ps -aux | egrep "script.sh" and you will see that your script is still running at the background. Of cource,if you want to stop it then execute the same command (ps) and kill -9 <PID-OF-YOUR-SCRIPT>

Rails update_attributes without save?

For mass assignment of values to an ActiveRecord model without saving, use either the assign_attributes or attributes= methods. These methods are available in Rails 3 and newer. However, there are minor differences and version-related gotchas to be aware of.

Both methods follow this usage:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }

@user.attributes = { model: "Sierra", year: "2012", looks: "Sexy" }

Note that neither method will perform validations or execute callbacks; callbacks and validation will happen when save is called.

Rails 3

attributes= differs slightly from assign_attributes in Rails 3. attributes= will check that the argument passed to it is a Hash, and returns immediately if it is not; assign_attributes has no such Hash check. See the ActiveRecord Attribute Assignment API documentation for attributes=.

The following invalid code will silently fail by simply returning without setting the attributes:

@user.attributes = [ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ]

attributes= will silently behave as though the assignments were made successfully, when really, they were not.

This invalid code will raise an exception when assign_attributes tries to stringify the hash keys of the enclosing array:

@user.assign_attributes([ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ])

assign_attributes will raise a NoMethodError exception for stringify_keys, indicating that the first argument is not a Hash. The exception itself is not very informative about the actual cause, but the fact that an exception does occur is very important.

The only difference between these cases is the method used for mass assignment: attributes= silently succeeds, and assign_attributes raises an exception to inform that an error has occurred.

These examples may seem contrived, and they are to a degree, but this type of error can easily occur when converting data from an API, or even just using a series of data transformation and forgetting to Hash[] the results of the final .map. Maintain some code 50 lines above and 3 functions removed from your attribute assignment, and you've got a recipe for failure.

The lesson with Rails 3 is this: always use assign_attributes instead of attributes=.

Rails 4

In Rails 4, attributes= is simply an alias to assign_attributes. See the ActiveRecord Attribute Assignment API documentation for attributes=.

With Rails 4, either method may be used interchangeably. Failure to pass a Hash as the first argument will result in a very helpful exception: ArgumentError: When assigning attributes, you must pass a hash as an argument.

Validations

If you're pre-flighting assignments in preparation to a save, you might be interested in validating before save, as well. You can use the valid? and invalid? methods for this. Both return boolean values. valid? returns true if the unsaved model passes all validations or false if it does not. invalid? is simply the inverse of valid?

valid? can be used like this:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }.valid?

This will give you the ability to handle any validations issues in advance of calling save.

Set height 100% on absolute div

try adding

position:relative

to your body styles. Whenever positioning anything absolutely, you need one of the parent containers to be positioned relative as this will make the item be positioned absolute to the parent container that is relative.

As you had no relative elements, the css will not know what the div is absolutely position to and therefore will not know what to take 100% height of

For each row in an R dataframe

you can do something for a list object,

data("mtcars")
rownames(mtcars)
data <- list(mtcars ,mtcars, mtcars, mtcars);data

out1 <- NULL 
for(i in seq_along(data)) { 
  out1[[i]] <- data[[i]][rownames(data[[i]]) != "Volvo 142E", ] } 
out1

Or a data frame,

data("mtcars")
df <- mtcars
out1 <- NULL 
for(i in 1:nrow(df)) {
  row <- rownames(df[i,])
  # do stuff with row
  out1 <- df[rownames(df) != "Volvo 142E",]
  
}
out1 

error while loading shared libraries: libncurses.so.5:

I solved the issue using

ln -s libncursesw.so.5  /lib/x86_64-linux-gnu/libncursesw.so.6

on ubunutu 18.10

How to increase an array's length

Item[] newItemList = new  Item[itemList.length+1];
    //for loop to go thorough the list one by one
    for(int i=0; i< itemList.length;i++){
        //value is stored here in the new list from the old one
        newItemList[i]=itemList[i];
    }
    //all the values of the itemLists are stored in a bigger array named newItemList
    itemList=newItemList;

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

Fixed width buttons with Bootstrap

btn-group-justified and btn-group only work for static content but not on dynamically created buttons, and fixed with of button in css is not practical as it stay on the same width even all content are short.

My solution: put the same class to group of buttons then loop to all of them, get the width of the longest button and apply it to all

var bwidth=0
$("button.btnGroup").each(function(i,v){
    if($(v).width()>bwidth) bwidth=$(v).width();
});
$("button.btnGroup").width(bwidth);

Sample output here

How to compare two files in Notepad++ v6.6.8

Update:

  • for Notepad++ 7.5 and above use Compare v2.0.0
  • for Notepad++ 7.7 and above use Compare v2.0.0 for Notepad++ 7.7, if you need to install manually follow the description below, otherwise use "Plugin Admin".

I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).

So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.

I wrote a guideline how to install it:

  1. Start your Notepad++ as administrator mode.
  2. Press F1 to find out if your Notepad++ is 64bit or 32bit (86x), hence you need to download the correct plugin version. Download Compare-plugin 2.
  3. Unzip Compare-plugin in temporary folder.
  4. Import plugin from the temporary folder.
  5. The plugin should appear under Plugins menu.

Note:
It is also possible to drag and drop the plugin .dll file directly in plugin folder.
64bit: %programfiles%\Notepad++\plugins
32bit: %programfiles(x86)%\Notepad++\plugins

Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.

Disclaimer: the link of this guideline refer to my personal web site.

Calculate percentage saved between two numbers?

I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:

(1 - (oldNumber / newNumber)) * 100

So, the percentage difference from 30 to 40 is:

(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)

The percentage difference from 40 to 30 is:

(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)

In php, I use a function like this:

function calculatePercentage($oldFigure, $newFigure) {
        if (($oldFigure != 0) && ($newFigure != 0)) {
            $percentChange = (1 - $oldFigure / $newFigure) * 100;
        }
        else {
            $percentChange = null;
        }
        return $percentChange;
}

"Large data" workflows using pandas

Why Pandas ? Have you tried Standard Python ?

The use of standard library python. Pandas is subject to frequent updates, even with the recent release of the stable version.

Using the standard python library your code will always run.

One way of doing it is to have an idea of the way you want your data to be stored , and which questions you want to solve regarding the data. Then draw a schema of how you can organise your data (think tables) that will help you query the data, not necessarily normalisation.

You can make good use of :

  • list of dictionaries to store the data in memory (Think Amazon EC2) or disk, one dict being one row,
  • generators to process the data row after row to not overflow your RAM,
  • list comprehension to query your data,
  • make use of Counter, DefaultDict, ...
  • store your data on your hard drive using whatever storing solution you have chosen, json could be one of them.

Ram and HDD is becoming cheaper and cheaper with time and standard python 3 is widely available and stable.

The fondamental question you are trying to solve is "how to query large sets of data ?". The hdfs architecture is more or less what I am describing here (data modelling with data being stored on disk).

Let's say you have 1000 petabytes of data, there no way you will be able to store it in Dask or Pandas, your best chances here is to store it on disk and process it with generators.

Remove part of string after "."

If the string should be of fixed length, then substr from base R can be used. But, we can get the position of the . with regexpr and use that in substr

substr(a, 1, regexpr("\\.", a)-1)
#[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"   

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

I was able to fix it using the answer here: https://stackoverflow.com/a/32176571/1174024 But I have 150 modules. So I would have had to perform this step 150 times.

So I needed to do it a different way.

So first close the existing project, then Import it again, In the first step of the wizard choose "Gradle" project. Then the next step of the wizard has the Gradle project properties. Here it's going to ask you for, among other things, the Java SDK to use. The default will be "Project SDK". Do not use this default, instead hand pick your Java SDK from the list. Then finish the import.

Now the problem should go away.

How do I turn off the mysql password validation?

If you want to make exceptions, you can apply the following "hack". It requires a user with DELETE and INSERT privilege for mysql.plugin system table.

uninstall plugin validate_password;
SET PASSWORD FOR 'app' = PASSWORD('abcd');
INSTALL PLUGIN validate_password SONAME 'validate_password.so';

Bland security disclaimer: Consider, why you are making your password shorter or easier and perhaps consider replacing it with one that is more complex. However, I understand the "it's 3AM and just needs to work" moments, just make sure you don't build a system of hacks, lest you yourself be hacked

Difference between checkout and export in SVN

svn export simply extracts all the files from a revision and does not allow revision control on it. It also does not litter each directory with .svn directories.

svn checkout allows you to use version control in the directory made, e.g. your standard commands such as svn update and svn commit.

Center an element with "absolute" position and undefined width in CSS?

This is a trick I figured out for getting a DIV to float exactly in the center of a page. It is really ugly of course, but it works in all browsers.

Dots and Dashes

<div style="border: 5 dashed red;position:fixed;top:0;bottom:0;left:0;right:0;padding:5">
    <table style="position:fixed;" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="width:200;border: 5 dashed green;padding:10">
                    Perfectly Centered Content
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

Cleaner

Wow, those five years just flew by, didn't they?

<div style="position:fixed;top:0px;bottom:0px;left:0px;right:0px;padding:5px">
    <table style="position:fixed" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="padding:10px">
                    <img src="Happy.PM.png">
                    <h2>Stays in the Middle</h2>
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

As postman chrome app has deprecated so, Postman Native app is available to support native plateforms. You can install Postman on Linux/Ubuntu via the Snap store using the command in terminal.

$ snap install postman

After successful installation you can find this in your applications list.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Session class has been removed on SDK 4.0. The login magement is done through the class LoginManager. So:

mLoginManager = LoginManager.getInstance();
mLoginManager.logOut();

As the reference Upgrading to SDK 4.0 says:

Session Removed - AccessToken, LoginManager and CallbackManager classes supercede and replace functionality in the Session class.

Set style for TextView programmatically

I have only tested with EditText but you can use the method

public void setBackgroundResource (int resid)

to apply a style defined in an XML file.

Sine this method belongs to View I believe it will work with any UI element.

regards.

How to use enums in C++

If we want the strict type safety and scoped enum, using enum class is good in C++11.

If we had to work in C++98, we can using the advice given by InitializeSahib,San to enable the scoped enum.

If we also want the strict type safety, the follow code can implement somthing like enum.

#include <iostream>
class Color
{
public:
    static Color RED()
    {
        return Color(0);
    }
    static Color BLUE()
    {
        return Color(1);
    }
    bool operator==(const Color &rhs) const
    {
        return this->value == rhs.value;
    }
    bool operator!=(const Color &rhs) const
    {
        return !(*this == rhs);
    }

private:
    explicit Color(int value_) : value(value_) {}
    int value;
};

int main()
{
    Color color = Color::RED();
    if (color == Color::RED())
    {
        std::cout << "red" << std::endl;
    }
    return 0;
}

The code is modified from the class Month example in book Effective C++ 3rd: Item 18

Parsing CSV / tab-delimited txt file with Python

Start by turning the text into a list of lists. That will take care of the parsing part:

lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))

The rest can be done with indexed lookups:

d = dict()
key = lol[6][0]      # cell A7
value = lol[6][3]    # cell D7
d[key] = value       # add the entry to the dictionary
 ...

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

Setting the User-Agent header for a WebClient request

As a supplement to the other answers, here is Microsoft's guidance for user agent strings for its browsers. The user agent strings differ by browser (Internet Explorer and Edge) and operating system (Windows 7, 8, 10 and Windows Phone).

For example, here is the user agent string for Internet Explorer 11 on Windows 10:

Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko 

and for Internet Explorer for Windows Phone 8.1 Update:

Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537

Templates are given for the user agent strings for the Edge browser for Desktop, Mobile and WebView. See this answer for some Edge user agent string examples.

Finally, another page on MSDN provides guidance for IE11 on older desktop operating systems.

IE11 on Windows 8.1:

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

and IE11 on Windows 7:

Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko

How to specify a port to run a create-react-app based project?

How about giving the port number while invoking the command without need to change anything in your application code or environment files? That way it is possible running and serving same code base from several different ports.

like:

$ export PORT=4000 && npm start

You can put the port number you like in place of the example value 4000 above.

Array.Add vs +=

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation

$arr.Count
5

If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

Comparing boxed Long values 127 and 128

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

 For example:
    If we set java.lang.Integer.IntegerCache.high=500;
    then values from -128 to 500 will get cached and 

    Integer a=498;
    Integer b=499;
    System.out.println(a==b)

    Output will be "true".

Float and Double objects never gets cached.

Character will get cache from 0 to 127

You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

1) type cast both objects into primitive values and compare

    (long)val3 == (long)val4

2) read value of object and compare

    val3.longValue() == val4.longValue()

3) Use equals() method on object comparison.

    val3.equals(val4);  

Running code in main thread from another thread

for Kotlin, you can use Anko corountines:

update

doAsync {
   ...
}

deprecated

async(UI) {
    // Code run on UI thread
    // Use ref() instead of this@MyActivity
}

How is Pythons glob.glob ordered?

Order is arbitrary, but you can sort them yourself

If you want sorted by name:

sorted(glob.glob('*.png'))

sorted by modification time:

import os
sorted(glob.glob('*.png'), key=os.path.getmtime)

sorted by size:

import os
sorted(glob.glob('*.png'), key=os.path.getsize)

etc.

Find all zero-byte files in directory and subdirectories

No, you don't have to bother grep.

find $dir -size 0 ! -name "*.xml"

When to use in vs ref vs out

You're correct in that, semantically, ref provides both "in" and "out" functionality, whereas out only provides "out" functionality. There are some things to consider:

  1. out requires that the method accepting the parameter MUST, at some point before returning, assign a value to the variable. You find this pattern in some of the key/value data storage classes like Dictionary<K,V>, where you have functions like TryGetValue. This function takes an out parameter that holds what the value will be if retrieved. It wouldn't make sense for the caller to pass a value into this function, so out is used to guarantee that some value will be in the variable after the call, even if it isn't "real" data (in the case of TryGetValue where the key isn't present).
  2. out and ref parameters are marshaled differently when dealing with interop code

Also, as an aside, it's important to note that while reference types and value types differ in the nature of their value, every variable in your application points to a location of memory that holds a value, even for reference types. It just happens that, with reference types, the value contained in that location of memory is another memory location. When you pass values to a function (or do any other variable assignment), the value of that variable is copied into the other variable. For value types, that means that the entire content of the type is copied. For reference types, that means that the memory location is copied. Either way, it does create a copy of the data contained in the variable. The only real relevance that this holds deals with assignment semantics; when assigning a variable or passing by value (the default), when a new assignment is made to the original (or new) variable, it does not affect the other variable. In the case of reference types, yes, changes made to the instance are available on both sides, but that's because the actual variable is just a pointer to another memory location; the content of the variable--the memory location--didn't actually change.

Passing with the ref keyword says that both the original variable and the function parameter will actually point to the same memory location. This, again, affects only assignment semantics. If a new value is assigned to one of the variables, then because the other points to the same memory location the new value will be reflected on the other side.

How to assign from a function which returns more than one value?

(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...] like this:

library(gsubfn)  # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()

If you only need the first or second component these all work too:

list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()

(Of course, if you only needed one value then functionReturningTwoValues()[[1]] or functionReturningTwoValues()[[2]] would be sufficient.)

See the cited r-help thread for more examples.

(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with :

myfun <- function() list(a = 1, b = 2)

list[a, b] <- myfun()
a + b

# same
with(myfun(), a + b)

(3) attach Another alternative is attach:

attach(myfun())
a + b

ADDED: with and attach

stop service in android

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  //startService(myService);
  stopService(myService);

then the method onDestroy() in the service is called:

  @Override
    public void onDestroy() {

        Log.i(TAG, "onCreate() , service stopped...");
    }

Here is a complete example including how to stop the service.

Min / Max Validator in Angular 2 Final

I found a library implementing a lot of custom validators - ng2-validation - that can be used with template-driven forms (attribute directives). Example:

<input type="number" [(ngModel)]="someNumber" name="someNumber" #field="ngModel" [range]="[10, 20]"/>
<p *ngIf="someNumber.errors?.range">Must be in range</p>

How to convert an XML file to nice pandas dataframe?

You can easily use xml (from the Python standard library) to convert to a pandas.DataFrame. Here's what I would do (when reading from a file replace xml_data with the name of your file or file object):

import pandas as pd
import xml.etree.ElementTree as ET
import io

def iter_docs(author):
    author_attr = author.attrib
    for doc in author.iter('document'):
        doc_dict = author_attr.copy()
        doc_dict.update(doc.attrib)
        doc_dict['data'] = doc.text
        yield doc_dict

xml_data = io.StringIO(u'''\
<author type="XXX" language="EN" gender="xx" feature="xx" web="foobar.com">
    <documents count="N">
        <document KEY="e95a9a6c790ecb95e46cf15bee517651" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="bc360cfbafc39970587547215162f0db" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="19e71144c50a8b9160b3f0955e906fce" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="21d4af9021a174f61b884606c74d9e42" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="28a45eb2460899763d709ca00ddbb665" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="a0c0712a6a351f85d9f5757e9fff8946" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="626726ba8d34d15d02b6d043c55fe691" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="2cb473e0f102e2e4a40aa3006e412ae4" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...] [...]
]]>
        </document>
    </documents>
</author>
''')

etree = ET.parse(xml_data) #create an ElementTree object 
doc_df = pd.DataFrame(list(iter_docs(etree.getroot())))

If there are multiple authors in your original document or the root of your XML is not an author, then I would add the following generator:

def iter_author(etree):
    for author in etree.iter('author'):
        for row in iter_docs(author):
            yield row

and change doc_df = pd.DataFrame(list(iter_docs(etree.getroot()))) to doc_df = pd.DataFrame(list(iter_author(etree)))

Have a look at the ElementTree tutorial provided in the xml library documentation.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

java.lang.IllegalStateException: The specified child already has a parent

I solved it by setting attachToRoot of inflater.inflate() to false.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_overview, container, false);
    return view;
}

Deleting an object in java?

Yea, java is Garbage collected, it will delete the memory for you.

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How do I Search/Find and Replace in a standard string?

I believe this would work. It takes const char*'s as a parameter.

//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
   //ASSERT(find != NULL);
   //ASSERT(replace != NULL);
   size_t findLen = strlen(find);
   size_t replaceLen = strlen(replace);
   size_t pos = 0;

   //search for the next occurrence of find within source
   while ((pos = source.find(find, pos)) != std::string::npos)
   {
      //replace the found string with the replacement
      source.replace( pos, findLen, replace );

      //the next line keeps you from searching your replace string, 
      //so your could replace "hello" with "hello world" 
      //and not have it blow chunks.
      pos += replaceLen; 
   }
}