Programs & Examples On #Autowired

Autowiring is a DI container feature where the dependencies are automatically looked for according to some criteria.

No matching bean of type ... found for dependency

IF this is only occurring on deployments, be sure that you have the dependency of the package you are referencing in the .war. For instance, this was working locally on my machine, with debug configurations working fine, but after deploying to Amazon's Elastic Beanstalk , I received this error and noticed one of the dependencies was not bundled in the .war package.

Is there a way to @Autowire a bean that requires constructor arguments?

Well, from time to time I run into the same question. As far as I know, one cannot do that when one wants to add dynamic parameters to the constructor. However, the factory pattern may help.

public interface MyBean {
    // here be my fancy stuff
}

public interface MyBeanFactory {
    public MyBean getMyBean(/* bean parameters */);
}

@Component
public class MyBeanFactoryImpl implements MyBeanFactory {
    @Autowired
    WhateverIWantToInject somethingInjected;

    public MyBean getMyBean(/* params */) {
        return new MyBeanImpl(/* params */);
    }

    private class MyBeanImpl implements MyBean {
        public MyBeanImpl(/* params */) {
            // let's do whatever one has to
        }
    }
}

@Component
public class MyConsumerClass {
    @Autowired
    private MyBeanFactory beanFactory;

    public void myMethod() {
        // here one has to prepare the parameters
        MyBean bean = beanFactory.getMyBean(/* params */);
    }
}

Now, MyBean is not a spring bean per se, but it is close enough. Dependency Injection works, although I inject the factory and not the bean itself - one has to inject a new factory on top of his own new MyBean implementation if one wants to replace it.

Further, MyBean has access to other beans - because it may have access to the factory's autowired stuff.

And one might apparently want to add some logic to the getMyBean function, which is extra effort I allow, but unfortunately I have no better solution. Since the problem usually is that the dynamic parameters come from an external source, like a database, or user interaction, therefore I must instantiate that bean only in mid-run, only when that info is readily available, so the Factory should be quite adequate.

Requested bean is currently in creation: Is there an unresolvable circular reference?

@Resource annotation on field level also could be used to declare look up at runtime

@Autowired - No qualifying bean of type found for dependency

I had this happen because I added an autowired dependency to my service class but forgot to add it to the injected mocks in my service unit test.

The unit test exception appeared to report a problem in the service class when the problem was actually in the unit test. In retrospect, the error message told me exactly what the problem was.

How do I mock an autowired @Value field in Spring with Mockito?

You can use this magic Spring Test annotation :

@TestPropertySource(properties = { "my.spring.property=20" }) 

see org.springframework.test.context.TestPropertySource

For example, this is the test class :

@ContextConfiguration(classes = { MyTestClass.Config.class })
@TestPropertySource(properties = { "my.spring.property=20" })
public class MyTestClass {

  public static class Config {
    @Bean
    MyClass getMyClass() {
      return new MyClass ();
    }
  }

  @Resource
  private MyClass myClass ;

  @Test
  public void myTest() {
   ...

And this is the class with the property :

@Component
public class MyClass {

  @Value("${my.spring.property}")
  private int mySpringProperty;
   ...

@Autowired and static method

This builds upon @Pavel's answer, to solve the possibility of Spring context not being initialized when accessing from the static getBean method:

@Component
public class Spring {
  private static final Logger LOG = LoggerFactory.getLogger (Spring.class);

  private static Spring spring;

  @Autowired
  private ApplicationContext context;

  @PostConstruct
  public void registerInstance () {
    spring = this;
  }

  private Spring (ApplicationContext context) {
    this.context = context;
  }

  private static synchronized void initContext () {
    if (spring == null) {
      LOG.info ("Initializing Spring Context...");
      ApplicationContext context = new AnnotationConfigApplicationContext (io.zeniq.spring.BaseConfig.class);
      spring = new Spring (context);
    }
  }

  public static <T> T getBean(String name, Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(name, className);
  }

  public static <T> T getBean(Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(className);
  }

  public static AutowireCapableBeanFactory getBeanFactory() throws IllegalStateException {
    initContext();
    return spring.context.getAutowireCapableBeanFactory ();
  }
}

The important piece here is the initContext method. It ensures that the context will always get initialized. But, do note that initContext will be a point of contention in your code as it is synchronized. If your application is heavily parallelized (for eg: the backend of a high traffic site), this might not be a good solution for you.

intellij incorrectly saying no beans of type found for autowired repository

What you need to do is add

@ComponentScan("package/include/your/annotation/component") in AppConfiguration.java.

Since I think your AppConfiguraion.java's package is deeper than your annotation component (@Service, @Component...)'s package,

such as "package/include/your/annotation/component/deeper/config".

How does autowiring work in Spring?

The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies. When you annotate class with appropriate annotation (e.g. @Service) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the new keyword) in unit tests when you don't want to load the whole spring context.

Spring can you autowire inside an abstract class?

In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:

public abstract class EO {
    @Autowired
    protected SmsNotificationService smsNotificationService;
    @Autowired
    protected SendEmailService sendEmailService;
    ...
    protected abstract void executeOperation(GenericMessage gMessage);
}

public final class OperationsExecutor {
    public enum OperationsType {
        ENROLL, CAMPAIGN
    }

    private OperationsExecutor() {
    }

    public static Object delegateOperation(OperationsType type, Object obj) 
    {
        switch(type) {
            case ENROLL:
                if (obj == null) {
                    return new EnrollOperation();
                }
                return EnrollOperation.validateRequestParams(obj);
            case CAMPAIGN:
                if (obj == null) {
                    return new CampaignOperation();
                }
                return CampaignOperation.validateRequestParams(obj);
            default:
                throw new IllegalArgumentException("OperationsType not supported.");
        }
    }
}

@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
    @Override
    public void executeOperation(GenericMessage genericMessage) {
        LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
    }
}

Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)** annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.

<context:annotation-config />
<context:component-scan base-package="com.xyz" />

I also tried these other references to find a solution:

  1. http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.WqF5pJPwaAN
  2. http://forum.spring.io/forum/spring-projects/container/46815-problem-with-autowired-in-abstract-class
  3. https://github.com/cavallefano/Abstract-Factory-Pattern-Spring-Annotation
  4. http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
  5. https://www.madbit.org/blog/programming/1074/1074/#sthash.XEJXdIR5.dpbs
  6. Using abstract factory with Spring framework
  7. Spring Autowiring not working for Abstract classes
  8. Inject spring dependency in abstract super class
  9. Spring and Abstract class - injecting properties in abstract classes
    1. Spring autowire dependency defined in an abstract class

Please try using **@Configurable(dependencyCheck = true)** and update this post, I might try helping you if you face any problems.

@Resource vs @Autowired

In spring pre-3.0 it doesn't matter which one.

In spring 3.0 there's support for the standard (JSR-330) annotation @javax.inject.Inject - use it, with a combination of @Qualifier. Note that spring now also supports the @javax.inject.Qualifier meta-annotation:

@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}

So you can have

<bean class="com.pkg.SomeBean">
   <qualifier type="YourQualifier"/>
</bean>

or

@YourQualifier
@Component
public class SomeBean implements Foo { .. }

And then:

@Inject @YourQualifier private Foo foo;

This makes less use of String-names, which can be misspelled and are harder to maintain.


As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:

  • @Resource allows you to specify a name of the injected bean
  • @Autowired allows you to mark it as non-mandatory.

Spring: @Component versus @Bean

Additional Points from above answers

Let’s say we got a module which is shared in multiple apps and it contains a few services. Not all are needed for each app.

If use @Component on those service classes and the component scan in the application,

we might end up detecting more beans than necessary

In this case, you either had to adjust the filtering of the component scan or provide the configuration that even the unused beans can run. Otherwise, the application context won’t start.

In this case, it is better to work with @Bean annotation and only instantiate those beans,

which are required individually in each app

So, essentially, use @Bean for adding third-party classes to the context. And @Component if it is just inside your single application.

Understanding Spring @Autowired usage

Nothing in the example says that the "classes implementing the same interface". MovieCatalog is a type and CustomerPreferenceDao is another type. Spring can easily tell them apart.

In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".

What the examples show is various ways that you can use to inject beans into fields, methods and constructors.

The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:

This autowiring will fail:

 @Autowired
 public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }

Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier:

 @Autowired
 public void prepare( @Qualifier("bean1") Interface1 bean1,
     @Qualifier("bean2")  Interface1 bean2 ) { ... }

Using Spring 3 autowire in a standalone Java application

I case you are running SpringBoot:

I just had the same problem, that I could not Autowire one of my services from the static main method.

See below an approach in case you are relying on SpringApplication.run:

@SpringBootApplication
public class PricingOnlineApplication {

    @Autowired
    OrchestratorService orchestratorService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
        PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);

        application.start();
    }

    private void start() {
        orchestratorService.performPricingRequest(null);
    }

}

I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

Exclude subpackages from Spring autowiring?

This works in Spring 3.0.5. So, I would think it would work in 3.1

<context:component-scan base-package="com.example">  
    <context:exclude-filter type="aspectj" expression="com.example.dontscanme.*" />  
</context:component-scan> 

Injecting @Autowired private field during testing

Sometimes you can refactor your @Component to use constructor or setter based injection to setup your testcase (you can and still rely on @Autowired). Now, you can create your test entirely without a mocking framework by implementing test stubs instead (e.g. Martin Fowler's MailServiceStub):

@Component
public class MyLauncher {

    private MyService myService;

    @Autowired
    MyLauncher(MyService myService) {
        this.myService = myService;
    }

    // other methods
}

public class MyServiceStub implements MyService {
    // ...
}

public class MyLauncherTest
    private MyLauncher myLauncher;
    private MyServiceStub myServiceStub;

    @Before
    public void setUp() {
        myServiceStub = new MyServiceStub();
        myLauncher = new MyLauncher(myServiceStub);
    }

    @Test
    public void someTest() {

    }
}

This technique especially useful if the test and the class under test is located in the same package because then you can use the default, package-private access modifier to prevent other classes from accessing it. Note that you can still have your production code in src/main/java but your tests in src/main/test directories.


If you like Mockito then you will appreciate the MockitoJUnitRunner. It allows you to do "magic" things like @Manuel showed you:

@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest
    @InjectMocks
    private MyLauncher myLauncher; // no need to call the constructor

    @Mock
    private MyService myService;

    @Test
    public void someTest() {

    }
}

Alternatively, you can use the default JUnit runner and call the MockitoAnnotations.initMocks() in a setUp() method to let Mockito initialize the annotated values. You can find more information in the javadoc of @InjectMocks and in a blog post that I have written.

Can you use @Autowired with static fields?

You can achieve this using XML notation and the MethodInvokingFactoryBean. For an example look here.

private static StaticBean staticBean;

public void setStaticBean(StaticBean staticBean) {
   StaticBean.staticBean = staticBean;
}

You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.

Note testing can also be more difficult with this approach.

Why is my Spring @Autowired field null?

The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.

The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.

The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.

I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking

Inject your beans

The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:

@Controller
public class MileageFeeController {

    @Autowired
    private MileageFeeCalculator calc;

    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        return calc.mileageCharge(miles);
    }
}

If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.

Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean

Use @Configurable

If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.

@Service
@Configurable
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService;

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile());
    }
}

Tag that works by using @Configurable on the service object: working-configurable

Manual bean lookup: not recommended

This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.

To do this, you need a class to which Spring can give a reference to the ApplicationContext object:

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;   
    }

    public static ApplicationContext getContext() {
        return context;
    }
}

Then your legacy code can call getContext() and retrieve the beans it needs:

@Controller
public class MileageFeeController {    
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
        return calc.mileageCharge(miles);
    }
}

Tag that works by manually looking up the service object in the Spring context: working-manual-lookup

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

Better use @Inject all the time. Because it is java configuration approach(provided by sun) which makes our application agnostic to the framework. So if you spring also your classes will work.

If you use @Autowired it will works only with spring because @Autowired is spring provided annotation.

Injection of autowired dependencies failed;

Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

UTF-8 encoding in JSP page

Page encoding or anything else do not matter a lot. ISO-8859-1 is a subset of UTF-8, therefore you never have to convert ISO-8859-1 to UTF-8 because ISO-8859-1 is already UTF-8,a subset of UTF-8 but still UTF-8. Plus, all that do not mean a thing if You have a double encoding somewhere. This is my "cure all" recipe for all things encoding and charset related:

        String myString = "heartbroken ð";

//String is double encoded, fix that first.

                myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String cleanedText = StringEscapeUtils.unescapeJava(myString);
                byte[] bytes = cleanedText.getBytes(StandardCharsets.UTF_8);
                String text = new String(bytes, StandardCharsets.UTF_8);
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);
                decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                CharsetEncoder encoder = charset.newEncoder();
                encoder.onMalformedInput(CodingErrorAction.IGNORE);
                encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                try {
                    // The new ByteBuffer is ready to be read.
                    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
                    // The new ByteBuffer is ready to be read.
                    CharBuffer cbuf = decoder.decode(bbuf);
                    String str = cbuf.toString();
                } catch (CharacterCodingException e) {
                    logger.error("Error Message if you want to");

                } 

C++ multiline string literal

Just to elucidate a bit on @emsr's comment in @unwind's answer, if one is not fortunate enough to have a C++11 compiler (say GCC 4.2.1), and one wants to embed the newlines in the string (either char * or class string), one can write something like this:

const char *text =
  "This text is pretty long, but will be\n"
  "concatenated into just a single string.\n"
  "The disadvantage is that you have to quote\n"
  "each part, and newlines must be literal as\n"
  "usual.";

Very obvious, true, but @emsr's short comment didn't jump out at me when I read this the first time, so I had to discover this for myself. Hopefully, I've saved someone else a few minutes.

White space at top of page

This particular answer shows that h1 elements have an implicit margin-top that can cause the whitespace

https://stackoverflow.com/a/20021854/2129219

The suggestion to remove it is helpful, and certainly eye opening to how this is happening

h1 { margin-top: 0; }

How to use ESLint with Jest

ESLint supports this as of version >= 4:

/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;

module.exports = {
  extends: "eslint:recommended",
  env: {
    es6: true
  },
  overrides: [
    {
      files: [
        "**/*.test.js"
      ],
      env: {
        jest: true // now **/*.test.js files' env has both es6 *and* jest
      },
      // Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
      // "extends": ["plugin:jest/recommended"]
      plugins: ["jest"],
      rules: {
        "jest/no-disabled-tests": "warn",
        "jest/no-focused-tests": "error",
        "jest/no-identical-title": "error",
        "jest/prefer-to-have-length": "warn",
        "jest/valid-expect": "error"
      }
    }
  ],
};

Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

Typescript: React event types

For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState here's my solution:

const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);

const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
    setAnchorElement(event.currentTarget);
};

Rails - passing parameters in link_to

First of all, link_to is a html tag helper, its second argument is the url, followed by html_options. What you would like is to pass account_id as a url parameter to the path. If you have set up named routes correctly in routes.rb, you can use path helpers.

link_to "+ Service", new_my_service_path(:account_id => acct.id)

I think the best practice is to pass model values as a param nested within :

link_to "+ Service", new_my_service_path(:my_service => { :account_id => acct.id })

# my_services_controller.rb
def new
  @my_service = MyService.new(params[:my_service])
end

And you need to control that account_id is allowed for 'mass assignment'. In rails 3 you can use powerful controls to filter valid params within the controller where it belongs. I highly recommend.

http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods

Also note that if account_id is not freely set by the user (e.g., a user can only submit a service for the own single account_id, then it is better practice not to send it via the request, but set it within the controller by adding something like:

@my_service.account_id = current_user.account_id 

You can surely combine the two if you only allow users to create service on their own account, but allow admin to create anyone's by using roles in attr_accessible.

hope this helps

Learning Ruby on Rails

Ruby: I used Learn to program (in a weekend), Ruby Visual QuickStart (believe it or not this QS book was "off the hook" excellent). This took about a week.

Rails: I just went through Learn Rails in one "aggressive" week. Definitely feel I have the nuts and bolts. It's 2009 which I deemed important!

Now I plan to combine a more advanced book with a real project.

IDE: VIM with rails plugin is great if you're a vim addict. Otherwise, try any suggested above.

Of course railscast, etc., are useful for most up to date stuff.

How to display svg icons(.svg files) in UI using React Component?

if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:

import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';

const temp = (
     <div>
         <img src={logo} />
         <img src={image} />
     </div>
);

ReactDOM.render(temp,document.getElementByID("app"));

Happy Coding :")

resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/

Targeting both 32bit and 64bit with Visual Studio in same solution/project

Regarding your last question. Most likely you cant solve this inside a single MSI. If you are using registry/system folders or anything related, the MSI itself must be aware of this and you must prepare a 64bit MSI to properly install on 32 bit machine.

There is a possibility that you can make you product installed as a 32 it application and still be able to make it run as 64 bit one, but i think that may be somewhat hard to achieve.

that being said i think you should be able to keep a single code base for everything. In my current work place we have managed to do so. (but it did took some juggling to make everything play together)

Hope this helps. Heres a link to some info related to 32/64 bit issues: http://blog.typemock.com/2008/07/registry-on-windows-64-bit-double-your.html

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

click or change event on radio using jquery

You can specify the name attribute as below:

$( 'input[name="testGroup"]:radio' ).change(

Mask output of `The following objects are masked from....:` after calling attach() function

If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename) several times until all cases are gone then attach(newfilename) should have no output message.

attached files under environment tab

Row count with PDO

I tried $count = $stmt->rowCount(); with Oracle 11.2 and it did not work. I decided to used a for loop as show below.

   $count =  "";
    $stmt =  $conn->prepare($sql);
    $stmt->execute();
   echo "<table border='1'>\n";
   while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
        $count++;
        echo "<tr>\n";
    foreach ($row as $item) {
    echo "<td class='td2'>".($item !== null ? htmlentities($item, ENT_QUOTES):"&nbsp;")."</td>\n";
        } //foreach ends
        }// while ends
        echo "</table>\n";
       //echo " no of rows : ". oci_num_rows($stmt);
       //equivalent in pdo::prepare statement
       echo "no.of rows :".$count;

Twitter Bootstrap dropdown menu

It actually requires inclusion of Twitter Bootstrap's dropdown.js

http://getbootstrap.com/2.3.2/components.html

Insert variable values in the middle of a string

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

How to create a new instance from a class object in Python

Just call the "type" built in using three parameters, like this:

ClassName = type("ClassName", (Base1, Base2,...), classdictionary)

update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.

To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:

instance = ClassObject()

The mechanism for instantiation is thus:

Python does not use the new keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:

Its class' __call__ method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root.

So calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)

class type:
    ...
    def __call__(cls, *args, **kw):
          constructor = getattr(cls, "__new__")
          instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
          instance.__init__(cls, *args, **kw)
          return instance

(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happen "in real life" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally)

Drawing an image from a data URL to a canvas

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

Maven error "Failure to transfer..."

This worked for me in Windows as well.

  1. Locate the {user}/.m2/repository (Using Juno /Win7 here)
  2. In the Search field in upper right of window, type ".lastupdated". Windows will look through all subfolders for these files in the directory. (I did not look through cache.)
  3. Remove them by Right-click > Delete (I kept all of the lastupdated.properties).
  4. Then go back into Eclipse, Right-click on the project and select Maven > Update Project. I selected to "Force Update of Snapshots/Releases". Click Ok and the dependencies finally resolved correctly.

Java Byte Array to String to Byte Array

[JDK8]

import java.util.Base64;

To string:

String str = Base64.getEncoder().encode(new byte[]{ -47, 1, 16, ... });

To byte array:

byte[] bytes = Base64.getDecoder().decode("JVBERi0xLjQKMyAwIG9iago8P...");

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

You could use RAISE_APPLICATION_ERROR like this:

DECLARE
    ex_custom       EXCEPTION;
BEGIN
    RAISE ex_custom;
EXCEPTION
    WHEN ex_custom THEN
        RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/

That will raise an exception that looks like:

ORA-20001: My exception was raised

The error number can be anything between -20001 and -20999.

Objective-C : BOOL vs bool

Yup, BOOL is a typedef for a signed char according to objc.h.

I don't know about bool, though. That's a C++ thing, right? If it's defined as a signed char where 1 is YES/true and 0 is NO/false, then I imagine it doesn't matter which one you use.

Since BOOL is part of Objective-C, though, it probably makes more sense to use a BOOL for clarity (other Objective-C developers might be puzzled if they see a bool in use).

How to revert multiple git commits?

None of those worked for me, so I had three commits to revert (the last three commits), so I did:

git revert HEAD
git revert HEAD~2
git revert HEAD~4
git rebase -i HEAD~3 # pick, squash, squash

Worked like a charm :)

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

What is the difference between DTR/DSR and RTS/CTS flow control?

  • DTR - Data Terminal Ready
  • DSR - Data Set Ready
  • RTS - Request To Send
  • CTS - Clear To Send

There are multiple ways of doing things because there were never any protocols built into the standards. You use whatever ad-hoc "standard" your equipment implements.

Just based on the names, RTS/CTS would seem to be a natural fit. However, it's backwards from the needs that developed over time. These signals were created at a time when a terminal would batch-send a screen full of data, but the receiver might not be ready, thus the need for flow control. Later the problem would be reversed, as the terminal couldn't keep up with data coming from the host, but the RTS/CTS signals go the wrong direction - the interface isn't orthogonal, and there's no corresponding signals going the other way. Equipment makers adapted as best they could, including using the DTR and DSR signals.

EDIT

To add a bit more detail, its a two level hierarchy so "officially" both must happen for communication to take place. The behavior is defined in the original CCITT (now ITU-T) standard V.28.

enter image description here

The DCE is a modem connecting between the terminal and telephone network. In the telephone network was another piece of equipment which split off to the data network, eg. X.25.

The modem has three states: Powered off, Ready (Data Set Ready is true), and connected (Data Carrier Detect)

The terminal can't do anything until the modem is connected.

When the modem wants to send data, it raises RTS and the modem grants the request with CTS. The modem lowers CTS when its internal buffer is full.

So nostalgic!

Android checkbox style

Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.


My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.

At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.

First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.

<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox in a different name. So let's look at that parent style.

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">@android:drawable/btn_check_label_background</item>
    <item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>

This style references both a background and button drawable. btn_check_label_background is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox.

As listChoiceIndicatorMultiple is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):

<style name="Theme">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
    ...
</style>

<style name="Theme.Holo">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
    ...
</style>

<style name="Theme.Holo.Light" parent="Theme.Light">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
    ...
</style>

So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple attribute, the actual appearance of the CheckBox is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo, you will always get the CheckBox appearance matching the theme.

Now, if you want to change your CheckBox's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.

As for your second question:

Also can you set styles to individual widgets if you set a style to the application?

Absolutely, and they will override any activity- or application-set styles.

Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?


Update:

Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.

However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:

int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);

The first line will actually return the resource id of the btn_check_holo_light drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox, we can set it as 'button drawable' on the widget. The result is a CheckBox with the appearance of the Holo.Light version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.

Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo styling (non-light, that is).

Screenshot showing the result


Update2:

With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):

Lollipop added the ability to overwrite the theme at a view by view level by using the android:theme XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to use android:theme for Toolbars (deprecating the app:theme used previously) and, even better, brings android:theme support to all views on API 11+ devices.

In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo" />

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo.Light" />

The first CheckBox is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.

Of course you should no longer be using the Holo theme, but instead use Material.

Bash or KornShell (ksh)?

I'm a korn-shell veteran, so know that I speak from that perspective.

However, I have been comfortable with Bourne shell, ksh88, and ksh93, and for the most I know which features are supported in which. (I should skip ksh88 here, as it's not widely distributed anymore.)

For interactive use, take whatever fits your need. Experiment. I like being able to use the same shell for interactive use and for programming.

I went from ksh88 on SVR2 to tcsh, to ksh88sun (which added significant internationalisation support) and ksh93. I tried bash, and hated it because it flattened my history. Then I discovered shopt -s lithist and all was well. (The lithist option assures that newlines are preserved in your command history.)

For shell programming, I'd seriously recommend ksh93 if you want a consistent programming language, good POSIX conformance, and good performance, as many common unix commands can be available as builtin functions.

If you want portability use at least both. And make sure you have a good test suite.

There are many subtle differences between shells. Consider for example reading from a pipe:

b=42 && echo one two three four |
    read a b junk && echo $b

This will produce different results in different shells. The korn-shell runs pipelines from back to front; the last element in the pipeline runs in the current process. Bash did not support this useful behaviour until v4.x, and even then, it's not the default.

Another example illustrating consistency: The echo command itself, which was made obsolete by the split between BSD and SYSV unix, and each introduced their own convention for not printing newlines (and other behaviour). The result of this can still be seen in many 'configure' scripts.

Ksh took a radical approach to that - and introduced the print command, which actually supports both methods (the -n option from BSD, and the trailing \c special character from SYSV)

However, for serious systems programming I'd recommend something other than a shell, like python, perl. Or take it a step further, and use a platform like puppet - which allows you to watch and correct the state of whole clusters of systems, with good auditing.

Shell programming is like swimming in uncharted waters, or worse.

Programming in any language requires familiarity with its syntax, its interfaces and behaviour. Shell programming isn't any different.

Enable/Disable a dropdownbox in jquery

try this

 <script type="text/javascript">
        $(document).ready(function () {
            $("#chkdwn2").click(function () {
                if (this.checked)
                    $('#dropdown').attr('disabled', 'disabled');
                else
                    $('#dropdown').removeAttr('disabled');
            });
        });
    </script>

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

Password masking console application

You could append your keys to an accumulating linked list.

When a backspace key is received, remove the last key from the list.

When you receive the enter key, collapse your list into a string and do the rest of your work.

Tomcat starts but home page cannot open with url http://localhost:8080

I had the same issue. My tomcat was started but I was getting HTTP 404 page not found.However, in my situation, I installed tree instances of tomcat. Each instance contains conf, temp, work, webapps and logs folders. Unless I forgot, to copy the global web.xml under conf folder of each tomcat.

    e.g: /opt/tomcat/mytomcatInstance/conf/web.xml 

The web.xml Deployment Descriptor file describes how to deploy a web application in a servlet container.

So even if my tomcat was up, my web apps could not be deployed properly.

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.

Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.

Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.

To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.

How to remove duplicate values from a multi-dimensional array in PHP

Here is another way. No intermediate variables are saved.

We used this to de-duplicate results from a variety of overlapping queries.

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

What is the LD_PRELOAD trick?

Using LD_PRELOAD path, you can force the application loader to load provided shared object, over the default provided.

Developers uses this to debug their applications by providing different versions of the shared objects.

We've used it to hack certain applications, by overriding existing functions using prepared shared objects.

How to take complete backup of mysql database using mysqldump command line utility

Use '-R' to backup stored procedures, but also keep in mind that if you want a consistent dump of your database while its being modified you need to use --single-transaction (if you only backup innodb) or --lock-all-tables (if you also need myisam tables)

Simpler way to check if variable is not equal to multiple string values?

If you're planning on building a function in the if statement, I'd also advise the use of in_array. It's a lot cleaner.

If you're attempting to assign values to variables you can use the if/else shorthand:

$variable_to_fill = $some_variable !== 'uk' ? false : true;

Implement a simple factory pattern with Spring 3 annotations

You are right, by creating object manually you are not letting Spring to perform autowiring. Consider managing your services by Spring as well:

@Component
public class MyServiceFactory {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public static MyService getMyService(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne;
        } else if (service.equals("two")) {
            return myServiceTwo;
        } else if (service.equals("three")) {
            return myServiceThree;
        } else {
            return myServiceDefault;
        }
    }
}

But I would consider the overall design to be rather poor. Wouldn't it better to have one general MyService implementation and pass one/two/three string as extra parameter to checkStatus()? What do you want to achieve?

@Component
public class MyServiceAdapter implements MyService {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public boolean checkStatus(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne.checkStatus();
        } else if (service.equals("two")) {
            return myServiceTwo.checkStatus();
        } else if (service.equals("three")) {
            return myServiceThree.checkStatus();
        } else {
            return myServiceDefault.checkStatus();
        }
    }
}

This is still poorly designed because adding new MyService implementation requires MyServiceAdapter modification as well (SRP violation). But this is actually a good starting point (hint: map and Strategy pattern).

calling Jquery function from javascript

var jqueryFunction;

$().ready(function(){
    //jQuery function
    jqueryFunction = function( _msg )
    {
        alert( _msg );
    }
})

//javascript function
function jsFunction()
{
    //Invoke jQuery Function
    jqueryFunction("Call from js to jQuery");
}

http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

Xcode is not currently available from the Software Update server

I had to run Xcode.app and agree to the License Agreement

Setup: Brand new MacBook with Mavericks, then brew install and other c/l type things 'just work'.

Django templates: If false?

This is far easier to check in Python (i.e. your view code) than in the template, because the Python code is simply:

myvar is False

Illustrating:

>>> False is False
True
>>> None is False
False
>>> [] is False
False

The problem at the template level is that the template if doesn't parse is (though it does parse in). Also, if you don't mind it, you could try to patch support for is into the template engine; base it on the code for ==.

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

You need to change the bind-address parameter to 127.0.0.1 in the mysql config file (my.ini or my.cnf) or use the one that is defined there.

If that doesn't work you should check that the mysql service is actually running.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

No 'Access-Control-Allow-Origin' header in Angular 2 app

I had the same problem when I was practising Angular5. Then I came across https://spring.io/guides/gs/rest-service-cors/ which helped me to resolve the issue.

I have kept @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") on my request mapping method. We can also configure this globally in spring boot application.

Can I have onScrollListener for a ScrollView?

    // --------Start Scroll Bar Slide--------
    final HorizontalScrollView xHorizontalScrollViewHeader = (HorizontalScrollView) findViewById(R.id.HorizontalScrollViewHeader);
    final HorizontalScrollView xHorizontalScrollViewData = (HorizontalScrollView) findViewById(R.id.HorizontalScrollViewData);
    xHorizontalScrollViewData.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int scrollX; int scrollY;
            scrollX=xHorizontalScrollViewData.getScrollX();
            scrollY=xHorizontalScrollViewData.getScrollY();
            xHorizontalScrollViewHeader.scrollTo(scrollX, scrollY);
        }
    });
    // ---------End Scroll Bar Slide---------

SHA1 vs md5 vs SHA256: which to use for a PHP login?

What people seem to be missing is that if the hacker has access to the database he probably also has access to the php file that hashes the password and can likely just modify that to send him all the successful user name password combos. If he doesn't have access to the web directory he could always just pick a password hash it, and write that into the database. In other words the hash algorithm doesn't really matter as much as system security, and limiting login attempts also if you don't use SSL then the attacker can just listen in on the connection to get the information. Unless you need the algorithm to take a long time to compute (for your own purposes) then SHA-256 or SHA-512 with a user specific salt should be enough.

As an added security measure set up a script (bash, batch, python, etc) or program and give it an obscure name and have it check and see if login.php has changed (check date/time stamp) and send you an email if it has. Also should probably log all attempts at login with admin rights and log all failed attempts to log into the database and have the logs emailed to you.

How to change resolution (DPI) of an image?

You have to copy the bits over a new image with the target resolution, like this:

    using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
    {
        using (Bitmap newBitmap = new Bitmap(bitmap))
        {
            newBitmap.SetResolution(300, 300);
            newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
        }
    }

How to undo a SQL Server UPDATE query?

Considering that you already have a full backup I’d just restore that backup into separate database and migrate the data from there.

If your data has changed after the latest backup then what you recover all data that way but you can try to recover that by reading transaction log.

If your database was in full recovery mode than transaction log has enough details to recover updates to your data after the latest backup.

You might want to try with DBCC LOG, fn_log functions or with third party log reader such as ApexSQL Log

Unfortunately there is no easy way to read transaction log because MS doesn’t provide documentation for this and stores the data in its proprietary format.

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

Set the trigger option of the popover to hover instead of click, which is the default one.

This can be done using either data-* attributes in the markup:

<a id="popover" data-trigger="hover">Popover</a>

Or with an initialization option:

$("#popover").popover({ trigger: "hover" });

Here's a DEMO.

How to fast-forward a branch to head?

To rebase the current local tracker branch moving local changes on top of the latest remote state:

$ git fetch && git rebase

More generally, to fast-forward and drop the local changes (hard reset)*:

$ git fetch && git checkout ${the_branch_name} && git reset --hard origin/${the_branch_name}

to fast-forward and keep the local changes (rebase):

$ git fetch && git checkout ${the_branch_name} && git rebase origin/${the_branch_name}

* - to undo the change caused by unintentional hard reset first do git reflog, that displays the state of the HEAD in reverse order, find the hash the HEAD was pointing to before the reset operation (usually obvious) and hard reset the branch to that hash.

Android studio Gradle build speed up

This is what I did and my gradle build speed improved dramatically! from 1 min to 20sec for the first build and succeeding builds became from 40 sec to 5 sec.

In the gradle.properties file Add this:

org.gradle.jvmargs=-Xmx8192M -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

In the Command Line Arguments via Go to File > Other Settings> default Settings >Build, Execution, Deploy> Complier and add the following arguments to Command Line Arguments

Add this:

--debug --stacktrace -a, --no-rebuild -q, --quiet --offline

See image here

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

If you want to use some variable, you may use this way:

String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");

Displaying a vector of strings in C++

Because userString is empty. You only declare it

vector<string> userString;     

but never add anything, so the for loop won't even run.

How to find specific lines in a table using Selenium?

You want:

int rowNumber=...;
string value = driver.findElement(By.xpath("//div[@id='productOrderContainer']/table/tbody/tr[" + rowNumber +"]/div[id='something']")).getText();

In other words, locate <DIV> with the id "something" contained within the rowNumberth <TR> of the <TABLE> contained within the <DIV> with the id "productOrderContainer", and then get its text value (which is what I believe you mean by "get me the value in <div id='something'>"

JFrame: How to disable window resizing?

You can use this.setResizable(false); or frameObject.setResizable(false);

Formatting Decimal places in R

If you prefer significant digits to fixed digits then, the signif command might be useful:

> signif(1.12345, digits = 3)
[1] 1.12
> signif(12.12345, digits = 3)
[1] 12.1
> signif(12345.12345, digits = 3)
[1] 12300

Using Mysql WHERE IN clause in codeigniter

Try this one:

$this->db->select("*");
$this->db->where_in("(SELECT trans_id FROM myTable WHERE code = 'B')");
$this->db->where('code !=', 'B');
$this->db->get('myTable');

Note: $this->db->select("*"); is optional when you are selecting all columns from table

Embedding a media player in a website using HTML

I found the that either IE or Chrome choked on most of these, or they required external libraries. I just wanted to play an MP3, and I found the page http://www.w3schools.com/html/html_sounds.asp very helpful.

<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  <embed height="50" width="100" src="horse.mp3">
</audio>

Worked for me in the browsers I tried, but I didn't have some of the old ones around at this time.

How to set HTTP headers (for cache-control)?

This is the best .htaccess I have used in my actual website:

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

##Tweaks##
Header set X-Frame-Options SAMEORIGIN

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_headers.c>
    Header set Connection keep-alive
    <filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
        Header set Cache-Control "max-age=2592000, public"
    </filesmatch>
    <filesmatch "\.(jpg|jpeg|png)$">
        Header set Cache-Control "max-age=1209600, public"
    </filesmatch>
    # css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
    <filesmatch "\.(css)$">
        Header set Cache-Control "max-age=31536000, private"
    </filesmatch>
    <filesmatch "\.(js)$">
        Header set Cache-Control "max-age=1209600, private"
    </filesmatch>
    <filesMatch "\.(x?html?|php)$">
        Header set Cache-Control "max-age=600, private, must-revalidate"
      </filesMatch>
</IfModule>

What’s the best RESTful method to return total number of items in an object?

You could consider counts as a resource. The URL would then be:

/api/counts/member

How to call Base Class's __init__ method from the child class?

If you are using Python 3, it is recommended to simply call super() without any argument:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Do not call super with class as it may lead to infinite recursion exceptions as per this answer.

limit text length in php and provide 'Read more' link

$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";

if(count($words) == 101){
   $words[100] = " ... ";
}

$shown_string = implode(" ", $words);

How to get min, seconds and milliseconds from datetime.now() in python?

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

How can I run an external command asynchronously from Python?

subprocess.Popen does exactly what you want.

from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()

(Edit to complete the answer from comments)

The Popen instance can do various other things like you can poll() it to see if it is still running, and you can communicate() with it to send it data on stdin, and wait for it to terminate.

SQL multiple columns in IN clause

Determine whether the list of names is different with each query or reused. If it is reused, it belongs to the database.

Even if it is unique with each query, it may be useful to load it to a temporary table (#table syntax) for performance reasons - in that case you will be able to avoid recompilation of a complex query.

If the maximum number of names is fixed, you should use a parametrized query.

However, if none of the above cases applies, I would go with inlining the names in the query as in your approach #1.

How to limit text width

You can apply css like this:

div {
   word-wrap: break-word;
   width: 100px;
}

Usually browser does not break words, but word-wrap: break-word; will force it to break words too.

Demo: http://jsfiddle.net/Mp7tc/

More info about word-wrap

Send email from localhost running XAMMP in PHP using GMAIL mail server

in php.ini file,uncomment this one

sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
;sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"

and in sendmail.ini

smtp_server=smtp.gmail.com
smtp_port=465
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=yourpassword
[email protected]
hostname=localhost

configure this one..it will works...it working fine for me.

thanks.

How do I make a dotted/dashed line in Android?

For a Dotted effect on a Canvas, set this attribute to the paint object :

paint.setPathEffect(new DashPathEffect(new float[] {0,30}, 0));

And change the value 30 as your render suits you : it represents the "distance" between each dots.

enter image description here

:: (double colon) operator in Java 8

So I see here tons of answers that are frankly overcomplicated, and that's an understatement.

The answer is pretty simple: :: it's called a Method References https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

So I won't copy-paste, on the link, you can find all the information if you scroll down to the table.


Now, let's take a short look at what is a Method References:

A::b somewhat substitutes the following inline lambda expression: (params ...) -> A.b(params ...)

To correlate this with your questions, it's necessary to understand a java lambda expression. Which is not hard.

An inline lambda expression is similar to a defined functional interface (which is an interface that has no more and no less than 1 method). Let's take a short look what I mean:

InterfaceX f = (x) -> x*x; 

InterfaceX must be a functional interface. Any functional interface, the only thing what's important about InterfaceX for that compiler is that you define the format:

InterfaceX can be any of this:

interface InterfaceX
{
    public Integer callMe(Integer x);
}

or this

interface InterfaceX
{
    public Double callMe(Integer x);
}

or more generic:

interface InterfaceX<T,U>
{
    public T callMe(U x);
}

Let's take the first presented case and the inline lambda expression that we defined earlier.

Before Java 8, you could've defined it similarly this way:

 InterfaceX o = new InterfaceX(){
                     public int callMe (int x) 
                       {
                        return x*x;
                       } };
                     

Functionally, it's the same thing. The difference is more in how the compiler perceives this.

Now that we took a look at inline lambda expression, let's return to Method References (::). Let's say you have a class like this:

class Q {
        public static int anyFunction(int x)
             {
                 return x+5;
             } 
        }
    

Since method anyFunctions has the same types as InterfaceX callMe, we can equivalate those two with a Method Reference.

We can write it like this:

InterfaceX o =  Q::anyFunction; 

and that is equivalent to this :

InterfaceX o = (x) -> Q.anyFunction(x);

A cool thing and advantage of Method References are that at first, until you assign them to variables, they are typeless. So you can pass them as parameters to any equivalent looking (has same defined types) functional interface. Which is exactly what happens in your case

How can I install Apache Ant on Mac OS X?

MacPorts will install ant for you in MacOSX 10.9. Just use

$ sudo port install apache-ant

and it will install.

How can I create a carriage return in my C# string

You can put \r\n in your string.

How do I break out of nested loops in Java?

Best and Easy Method..

outerloop:
for(int i=0; i<10; i++){
    // here we can break Outer loop by 
    break outerloop;

    innerloop:
    for(int i=0; i<10; i++){
        // here we can break innerloop by 
        break innerloop;
     }
}

Peak signal detection in realtime timeseries data

Robust peak detection algorithm (using z-scores)

I came up with an algorithm that works very well for these types of datasets. It is based on the principle of dispersion: if a new datapoint is a given x number of standard deviations away from some moving mean, the algorithm signals (also called z-score). The algorithm is very robust because it constructs a separate moving mean and deviation, such that signals do not corrupt the threshold. Future signals are therefore identified with approximately the same accuracy, regardless of the amount of previous signals. The algorithm takes 3 inputs: lag = the lag of the moving window, threshold = the z-score at which the algorithm signals and influence = the influence (between 0 and 1) of new signals on the mean and standard deviation. For example, a lag of 5 will use the last 5 observations to smooth the data. A threshold of 3.5 will signal if a datapoint is 3.5 standard deviations away from the moving mean. And an influence of 0.5 gives signals half of the influence that normal datapoints have. Likewise, an influence of 0 ignores signals completely for recalculating the new threshold. An influence of 0 is therefore the most robust option (but assumes stationarity); putting the influence option at 1 is least robust. For non-stationary data, the influence option should therefore be put somewhere between 0 and 1.

It works as follows:

Pseudocode

# Let y be a vector of timeseries data of at least length lag+2
# Let mean() be a function that calculates the mean
# Let std() be a function that calculates the standard deviaton
# Let absolute() be the absolute value function

# Settings (the ones below are examples: choose what is best for your data)
set lag to 5;          # lag 5 for the smoothing functions
set threshold to 3.5;  # 3.5 standard deviations for signal
set influence to 0.5;  # between 0 and 1, where 1 is normal influence, 0.5 is half

# Initialize variables
set signals to vector 0,...,0 of length of y;   # Initialize signal results
set filteredY to y(1),...,y(lag)                # Initialize filtered series
set avgFilter to null;                          # Initialize average filter
set stdFilter to null;                          # Initialize std. filter
set avgFilter(lag) to mean(y(1),...,y(lag));    # Initialize first value
set stdFilter(lag) to std(y(1),...,y(lag));     # Initialize first value

for i=lag+1,...,t do
  if absolute(y(i) - avgFilter(i-1)) > threshold*stdFilter(i-1) then
    if y(i) > avgFilter(i-1) then
      set signals(i) to +1;                     # Positive signal
    else
      set signals(i) to -1;                     # Negative signal
    end
    set filteredY(i) to influence*y(i) + (1-influence)*filteredY(i-1);
  else
    set signals(i) to 0;                        # No signal
    set filteredY(i) to y(i);
  end
  set avgFilter(i) to mean(filteredY(i-lag),...,filteredY(i));
  set stdFilter(i) to std(filteredY(i-lag),...,filteredY(i));
end

Rules of thumb for selecting good parameters for your data can be found below.


Demo

Demonstration of robust thresholding algorithm

The Matlab code for this demo can be found here. To use the demo, simply run it and create a time series yourself by clicking on the upper chart. The algorithm starts working after drawing lag number of observations.


Result

For the original question, this algorithm will give the following output when using the following settings: lag = 30, threshold = 5, influence = 0:

Thresholding algorithm example


Implementations in different programming languages:


Rules of thumb for configuring the algorithm

lag: the lag parameter determines how much your data will be smoothed and how adaptive the algorithm is to changes in the long-term average of the data. The more stationary your data is, the more lags you should include (this should improve the robustness of the algorithm). If your data contains time-varying trends, you should consider how quickly you want the algorithm to adapt to these trends. I.e., if you put lag at 10, it takes 10 'periods' before the algorithm's treshold is adjusted to any systematic changes in the long-term average. So choose the lag parameter based on the trending behavior of your data and how adaptive you want the algorithm to be.

influence: this parameter determines the influence of signals on the algorithm's detection threshold. If put at 0, signals have no influence on the threshold, such that future signals are detected based on a threshold that is calculated with a mean and standard deviation that is not influenced by past signals. If put at 0.5, signals have half the influence of normal data points. Another way to think about this is that if you put the influence at 0, you implicitly assume stationarity (i.e. no matter how many signals there are, you always expect the time series to return to the same average over the long term). If this is not the case, you should put the influence parameter somewhere between 0 and 1, depending on the extent to which signals can systematically influence the time-varying trend of the data. E.g., if signals lead to a structural break of the long-term average of the time series, the influence parameter should be put high (close to 1) so the threshold can react to structural breaks quickly.

threshold: the threshold parameter is the number of standard deviations from the moving mean above which the algorithm will classify a new datapoint as being a signal. For example, if a new datapoint is 4.0 standard deviations above the moving mean and the threshold parameter is set as 3.5, the algorithm will identify the datapoint as a signal. This parameter should be set based on how many signals you expect. For example, if your data is normally distributed, a threshold (or: z-score) of 3.5 corresponds to a signaling probability of 0.00047 (from this table), which implies that you expect a signal once every 2128 datapoints (1/0.00047). The threshold therefore directly influences how sensitive the algorithm is and thereby also determines how often the algorithm signals. Examine your own data and choose a sensible threshold that makes the algorithm signal when you want it to (some trial-and-error might be needed here to get to a good threshold for your purpose).


WARNING: The code above always loops over all datapoints everytime it runs. When implementing this code, make sure to split the calculation of the signal into a separate function (without the loop). Then when a new datapoint arrives, update filteredY, avgFilter and stdFilter once. Do not recalculate the signals for all data everytime there is a new datapoint (like in the example above), that would be extremely inefficient and slow in real-time applications.

Other ways to modify the algorithm (for potential improvements) are:

  1. Use median instead of mean
  2. Use a robust measure of scale, such as the MAD, instead of the standard deviation
  3. Use a signalling margin, so the signal doesn't switch too often
  4. Change the way the influence parameter works
  5. Treat up and down signals differently (asymmetric treatment)
  6. Create a separate influence parameter for the mean and std (as in this Swift translation)

(Known) academic citations to this StackOverflow answer:

Other works using the algorithm from this answer

Other applications of the algorithm from this answer

Links to other peak detection algorithms


How to reference this algorithm:

Brakel, J.P.G. van (2014). "Robust peak detection algorithm using z-scores". Stack Overflow. Available at: https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/22640362#22640362 (version: 2020-11-08).


If you use this function somewhere, please credit me by using above reference. If you have any questions about the algorithm, post them in the comments below or reach out to me on LinkedIn.


select and echo a single field from mysql db using PHP

$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];

but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.

What is the difference between a .cpp file and a .h file?

Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:

  Source Files for C: .c
  Header Files for C: .h

  Source Files for C++: .cpp
  Header Files for C++: .hpp

Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.

C# : Converting Base Class to Child Class

Use the cast operator, as such:

var skyfilterClient = (SkyfilterClient)networkClient;

Publish to IIS, setting Environment Variable

Edit: as of RC2 and RTM releases, this advice is out of date. The best way I have found to accomplish this in release is to edit the following web.config sections in IIS for each environment:

system.webServer/aspNetCore:

Edit the environmentVariable entry and add an environment variable setting:

ASPNETCORE_ENVIRONMENT : < Your environment name >


As an alternative to drpdrp's approach, you can do the following:

  • In your project.json, add commands that pass the ASPNET_ENV variable directly to Kestrel:

    "commands": {
        "Development": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Development",
        "Staging": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Staging",
        "Production": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Production"
    }
    
  • When publishing, use the --iis-command option to specify an environment:

    dnu publish --configuration Debug --iis-command Staging --out "outputdir" --runtime dnx-clr-win-x86-1.0.0-rc1-update1
    

I found this approach to be less intrusive than creating extra IIS users.

Checking cin input stream produces an integer

You can check like this:

int x;
cin >> x;

if (cin.fail()) {
    //Not an int.
}

Furthermore, you can continue to get input until you get an int via:

#include <iostream>



int main() {

    int x;
    std::cin >> x;
    while(std::cin.fail()) {
        std::cout << "Error" << std::endl;
        std::cin.clear();
        std::cin.ignore(256,'\n');
        std::cin >> x;
    }
    std::cout << x << std::endl;

    return 0;
}

EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).

#include <iostream>
#include <string>

int main() {

    std::string theInput;
    int inputAsInt;

    std::getline(std::cin, theInput);

    while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {

        std::cout << "Error" << std::endl;

        if( theInput.find_first_not_of("0123456789") == std::string::npos) {
            std::cin.clear();
            std::cin.ignore(256,'\n');
        }

        std::getline(std::cin, theInput);
    }

    std::string::size_type st;
    inputAsInt = std::stoi(theInput,&st);
    std::cout << inputAsInt << std::endl;
    return 0;
}

Separation of business logic and data access in django

An old question, but I'd like to offer my solution anyway. It's based on acceptance that model objects too require some additional functionality while it's awkward to place it within the models.py. Heavy business logic may be written separately depending on personal taste, but I at least like the model to do everything related to itself. This solution also supports those who like to have all the logic placed within models themselves.

As such, I devised a hack that allows me to separate logic from model definitions and still get all the hinting from my IDE.

The advantages should be obvious, but this lists a few that I have observed:

  • DB definitions remain just that - no logic "garbage" attached
  • Model-related logic is all placed neatly in one place
  • All the services (forms, REST, views) have a single access point to logic
  • Best of all: I did not have to rewrite any code once I realised that my models.py became too cluttered and had to separate the logic away. The separation is smooth and iterative: I could do a function at a time or entire class or the entire models.py.

I have been using this with Python 3.4 and greater and Django 1.8 and greater.

app/models.py

....
from app.logic.user import UserLogic

class User(models.Model, UserLogic):
    field1 = models.AnyField(....)
    ... field definitions ...

app/logic/user.py

if False:
    # This allows the IDE to know about the User model and its member fields
    from main.models import User

class UserLogic(object):
    def logic_function(self: 'User'):
        ... code with hinting working normally ...

The only thing I can't figure out is how to make my IDE (PyCharm in this case) recognise that UserLogic is actually User model. But since this is obviously a hack, I'm quite happy to accept the little nuisance of always specifying type for self parameter.

Set UIButton title UILabel font size programmatically

You can also set the font size, and the font style using something like this. It's a little more than what you're asking for but hey, what the heck...

[myButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:13.0]];

And… if you're feeling frisky a list of available fonts can be found by implementing this code and then checking the output in your xCode debugger.

Code:

NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
    NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
    fontNames = [[NSArray alloc] initWithArray:
            [UIFont fontNamesForFamilyName:
            [familyNames objectAtIndex:indFamily]]];
    for (indFont=0; indFont<[fontNames count]; ++indFont)
    {
        NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
    }
}

Example:

2012-04-02 11:36:34.395 MyApp[3579:707] Family name: Thonburi
2012-04-02 11:36:34.398 MyApp[3579:707]     Font name: Thonburi-Bold
2012-04-02 11:36:34.402 MyApp[3579:707]     Font name: Thonburi
2012-04-02 11:36:34.405 MyApp[3579:707] Family name: Snell Roundhand
2012-04-02 11:36:34.408 MyApp[3579:707]     Font name: SnellRoundhand-Bold
2012-04-02 11:36:34.411 MyApp[3579:707]     Font name: SnellRoundhand-Black
2012-04-02 11:36:34.415 MyApp[3579:707]     Font name: SnellRoundhand
2012-04-02 11:36:34.418 MyApp[3579:707] Family name: Academy Engraved LET
2012-04-02 11:36:34.421 MyApp[3579:707]     Font name: AcademyEngravedLetPlain
2012-04-02 11:36:34.424 MyApp[3579:707] Family name: Marker Felt
2012-04-02 11:36:34.427 MyApp[3579:707]     Font name: MarkerFelt-Wide
2012-04-02 11:36:34.430 MyApp[3579:707]     Font name: MarkerFelt-Thin
2012-04-02 11:36:34.434 MyApp[3579:707] Family name: Geeza Pro
2012-04-02 11:36:34.437 MyApp[3579:707]     Font name: GeezaPro-Bold
2012-04-02 11:36:34.441 MyApp[3579:707]     Font name: GeezaPro
2012-04-02 11:36:34.445 MyApp[3579:707] Family name: Arial Rounded MT Bold
2012-04-02 11:36:34.448 MyApp[3579:707]     Font name: ArialRoundedMTBold
2012-04-02 11:36:34.451 MyApp[3579:707] Family name: Trebuchet MS
2012-04-02 11:36:34.455 MyApp[3579:707]     Font name: TrebuchetMS
2012-04-02 11:36:34.458 MyApp[3579:707]     Font name: TrebuchetMS-Bold
2012-04-02 11:36:34.461 MyApp[3579:707]     Font name: TrebuchetMS-Italic
2012-04-02 11:36:34.464 MyApp[3579:707]     Font name: Trebuchet-BoldItalic
2012-04-02 11:36:34.467 MyApp[3579:707] Family name: Arial
2012-04-02 11:36:34.471 MyApp[3579:707]     Font name: Arial-BoldMT
2012-04-02 11:36:34.474 MyApp[3579:707]     Font name: ArialMT
2012-04-02 11:36:34.477 MyApp[3579:707]     Font name: Arial-ItalicMT
2012-04-02 11:36:34.480 MyApp[3579:707]     Font name: Arial-BoldItalicMT
2012-04-02 11:36:34.483 MyApp[3579:707] Family name: Marion
2012-04-02 11:36:34.487 MyApp[3579:707]     Font name: Marion-Regular
2012-04-02 11:36:34.491 MyApp[3579:707]     Font name: Marion-Bold
2012-04-02 11:36:34.494 MyApp[3579:707]     Font name: Marion-Italic
2012-04-02 11:36:34.503 MyApp[3579:707] Family name: Gurmukhi MN
2012-04-02 11:36:34.507 MyApp[3579:707]     Font name: GurmukhiMN
2012-04-02 11:36:34.511 MyApp[3579:707]     Font name: GurmukhiMN-Bold
2012-04-02 11:36:34.514 MyApp[3579:707] Family name: Malayalam Sangam MN
2012-04-02 11:36:34.518 MyApp[3579:707]     Font name: MalayalamSangamMN-Bold
2012-04-02 11:36:34.522 MyApp[3579:707]     Font name: MalayalamSangamMN
2012-04-02 11:36:34.525 MyApp[3579:707] Family name: Bradley Hand
2012-04-02 11:36:34.529 MyApp[3579:707]     Font name: BradleyHandITCTT-Bold
2012-04-02 11:36:34.532 MyApp[3579:707] Family name: Kannada Sangam MN
2012-04-02 11:36:34.536 MyApp[3579:707]     Font name: KannadaSangamMN
2012-04-02 11:36:34.540 MyApp[3579:707]     Font name: KannadaSangamMN-Bold
2012-04-02 11:36:34.544 MyApp[3579:707] Family name: Bodoni 72 Oldstyle
2012-04-02 11:36:34.548 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-Book
2012-04-02 11:36:34.552 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-Bold
2012-04-02 11:36:34.555 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-BookIt
2012-04-02 11:36:34.559 MyApp[3579:707] Family name: Cochin
2012-04-02 11:36:34.562 MyApp[3579:707]     Font name: Cochin
2012-04-02 11:36:34.566 MyApp[3579:707]     Font name: Cochin-BoldItalic
2012-04-02 11:36:34.570 MyApp[3579:707]     Font name: Cochin-Italic
2012-04-02 11:36:34.573 MyApp[3579:707]     Font name: Cochin-Bold
2012-04-02 11:36:34.577 MyApp[3579:707] Family name: Sinhala Sangam MN
2012-04-02 11:36:34.581 MyApp[3579:707]     Font name: SinhalaSangamMN
2012-04-02 11:36:34.584 MyApp[3579:707]     Font name: SinhalaSangamMN-Bold
2012-04-02 11:36:34.588 MyApp[3579:707] Family name: Hiragino Kaku Gothic ProN
2012-04-02 11:36:34.592 MyApp[3579:707]     Font name: HiraKakuProN-W6
2012-04-02 11:36:34.596 MyApp[3579:707]     Font name: HiraKakuProN-W3
2012-04-02 11:36:34.599 MyApp[3579:707] Family name: Papyrus
2012-04-02 11:36:34.603 MyApp[3579:707]     Font name: Papyrus-Condensed
2012-04-02 11:36:34.607 MyApp[3579:707]     Font name: Papyrus
2012-04-02 11:36:34.614 MyApp[3579:707] Family name: Verdana
2012-04-02 11:36:34.620 MyApp[3579:707]     Font name: Verdana
2012-04-02 11:36:34.626 MyApp[3579:707]     Font name: Verdana-Bold
2012-04-02 11:36:34.674 MyApp[3579:707]     Font name: Verdana-BoldItalic
2012-04-02 11:36:34.690 MyApp[3579:707]     Font name: Verdana-Italic
2012-04-02 11:36:34.730 MyApp[3579:707] Family name: Zapf Dingbats
2012-04-02 11:36:34.748 MyApp[3579:707]     Font name: ZapfDingbatsITC
2012-04-02 11:36:34.752 MyApp[3579:707] Family name: Courier
2012-04-02 11:36:34.757 MyApp[3579:707]     Font name: Courier-Bold
2012-04-02 11:36:34.762 MyApp[3579:707]     Font name: Courier
2012-04-02 11:36:34.769 MyApp[3579:707]     Font name: Courier-BoldOblique
2012-04-02 11:36:34.778 MyApp[3579:707]     Font name: Courier-Oblique
2012-04-02 11:36:34.786 MyApp[3579:707] Family name: Hoefler Text
2012-04-02 11:36:34.793 MyApp[3579:707]     Font name: HoeflerText-Black
2012-04-02 11:36:34.802 MyApp[3579:707]     Font name: HoeflerText-Italic
2012-04-02 11:36:34.810 MyApp[3579:707]     Font name: HoeflerText-Regular
2012-04-02 11:36:34.819 MyApp[3579:707]     Font name: HoeflerText-BlackItalic
2012-04-02 11:36:34.827 MyApp[3579:707] Family name: Euphemia UCAS
2012-04-02 11:36:34.836 MyApp[3579:707]     Font name: EuphemiaUCAS-Bold
2012-04-02 11:36:34.843 MyApp[3579:707]     Font name: EuphemiaUCAS
2012-04-02 11:36:34.848 MyApp[3579:707]     Font name: EuphemiaUCAS-Italic
2012-04-02 11:36:34.853 MyApp[3579:707] Family name: Helvetica
2012-04-02 11:36:34.857 MyApp[3579:707]     Font name: Helvetica-LightOblique
2012-04-02 11:36:34.863 MyApp[3579:707]     Font name: Helvetica
2012-04-02 11:36:34.873 MyApp[3579:707]     Font name: Helvetica-Oblique
2012-04-02 11:36:34.876 MyApp[3579:707]     Font name: Helvetica-BoldOblique
2012-04-02 11:36:34.880 MyApp[3579:707]     Font name: Helvetica-Bold
2012-04-02 11:36:34.884 MyApp[3579:707]     Font name: Helvetica-Light
2012-04-02 11:36:34.887 MyApp[3579:707] Family name: Hiragino Mincho ProN
2012-04-02 11:36:34.892 MyApp[3579:707]     Font name: HiraMinProN-W3
2012-04-02 11:36:34.898 MyApp[3579:707]     Font name: HiraMinProN-W6
2012-04-02 11:36:34.902 MyApp[3579:707] Family name: Bodoni Ornaments
2012-04-02 11:36:34.905 MyApp[3579:707]     Font name: BodoniOrnamentsITCTT
2012-04-02 11:36:34.923 MyApp[3579:707] Family name: Apple Color Emoji
2012-04-02 11:36:34.938 MyApp[3579:707]     Font name: AppleColorEmoji
2012-04-02 11:36:34.942 MyApp[3579:707] Family name: Optima
2012-04-02 11:36:34.946 MyApp[3579:707]     Font name: Optima-ExtraBlack
2012-04-02 11:36:34.950 MyApp[3579:707]     Font name: Optima-Italic
2012-04-02 11:36:34.954 MyApp[3579:707]     Font name: Optima-Regular
2012-04-02 11:36:34.965 MyApp[3579:707]     Font name: Optima-BoldItalic
2012-04-02 11:36:34.969 MyApp[3579:707]     Font name: Optima-Bold
2012-04-02 11:36:34.972 MyApp[3579:707] Family name: Gujarati Sangam MN
2012-04-02 11:36:34.985 MyApp[3579:707]     Font name: GujaratiSangamMN
2012-04-02 11:36:34.989 MyApp[3579:707]     Font name: GujaratiSangamMN-Bold
2012-04-02 11:36:34.993 MyApp[3579:707] Family name: Devanagari Sangam MN
2012-04-02 11:36:34.998 MyApp[3579:707]     Font name: DevanagariSangamMN
2012-04-02 11:36:35.002 MyApp[3579:707]     Font name: DevanagariSangamMN-Bold
2012-04-02 11:36:35.006 MyApp[3579:707] Family name: Times New Roman
2012-04-02 11:36:35.017 MyApp[3579:707]     Font name: TimesNewRomanPS-ItalicMT
2012-04-02 11:36:35.021 MyApp[3579:707]     Font name: TimesNewRomanPS-BoldMT
2012-04-02 11:36:35.032 MyApp[3579:707]     Font name: TimesNewRomanPSMT
2012-04-02 11:36:35.037 MyApp[3579:707]     Font name: TimesNewRomanPS-BoldItalicMT
2012-04-02 11:36:35.041 MyApp[3579:707] Family name: Kailasa
2012-04-02 11:36:35.045 MyApp[3579:707]     Font name: Kailasa
2012-04-02 11:36:35.050 MyApp[3579:707]     Font name: Kailasa-Bold
2012-04-02 11:36:35.053 MyApp[3579:707] Family name: Telugu Sangam MN
2012-04-02 11:36:35.064 MyApp[3579:707]     Font name: TeluguSangamMN-Bold
2012-04-02 11:36:35.068 MyApp[3579:707]     Font name: TeluguSangamMN
2012-04-02 11:36:35.071 MyApp[3579:707] Family name: Heiti SC
2012-04-02 11:36:35.099 MyApp[3579:707]     Font name: STHeitiSC-Medium
2012-04-02 11:36:35.107 MyApp[3579:707]     Font name: STHeitiSC-Light
2012-04-02 11:36:35.111 MyApp[3579:707] Family name: Futura
2012-04-02 11:36:35.115 MyApp[3579:707]     Font name: Futura-Medium
2012-04-02 11:36:35.119 MyApp[3579:707]     Font name: Futura-CondensedExtraBold
2012-04-02 11:36:35.122 MyApp[3579:707]     Font name: Futura-CondensedMedium
2012-04-02 11:36:35.135 MyApp[3579:707]     Font name: Futura-MediumItalic
2012-04-02 11:36:35.155 MyApp[3579:707] Family name: Bodoni 72
2012-04-02 11:36:35.160 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-BookIta
2012-04-02 11:36:35.164 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-Book
2012-04-02 11:36:35.168 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-Bold
2012-04-02 11:36:35.171 MyApp[3579:707] Family name: Baskerville
2012-04-02 11:36:35.183 MyApp[3579:707]     Font name: Baskerville-SemiBoldItalic
2012-04-02 11:36:35.187 MyApp[3579:707]     Font name: Baskerville-Bold
2012-04-02 11:36:35.197 MyApp[3579:707]     Font name: Baskerville-Italic
2012-04-02 11:36:35.245 MyApp[3579:707]     Font name: Baskerville-BoldItalic
2012-04-02 11:36:35.253 MyApp[3579:707]     Font name: Baskerville-SemiBold
2012-04-02 11:36:35.258 MyApp[3579:707]     Font name: Baskerville
2012-04-02 11:36:35.262 MyApp[3579:707] Family name: Chalkboard SE
2012-04-02 11:36:35.266 MyApp[3579:707]     Font name: ChalkboardSE-Regular
2012-04-02 11:36:35.269 MyApp[3579:707]     Font name: ChalkboardSE-Bold
2012-04-02 11:36:35.279 MyApp[3579:707]     Font name: ChalkboardSE-Light
2012-04-02 11:36:35.284 MyApp[3579:707] Family name: Heiti TC
2012-04-02 11:36:35.288 MyApp[3579:707]     Font name: STHeitiTC-Medium
2012-04-02 11:36:35.299 MyApp[3579:707]     Font name: STHeitiTC-Light
2012-04-02 11:36:35.305 MyApp[3579:707] Family name: Copperplate
2012-04-02 11:36:35.310 MyApp[3579:707]     Font name: Copperplate
2012-04-02 11:36:35.313 MyApp[3579:707]     Font name: Copperplate-Light
2012-04-02 11:36:35.317 MyApp[3579:707]     Font name: Copperplate-Bold
2012-04-02 11:36:35.320 MyApp[3579:707] Family name: Party LET
2012-04-02 11:36:35.334 MyApp[3579:707]     Font name: PartyLetPlain
2012-04-02 11:36:35.338 MyApp[3579:707] Family name: American Typewriter
2012-04-02 11:36:35.351 MyApp[3579:707]     Font name: AmericanTypewriter-CondensedLight
2012-04-02 11:36:35.357 MyApp[3579:707]     Font name: AmericanTypewriter-Light
2012-04-02 11:36:35.361 MyApp[3579:707]     Font name: AmericanTypewriter-Bold
2012-04-02 11:36:35.364 MyApp[3579:707]     Font name: AmericanTypewriter
2012-04-02 11:36:35.368 MyApp[3579:707]     Font name: AmericanTypewriter-CondensedBold
2012-04-02 11:36:35.372 MyApp[3579:707]     Font name: AmericanTypewriter-Condensed
2012-04-02 11:36:35.384 MyApp[3579:707] Family name: AppleGothic
2012-04-02 11:36:35.400 MyApp[3579:707]     Font name: AppleGothic
2012-04-02 11:36:35.406 MyApp[3579:707] Family name: Bangla Sangam MN
2012-04-02 11:36:35.411 MyApp[3579:707]     Font name: BanglaSangamMN-Bold
2012-04-02 11:36:35.414 MyApp[3579:707]     Font name: BanglaSangamMN
2012-04-02 11:36:35.418 MyApp[3579:707] Family name: Noteworthy
2012-04-02 11:36:35.422 MyApp[3579:707]     Font name: Noteworthy-Light
2012-04-02 11:36:35.432 MyApp[3579:707]     Font name: Noteworthy-Bold
2012-04-02 11:36:35.436 MyApp[3579:707] Family name: Zapfino
2012-04-02 11:36:35.443 MyApp[3579:707]     Font name: Zapfino
2012-04-02 11:36:35.448 MyApp[3579:707] Family name: Tamil Sangam MN
2012-04-02 11:36:35.452 MyApp[3579:707]     Font name: TamilSangamMN
2012-04-02 11:36:35.456 MyApp[3579:707]     Font name: TamilSangamMN-Bold
2012-04-02 11:36:35.459 MyApp[3579:707] Family name: DB LCD Temp
2012-04-02 11:36:35.463 MyApp[3579:707]     Font name: DBLCDTempBlack
2012-04-02 11:36:35.467 MyApp[3579:707] Family name: Arial Hebrew
2012-04-02 11:36:35.471 MyApp[3579:707]     Font name: ArialHebrew
2012-04-02 11:36:35.475 MyApp[3579:707]     Font name: ArialHebrew-Bold
2012-04-02 11:36:35.479 MyApp[3579:707] Family name: Chalkduster
2012-04-02 11:36:35.482 MyApp[3579:707]     Font name: Chalkduster
2012-04-02 11:36:35.486 MyApp[3579:707] Family name: Georgia
2012-04-02 11:36:35.490 MyApp[3579:707]     Font name: Georgia-Italic
2012-04-02 11:36:35.493 MyApp[3579:707]     Font name: Georgia-BoldItalic
2012-04-02 11:36:35.497 MyApp[3579:707]     Font name: Georgia-Bold
2012-04-02 11:36:35.501 MyApp[3579:707]     Font name: Georgia
2012-04-02 11:36:35.504 MyApp[3579:707] Family name: Helvetica Neue
2012-04-02 11:36:35.508 MyApp[3579:707]     Font name: HelveticaNeue-Bold
2012-04-02 11:36:35.511 MyApp[3579:707]     Font name: HelveticaNeue-CondensedBlack
2012-04-02 11:36:35.515 MyApp[3579:707]     Font name: HelveticaNeue-Medium
2012-04-02 11:36:35.518 MyApp[3579:707]     Font name: HelveticaNeue
2012-04-02 11:36:35.522 MyApp[3579:707]     Font name: HelveticaNeue-Light
2012-04-02 11:36:35.526 MyApp[3579:707]     Font name: HelveticaNeue-CondensedBold
2012-04-02 11:36:35.529 MyApp[3579:707]     Font name: HelveticaNeue-LightItalic
2012-04-02 11:36:35.532 MyApp[3579:707]     Font name: HelveticaNeue-UltraLightItalic
2012-04-02 11:36:35.536 MyApp[3579:707]     Font name: HelveticaNeue-UltraLight
2012-04-02 11:36:35.540 MyApp[3579:707]     Font name: HelveticaNeue-BoldItalic
2012-04-02 11:36:35.543 MyApp[3579:707]     Font name: HelveticaNeue-Italic
2012-04-02 11:36:35.547 MyApp[3579:707] Family name: Gill Sans
2012-04-02 11:36:35.551 MyApp[3579:707]     Font name: GillSans-LightItalic
2012-04-02 11:36:35.555 MyApp[3579:707]     Font name: GillSans-BoldItalic
2012-04-02 11:36:35.558 MyApp[3579:707]     Font name: GillSans-Italic
2012-04-02 11:36:35.562 MyApp[3579:707]     Font name: GillSans
2012-04-02 11:36:35.565 MyApp[3579:707]     Font name: GillSans-Bold
2012-04-02 11:36:35.569 MyApp[3579:707]     Font name: GillSans-Light
2012-04-02 11:36:35.572 MyApp[3579:707] Family name: Palatino
2012-04-02 11:36:35.576 MyApp[3579:707]     Font name: Palatino-Roman
2012-04-02 11:36:35.580 MyApp[3579:707]     Font name: Palatino-Bold
2012-04-02 11:36:35.583 MyApp[3579:707]     Font name: Palatino-BoldItalic
2012-04-02 11:36:35.587 MyApp[3579:707]     Font name: Palatino-Italic
2012-04-02 11:36:35.591 MyApp[3579:707] Family name: Courier New
2012-04-02 11:36:35.594 MyApp[3579:707]     Font name: CourierNewPSMT
2012-04-02 11:36:35.598 MyApp[3579:707]     Font name: CourierNewPS-BoldMT
2012-04-02 11:36:35.601 MyApp[3579:707]     Font name: CourierNewPS-BoldItalicMT
2012-04-02 11:36:35.605 MyApp[3579:707]     Font name: CourierNewPS-ItalicMT
2012-04-02 11:36:35.608 MyApp[3579:707] Family name: Oriya Sangam MN
2012-04-02 11:36:35.612 MyApp[3579:707]     Font name: OriyaSangamMN-Bold
2012-04-02 11:36:35.616 MyApp[3579:707]     Font name: OriyaSangamMN
2012-04-02 11:36:35.619 MyApp[3579:707] Family name: Didot
2012-04-02 11:36:35.623 MyApp[3579:707]     Font name: Didot-Italic
2012-04-02 11:36:35.627 MyApp[3579:707]     Font name: Didot
2012-04-02 11:36:35.630 MyApp[3579:707]     Font name: Didot-Bold
2012-04-02 11:36:35.634 MyApp[3579:707] Family name: Bodoni 72 Smallcaps
2012-04-02 11:36:35.638 MyApp[3579:707]     Font name: BodoniSvtyTwoSCITCTT-Book

How to use private Github repo as npm dependency

I wasn't able to make the accepted answer work in a Docker container.

What worked for me was to set the Personal Access Token from github in a file .nextrc

ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n  login $GITHUB_READ_TOKEN" > ~/.netrc 
RUN npm install --only=production --force \
  && npm cache clean --force
RUN rm ~/.netrc

in package.json

"my-lib": "github:username/repo",

Simple PHP Pagination script

This is a mix of HTML and code but it's pretty basic, easy to understand and should be fairly simple to decouple to suit your needs I think.

try {

    // Find out how many items are in the table
    $total = $dbh->query('
        SELECT
            COUNT(*)
        FROM
            table
    ')->fetchColumn();

    // How many items to list per page
    $limit = 20;

    // How many pages will there be
    $pages = ceil($total / $limit);

    // What page are we currently on?
    $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
        'options' => array(
            'default'   => 1,
            'min_range' => 1,
        ),
    )));

    // Calculate the offset for the query
    $offset = ($page - 1)  * $limit;

    // Some information to display to the user
    $start = $offset + 1;
    $end = min(($offset + $limit), $total);

    // The "back" link
    $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">&laquo;</a> <a href="?page=' . ($page - 1) . '" title="Previous page">&lsaquo;</a>' : '<span class="disabled">&laquo;</span> <span class="disabled">&lsaquo;</span>';

    // The "forward" link
    $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">&rsaquo;</a> <a href="?page=' . $pages . '" title="Last page">&raquo;</a>' : '<span class="disabled">&rsaquo;</span> <span class="disabled">&raquo;</span>';

    // Display the paging information
    echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';

    // Prepare the paged query
    $stmt = $dbh->prepare('
        SELECT
            *
        FROM
            table
        ORDER BY
            name
        LIMIT
            :limit
        OFFSET
            :offset
    ');

    // Bind the query params
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    // Do we have any results?
    if ($stmt->rowCount() > 0) {
        // Define how we want to fetch the results
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $iterator = new IteratorIterator($stmt);

        // Display the results
        foreach ($iterator as $row) {
            echo '<p>', $row['name'], '</p>';
        }

    } else {
        echo '<p>No results could be displayed.</p>';
    }

} catch (Exception $e) {
    echo '<p>', $e->getMessage(), '</p>';
}

How do I display the value of a Django form field in a template?

I wanted to display the value of a formset field. I concluded this solution, which should work for normal forms too:

{% if form.email.data %} {{ form.email.data }}
{% else %} {{ form.initial.email }} 
{% endif %}

The above solutions didn't worked very well for me, and I doubt they would work in case of prefixed forms (such as wizards and formsets). The solutions using {{ form.data.email }} can't work, because it is a dictionary lookup, and with prefixed forms your field name would look something like '1-email' (wizard and prefixed form) or 'form-1-email' (formset), and the minus sign (-) are not allowed in dotted template lookup expressions.

{{form.field_name.value}} is Django 1.3+ only.

How to change the JDK for a Jenkins job?

Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]

How to check if a column exists in a datatable

You can use operator Contains,

private void ContainColumn(string columnName, DataTable table)
{
    DataColumnCollection columns = table.Columns;        
    if (columns.Contains(columnName))
    {
       ....
    }
}

MSDN - DataColumnCollection.Contains()

Center Plot title in ggplot2

As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

theme(plot.title = element_text(hjust = 0.5))

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

theme_update(plot.title = element_text(hjust = 0.5))

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")

enter image description here

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())

C# how to wait for a webpage to finish loading before continuing

Assuming the "commit" element represents a standard Form submit button then you can attach an event handler to the WebBrowsers Navigated event.

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

I have used

str.replace("'", "");

to replace the single quote in my string. Its working fine for me.

Excel VBA code to copy a specific string to clipboard

If the url is in a cell in your workbook, you can simply copy the value from that cell:

Private Sub CommandButton1_Click()
    Sheets("Sheet1").Range("A1").Copy
End Sub

(Add a button by using the developer tab. Customize the ribbon if it isn't visible.)

If the url isn't in the workbook, you can use the Windows API. The code that follows can be found here: http://support.microsoft.com/kb/210216

After you've added the API calls below, change the code behind the button to copy to the clipboard:

Private Sub CommandButton1_Click()
    ClipBoard_SetData ("http:\\stackoverflow.com")
End Sub

Add a new module to your workbook and paste in the following code:

Option Explicit

Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
   ByVal dwBytes As Long) As Long
Declare Function CloseClipboard Lib "User32" () As Long
Declare Function OpenClipboard Lib "User32" (ByVal hwnd As Long) _
   As Long
Declare Function EmptyClipboard Lib "User32" () As Long
Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
   ByVal lpString2 As Any) As Long
Declare Function SetClipboardData Lib "User32" (ByVal wFormat _
   As Long, ByVal hMem As Long) As Long

Public Const GHND = &H42
Public Const CF_TEXT = 1
Public Const MAXSIZE = 4096

Function ClipBoard_SetData(MyString As String)
   Dim hGlobalMemory As Long, lpGlobalMemory As Long
   Dim hClipMemory As Long, X As Long

   ' Allocate moveable global memory.
   '-------------------------------------------
   hGlobalMemory = GlobalAlloc(GHND, Len(MyString) + 1)

   ' Lock the block to get a far pointer
   ' to this memory.
   lpGlobalMemory = GlobalLock(hGlobalMemory)

   ' Copy the string to this global memory.
   lpGlobalMemory = lstrcpy(lpGlobalMemory, MyString)

   ' Unlock the memory.
   If GlobalUnlock(hGlobalMemory) <> 0 Then
      MsgBox "Could not unlock memory location. Copy aborted."
      GoTo OutOfHere2
   End If

   ' Open the Clipboard to copy data to.
   If OpenClipboard(0&) = 0 Then
      MsgBox "Could not open the Clipboard. Copy aborted."
      Exit Function
   End If

   ' Clear the Clipboard.
   X = EmptyClipboard()

   ' Copy the data to the Clipboard.
   hClipMemory = SetClipboardData(CF_TEXT, hGlobalMemory)

OutOfHere2:

   If CloseClipboard() = 0 Then
      MsgBox "Could not close Clipboard."
   End If

End Function

Angularjs if-then-else construction in expression

This can be done in one line.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

Usage in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

Changing the width of Bootstrap popover

For people who prefer the JavaScript solution. In Bootstrap 4 tip() became getTipElement() and it returns a no jQuery object. So in order to change the width of the popover in Bootstrap 4 you can use:

}).on("show.bs.popover", function() {
    $($(this).data("bs.popover").getTipElement()).css("max-width", "405px");
});

How to set up ES cluster?

Elastic Search 7 changed the configurations for cluster initialisation. What is important to note is the ES instances communicate internally using the Transport layer(TCP) and not the HTTP protocol which is normally used to perform ops on the indices. Below is sample config for 2 machines cluster.

cluster.name: cluster-new
node.name: node-1
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.211
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

Machine 2 config:-

cluster.name: cluster-new
node.name: node-2
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.212
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

cluster.name: This has be same across all the machines that are going to be part of a cluster.

node.name : Identifier for the ES instance. Defaults to machine name if not given.

node.master: specifies whether this ES instance is going to be master or not

node.data: specifies whether this ES instance is going to be data node or not(hold data)

bootsrap.memory_lock: disable swapping.You can start the cluster without setting this flag. But its recommended to set the lock.More info: https://www.elastic.co/guide/en/elasticsearch/reference/master/setup-configuration-memory.html

network.host: 0.0.0.0 if you want to expose the ES instance over network. 0.0.0.0 is different from 127.0.0.1( aka localhost or loopback address). It means all IPv4 addresses on the machine. If machine has multiple ip addresses with a server listening on 0.0.0.0, the client can reach the machine from any of the IPv4 addresses.

http.port: port on which this ES instance will listen to for HTTP requests

transport.host: The IPv4 address of the host(this will be used to communicate with other ES instances running on different machines). More info: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-transport.html

transport.tcp.port: 9300 (the port where the machine will accept the tcp connections)

discovery.seed_hosts: This was changed in recent versions. Initialise all the IPv4 addresses with TCP port(important) of ES instances that are going to be part of this cluster. This is going to be same across all ES instances that are part of this cluster.

cluster.initial_master_nodes: node names(node.name) of the ES machines that are going to participate in master election.(Quorum based decision making :- https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-quorums.html#modules-discovery-quorums)

Spring MVC - HttpMediaTypeNotAcceptableException

response.setHeader("Accept",  "application/json");

HTML select dropdown list

_x000D_
_x000D_
<select>_x000D_
    <option value="" style="display:none">Choose one provider</option>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This way the user cannot see this option, but it shows in the select box.

SQL Server IN vs. EXISTS Performance

The accepted answer is shortsighted and the question a bit loose in that:

1) Neither explicitly mention whether a covering index is present in the left, right, or both sides.

2) Neither takes into account the size of input left side set and input right side set.
(The question just mentions an overall large result set).

I believe the optimizer is smart enough to convert between "in" vs "exists" when there is a significant cost difference due to (1) and (2), otherwise it may just be used as a hint (e.g. exists to encourage use of an a seekable index on the right side).

Both forms can be converted to join forms internally, have the join order reversed, and run as loop, hash or merge--based on the estimated row counts (left and right) and index existence in left, right, or both sides.

"Javac" doesn't work correctly on Windows 10

If you have set all PATH variables correctly after installation, just restart it.

I had the same problem, I had also installed new Windows7 OS then I upgraded it to Win 10. Then i started setup necessary tools like IntelliJ, Java jdk,jre, eclipse so on. In cmd, java -version worked but javac compiler got unrecognized. I checked and all good, the files in the folders, path are correct and so on.

I restarted and checked it again in cmd ,it worked.

How to set the default value for radio buttons in AngularJS?

Set a default value for people with ngInit

<div ng-app>
    <div ng-init="people=1" />
        <input type="radio" ng-model="people" value="1"><label>1</label>
        <input type="radio" ng-model="people" value="2"><label>2</label>
        <input type="radio" ng-model="people" value="3"><label>3</label>
    <ul>
        <li>{{10*people}}€</li>
        <li>{{8*people}}€</li>
        <li>{{30*people}}€</li>
    </ul>
</div>

Demo: Fiddle

Two way sync with rsync

I'm not sure whether it works with two syncing but for the --delete to work you also need to add the --recursive parameter as well.

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

Conditional formatting based on another cell's value

One more example:

If you have Column from A to D, and need to highlight the whole line (e.g. from A to D) if B is "Complete", then you can do it following:

"Custom formula is":  =$B:$B="Completed" 
Background Color:     red 
Range:                A:D

Of course, you can change Range to A:T if you have more columns.

If B contains "Complete", use search as following:

"Custom formula is":  =search("Completed",$B:$B) 
Background Color:     red 
Range:                A:D

javax.persistence.NoResultException: No entity found for query

String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
DrawUnusedBalance drawUnusedBalance = em.unwrap(Session.class)
    .createQuery(hql, DrawUnusedBalance.class)
    .setParameter("today",new LocalDate())
    .uniqueResultOptional()
    .orElseThrow(NotFoundException::new);

How do I find out my MySQL URL, host, port and username?

Easiest way is probably using command status; In the output you'll find database, user, host and port:

mysql> status;
--------------
mysql  Ver 8.0.13 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          43
Current database:       mysql
Current user:           user@localhost
SSL:                    Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter:        ;
Server version:         8.0.13 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    cp852
Conn.  characterset:    cp852
TCP port:               3306
Uptime:                 3 hours 32 min 40 sec

Threads: 3  Questions: 197  Slow queries: 0  Opens: 214  Flush tables: 2  Open tables: 190  Queries per second avg: 0.015
--------------

What are public, private and protected in object oriented programming?

To sum it up,in object oriented programming, everything is modeled into classes and objects. Classes contain properties and methods. Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other .dlls or even other applications.

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

For Each line As String In System.IO.File.ReadAllLines("D:\abc.csv")
    DataGridView1.Rows.Add(line.Split(","))
Next

Laravel - Form Input - Multiple select for a one to many relationship

I agree with user3158900, and I only differ slightly in the way I use it:

{{Form::label('sports', 'Sports')}}
{{Form::select('sports',$aSports,null,array('multiple'=>'multiple','name'=>'sports[]'))}}

However, in my experience the 3rd parameter of the select is a string only, so for repopulating data for a multi-select I have had to do something like this:

<select multiple="multiple" name="sports[]" id="sports">
@foreach($aSports as $aKey => $aSport)
    @foreach($aItem->sports as $aItemKey => $aItemSport)
        <option value="{{$aKey}}" @if($aKey == $aItemKey)selected="selected"@endif>{{$aSport}}</option>
    @endforeach
@endforeach
</select>

Accessing Arrays inside Arrays In PHP

If $a is the array that's passed, $a[76][0]['id'] should give '76' and $a[76][1]['id'] should give '81', but I can't test as I don't have PHP installed on this machine.

How to compare type of an object in Python?

To get the type, use the __class__ member, as in unknown_thing.__class__

Talk of duck-typing is useless here because it doesn't answer a perfectly good question. In my application code I never need to know the type of something, but it's still useful to have a way to learn an object's type. Sometimes I need to get the actual class to validate a unit test. Duck typing gets in the way there because all possible objects have the same API, but only one is correct. Also, sometimes I'm maintaining somebody else's code, and I have no idea what kind of object I've been passed. This is my biggest problem with dynamically typed languages like Python. Version 1 is very easy and quick to develop. Version 2 is a pain in the buns, especially if you didn't write version 1. So sometimes, when I'm working with a function I didn't write, I need to know the type of a parameter, just so I know what methods I can call on it.

That's where the __class__ parameter comes in handy. That (as far as I can tell) is the best way (maybe the only way) to get an object's type.

How do I flush the PRINT buffer in TSQL?

Building on the answer by @JoelCoehoorn, my approach is to leave all my PRINT statements in place, and simply follow them with the RAISERROR statement to cause the flush.

For example:

PRINT 'MyVariableName: ' + @MyVariableName
RAISERROR(N'', 0, 1) WITH NOWAIT

The advantage of this approach is that the PRINT statements can concatenate strings, whereas the RAISERROR cannot. (So either way you have the same number of lines of code, as you'd have to declare and set a variable to use in RAISERROR).

If, like me, you use AutoHotKey or SSMSBoost or an equivalent tool, you can easily set up a shortcut such as "]flush" to enter the RAISERROR line for you. This saves you time if it is the same line of code every time, i.e. does not need to be customised to hold specific text or a variable.

How to check if a variable is not null?

Sometimes if it was not even defined is better to be prepared. For this I used typeof

if(typeof(variable) !== "undefined") {
    //it exist
    if(variable !== null) {
        //and is not null
    }
    else {
        //but is null
    }
}
else {
    //it doesn't
}

How do I create test and train samples from one dataframe with pandas?

I think you also need to a get a copy not a slice of dataframe if you wanna add columns later.

msk = np.random.rand(len(df)) < 0.8
train, test = df[msk].copy(deep = True), df[~msk].copy(deep = True)

Correct way to use get_or_create?

get_or_create returns a tuple.

customer.source, created = Source.objects.get_or_create(name="Website")

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

In the old days, "/opt" was used by UNIX vendors like AT&T, Sun, DEC and 3rd-party vendors to hold "Option" packages; i.e. packages that you might have paid extra money for. I don't recall seeing "/opt" on Berkeley BSD UNIX. They used "/usr/local" for stuff that you installed yourself.

But of course, the true "meaning" of the different directories has always been somewhat vague. That is arguably a good thing, because if these directories had precise (and rigidly enforced) meanings you'd end up with a proliferation of different directory names.

According to the Filesystem Hierarchy Standard, /opt is for "the installation of add-on application software packages". /usr/local is "for use by the system administrator when installing software locally".

How to get first two characters of a string in oracle query?

SUBSTR (documentation):

SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName from shipment

When selected, it's like any other column. You should give it a name (with As keyword), and you can selected other columns in the same statement:

SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName, column2, ... from shipment

docker container ssl certificates

As was suggested in a comment above, if the certificate store on the host is compatible with the guest, you can just mount it directly.

On a Debian host (and container), I've successfully done:

docker run -v /etc/ssl/certs:/etc/ssl/certs:ro ...

How do I calculate someone's age based on a DateTime type birthday?

The following approach (extract from Time Period Library for .NET class DateDiff) considers the calendar of the culture info:

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2 )
{
  return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );
} // YearDiff

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )
{
  if ( date1.Equals( date2 ) )
  {
    return 0;
  }

  int year1 = calendar.GetYear( date1 );
  int month1 = calendar.GetMonth( date1 );
  int year2 = calendar.GetYear( date2 );
  int month2 = calendar.GetMonth( date2 );

  // find the the day to compare
  int compareDay = date2.Day;
  int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );
  if ( compareDay > compareDaysPerMonth )
  {
    compareDay = compareDaysPerMonth;
  }

  // build the compare date
  DateTime compareDate = new DateTime( year1, month2, compareDay,
    date2.Hour, date2.Minute, date2.Second, date2.Millisecond );
  if ( date2 > date1 )
  {
    if ( compareDate < date1 )
    {
      compareDate = compareDate.AddYears( 1 );
    }
  }
  else
  {
    if ( compareDate > date1 )
    {
      compareDate = compareDate.AddYears( -1 );
    }
  }
  return year2 - calendar.GetYear( compareDate );
} // YearDiff

Usage:

// ----------------------------------------------------------------------
public void CalculateAgeSamples()
{
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years
} // CalculateAgeSamples

// ----------------------------------------------------------------------
public void PrintAge( DateTime birthDate, DateTime moment )
{
  Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) );
} // PrintAge

Bootstrap combining rows (rowspan)

_x000D_
_x000D_
div {_x000D_
  height:50px;_x000D_
}_x000D_
.short-div {_x000D_
  height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
  <h1>Responsive Bootstrap</h1>_x000D_
  <div class="row">_x000D_
    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
      <div class="short-div" style="background-color:green">Span 2</div>_x000D_
      <div class="short-div" style="background-color:purple">Span 2</div>_x000D_
    </div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
  <div class="row-fluid">_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
      <div class="short-div" style="background-color:#999">Span 6</div>_x000D_
      <div class="short-div">Span 6</div>_x000D_
    </div>_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

in iPhone App How to detect the screen resolution of the device

See the UIScreen Reference: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScreen_Class/Reference/UIScreen.html

if([[UIScreen mainScreen] respondsToSelector:NSSelectorFromString(@"scale")])
{
    if ([[UIScreen mainScreen] scale] < 1.1)
        NSLog(@"Standard Resolution Device");

    if ([[UIScreen mainScreen] scale] > 1.9)
        NSLog(@"High Resolution Device");
}

Twitter Bootstrap 3 Sticky Footer

Here is a CSS based solution for a fully responsive variable-height sticky footer.
Advantage: footer allows variable height, as height no longer needs to be hard-coded in CSS.

_x000D_
_x000D_
body {_x000D_
  display: -webkit-box;_x000D_
  display: -webkit-flex;_x000D_
  display: -moz-box;_x000D_
  display: -ms-flexbox;_x000D_
  display: flex;_x000D_
  -webkit-box-orient: vertical;_x000D_
  -webkit-box-direction: normal;_x000D_
  -webkit-flex-direction: column;_x000D_
     -moz-box-orient: vertical;_x000D_
     -moz-box-direction: normal;_x000D_
      -ms-flex-direction: column;_x000D_
          flex-direction: column;_x000D_
  min-height: 100vh;_x000D_
}_x000D_
body > * {_x000D_
  -webkit-box-flex: 0;_x000D_
  -webkit-flex-grow: 0;_x000D_
     -moz-box-flex: 0;_x000D_
      -ms-flex-positive: 0;_x000D_
          flex-grow: 0;_x000D_
}_x000D_
body > nav + .container {_x000D_
  -webkit-box-flex: 1;_x000D_
  -webkit-flex-grow: 1;_x000D_
     -moz-box-flex: 1;_x000D_
      -ms-flex-positive: 1;_x000D_
          flex-grow: 1;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
/* Reset CSS and some footer styling. Only needed on StackOverflow */_x000D_
body {_x000D_
  padding: 50px 0 0;_x000D_
  margin: 0;_x000D_
}_x000D_
footer {_x000D_
  background-color: #f8f8f8; _x000D_
  padding: 15px 0 5px; _x000D_
  border-top: 1px solid #e7e7e7;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<!DOCTYPE html>_x000D_
_x000D_
     <!-- Fixed navbar -->_x000D_
    <nav class="navbar navbar-default navbar-fixed-top">_x000D_
      <div class="container">_x000D_
        <div class="navbar-header">_x000D_
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
            <span class="sr-only">Toggle navigation</span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
            <span class="icon-bar"></span>_x000D_
          </button>_x000D_
          <a class="navbar-brand" href="#">Project name</a>_x000D_
        </div>_x000D_
        <div id="navbar" class="collapse navbar-collapse">_x000D_
          <ul class="nav navbar-nav">_x000D_
            <li class="active"><a href="#">Home</a></li>_x000D_
            <li><a href="#about">About</a></li>_x000D_
            <li><a href="#contact">Contact</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li role="separator" class="divider"></li>_x000D_
                <li class="dropdown-header">Nav header</li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
                <li><a href="#">One more separated link</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div><!--/.nav-collapse -->_x000D_
      </div>_x000D_
    </nav>_x000D_
_x000D_
    <!-- Begin page content -->_x000D_
    <div class="container">_x000D_
      <div class="page-header">_x000D_
        <h1>Responsive sticky footer of any height</h1>_x000D_
      </div>_x000D_
      <p class="lead">You can have a sticky footer of any height using this CSS. It's also fully responsive, no JavaScript needed.</p>_x000D_
      _x000D_
    </div>_x000D_
_x000D_
    <footer class="footer">_x000D_
      <div class="container">_x000D_
        <p class="text-muted">Place sticky footer content here.</p>_x000D_
        <p class="text-muted">And some more content.</p>_x000D_
        <p class="text-muted">And more...</p>_x000D_
      </div>_x000D_
    </footer>
_x000D_
_x000D_
_x000D_

And here is the un-prefixed SCSS (for gulp/grunt):

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  > * {
    flex-grow: 0;
  }
  > nav + .container {
    flex-grow: 1;
  }
}

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had Microsoft Access Database Engine 2010 Redistributable already installed on my machine but was still receiving the Microsoft ACE OLEDB Provider error.

Then I recalled that I had upgraded to Office 2016 recently, so, may be I should try reinstalling Microsoft Access Database Engine 2010 Redistributable. And that fixed the problem on my machine.

So, if you have upgraded to different version of MS Office or even repaired/reinstalled your MS Office then try reinstalling Microsoft Access Database Engine 2010 Redistributable before wasting time with finding other fixes. Good luck!

Matplotlib - How to plot a high resolution graph?

For saving the graph:

matplotlib.rcParams['savefig.dpi'] = 300

For displaying the graph when you use plt.show():

matplotlib.rcParams["figure.dpi"] = 100

Just add them at the top

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Read file As String

You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs) to do that.

e.g.

IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)

For adding the correct library:

Add the following to your app/build.gradle file:

dependencies {
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}

or for the Maven repo see -> this link

For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi

Select distinct rows from datatable in Linq

We can get the distinct similar to the example shown below

 //example
           var  distinctValues =  DetailedBreakDown_Table.AsEnumerable().Select(r => new
            {
                InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
                Universe = r.Field<string>("Universe"),
                AsOfDate = _imqDate,
                Ticker = "",
                Cusip = "",
                PortfolioDate = r.Field<DateTime>("PortfolioDate")

            } ).Distinct();

What is the best way to get all the divisors of a number?

Old question, but here is my take:

def divs(n, m):
    if m == 1: return [1]
    if n % m == 0: return [m] + divs(n, m - 1)
    return divs(n, m - 1)

You can proxy with:

def divisorGenerator(n):
    for x in reversed(divs(n, n)):
        yield x

NOTE: For languages that support, this could be tail recursive.

Is a LINQ statement faster than a 'foreach' loop?

This is actually quite a complex question. Linq makes certain things very easy to do, that if you implement them yourself, you might stumble over (e.g. linq .Except()). This particularly applies to PLinq, and especially to parallel aggregation as implemented by PLinq.

In general, for identical code, linq will be slower, because of the overhead of delegate invocation.

If, however, you are processing a large array of data, and applying relatively simple calculations to the elements, you will get a huge performance increase if:

  1. You use an array to store the data.
  2. You use a for loop to access each element (as opposed to foreach or linq).

    • Note: When benchmarking, please everyone remember - if you use the same array/list for two consecutive tests, the CPU cache will make the second one faster. *

Setting default value for TypeScript object passed as argument

This can be a nice way to do it that does not involve long constructors

class Person {
    firstName?: string = 'Bob';
    lastName?: string = 'Smith';

    // Pass in this class as the required params
    constructor(params: Person) {
        // object.assign will overwrite defaults if params exist
        Object.assign(this, params)
    }
}

// you can still use the typing 
function sayName(params: Person){ 
    let name = params.firstName + params.lastName
    alert(name)
}

// you do have to call new but for my use case this felt better
sayName(new Person({firstName: 'Gordon'}))
sayName(new Person({lastName: 'Thomas'}))

Wildcards in a Windows hosts file

Configuration for nginx config auto subdomain with Acrylic DNS Proxy

auto.conf file for your nginx sites folder

server {
    listen 80;
    server_name ~^(?<branch>.*)\.example\.com;
    root /var/www/html/$branch/public;  

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_log  /var/log/nginx/$branch.error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ \.php$ {
       try_files $uri /index.php =404;
       fastcgi_pass php-fpm:9000;
       fastcgi_index index.php;
       fastcgi_buffers 16 16k;
       fastcgi_buffer_size 32k;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

Add to Acrylic hosts file 127.0.0.1 example.com *.example.com and restart Acrylic service. $branch - your subdomain name.

Set instead of root /var/www/html/$branch/public; your project path

How to upgrade Git on Windows to the latest version?

Just give the following command with your command prompt.

git update-git-for-windows

This will ask you a confirmation as follows. Press Y to proceed.

enter image description here

Once the files are dowloaded, Continue with normal installation procedures. You can check the git version after finishing installation with the following command

git version

For me, the result was as follows.

enter image description here

Using C++ filestreams (fstream), how can you determine the size of a file?

I'm a novice, but this is my self taught way of doing it:

ifstream input_file("example.txt", ios::in | ios::binary)

streambuf* buf_ptr =  input_file.rdbuf(); //pointer to the stream buffer

input.get(); //extract one char from the stream, to activate the buffer
input.unget(); //put the character back to undo the get()

size_t file_size = buf_ptr->in_avail();
//a value of 0 will be returned if the stream was not activated, per line 3.

Transpose a data frame

You'd better not transpose the data.frame while the name column is in it - all numeric values will then be turned into strings!

Here's a solution that keeps numbers as numbers:

# first remember the names
n <- df.aree$name

# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))

str(df.aree) # Check the column types

How to validate an email address using a regular expression?

Quick answer

Use the following regex for input validation:

([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)+

Addresses matched by this regex:

  • have a local part (i.e. the part before the @-sign) that is strictly compliant with RFC 5321/5322,
  • have a domain part (i.e. the part after the @-sign) that is a host name with at least two labels, each of which is at most 63 characters long.

The second constraint is a restriction on RFC 5321/5322.

Elaborate answer

Using a regular expression that recognizes email addresses could be useful in various situations: for example to scan for email addresses in a document, to validate user input, or as an integrity constraint on a data repository.

It should however be noted that if you want to find out if the address actually refers to an existing mailbox, there's no substitute for sending a message to the address. If you only want to check if an address is grammatically correct then you could use a regular expression, but note that ""@[] is a grammatically correct email address that certainly doesn't refer to an existing mailbox.

The syntax of email addresses has been defined in various RFCs, most notably RFC 822 and RFC 5322. RFC 822 should be seen as the "original" standard and RFC 5322 as the latest standard. The syntax defined in RFC 822 is the most lenient and subsequent standards have restricted the syntax further and further, where newer systems or services should recognize obsolete syntax, but never produce it.

In this answer I’ll take “email address” to mean addr-spec as defined in the RFCs (i.e. [email protected], but not "John Doe"<[email protected]>, nor some-group:[email protected],[email protected];).

There's one problem with translating the RFC syntaxes into regexes: the syntaxes are not regular! This is because they allow for optional comments in email addresses that can be infinitely nested, while infinite nesting can't be described by a regular expression. To scan for or validate addresses containing comments you need a parser or more powerful expressions. (Note that languages like Perl have constructs to describe context free grammars in a regex-like way.) In this answer I'll disregard comments and only consider proper regular expressions.

The RFCs define syntaxes for email messages, not for email addresses as such. Addresses may appear in various header fields and this is where they are primarily defined. When they appear in header fields addresses may contain (between lexical tokens) whitespace, comments and even linebreaks. Semantically this has no significance however. By removing this whitespace, etc. from an address you get a semantically equivalent canonical representation. Thus, the canonical representation of first. last (comment) @ [3.5.7.9] is first.last@[3.5.7.9].

Different syntaxes should be used for different purposes. If you want to scan for email addresses in a (possibly very old) document it may be a good idea to use the syntax as defined in RFC 822. On the other hand, if you want to validate user input you may want to use the syntax as defined in RFC 5322, probably only accepting canonical representations. You should decide which syntax applies to your specific case.

I use POSIX "extended" regular expressions in this answer, assuming an ASCII compatible character set.

RFC 822

I arrived at the following regular expression. I invite everyone to try and break it. If you find any false positives or false negatives, please post them in a comment and I'll try to fix the expression as soon as possible.

([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]))*(\\\r)*")(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]))*(\\\r)*"))*@([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]))*(\\\r)*])(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]))*(\\\r)*]))*

I believe it's fully complient with RFC 822 including the errata. It only recognizes email addresses in their canonical form. For a regex that recognizes (folding) whitespace see the derivation below.

The derivation shows how I arrived at the expression. I list all the relevant grammar rules from the RFC exactly as they appear, followed by the corresponding regex. Where an erratum has been published I give a separate expression for the corrected grammar rule (marked "erratum") and use the updated version as a subexpression in subsequent regular expressions.

As stated in paragraph 3.1.4. of RFC 822 optional linear white space may be inserted between lexical tokens. Where applicable I've expanded the expressions to accommodate this rule and marked the result with "opt-lwsp".

CHAR        =  <any ASCII character>
            =~ .

CTL         =  <any ASCII control character and DEL>
            =~ [\x00-\x1F\x7F]

CR          =  <ASCII CR, carriage return>
            =~ \r

LF          =  <ASCII LF, linefeed>
            =~ \n

SPACE       =  <ASCII SP, space>
            =~  

HTAB        =  <ASCII HT, horizontal-tab>
            =~ \t

<">         =  <ASCII quote mark>
            =~ "

CRLF        =  CR LF
            =~ \r\n

LWSP-char   =  SPACE / HTAB
            =~ [ \t]

linear-white-space =  1*([CRLF] LWSP-char)
                   =~ ((\r\n)?[ \t])+

specials    =  "(" / ")" / "<" / ">" / "@" /  "," / ";" / ":" / "\" / <"> /  "." / "[" / "]"
            =~ [][()<>@,;:\\".]

quoted-pair =  "\" CHAR
            =~ \\.

qtext       =  <any CHAR excepting <">, "\" & CR, and including linear-white-space>
            =~ [^"\\\r]|((\r\n)?[ \t])+

dtext       =  <any CHAR excluding "[", "]", "\" & CR, & including linear-white-space>
            =~ [^][\\\r]|((\r\n)?[ \t])+

quoted-string  =  <"> *(qtext|quoted-pair) <">
               =~ "([^"\\\r]|((\r\n)?[ \t])|\\.)*"
(erratum)      =~ "(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*"

domain-literal =  "[" *(dtext|quoted-pair) "]"
               =~ \[([^][\\\r]|((\r\n)?[ \t])|\\.)*]
(erratum)      =~ \[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*]

atom        =  1*<any CHAR except specials, SPACE and CTLs>
            =~ [^][()<>@,;:\\". \x00-\x1F\x7F]+

word        =  atom / quoted-string
            =~ [^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*"

domain-ref  =  atom

sub-domain  =  domain-ref / domain-literal
            =~ [^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*]

local-part  =  word *("." word)
            =~ ([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*")(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*"))*
(opt-lwsp)  =~ ([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*")(((\r\n)?[ \t])*\.((\r\n)?[ \t])*([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*"))*

domain      =  sub-domain *("." sub-domain)
            =~ ([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*])(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*]))*
(opt-lwsp)  =~ ([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*])(((\r\n)?[ \t])*\.((\r\n)?[ \t])*([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*]))*

addr-spec   =  local-part "@" domain
            =~ ([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*")(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*"))*@([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*])(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*]))*
(opt-lwsp)  =~ ([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*")((\r\n)?[ \t])*(\.((\r\n)?[ \t])*([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*")((\r\n)?[ \t])*)*@((\r\n)?[ \t])*([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*])(((\r\n)?[ \t])*\.((\r\n)?[ \t])*([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]|(\r\n)?[ \t]))*(\\\r)*]))*
(canonical) =~ ([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]))*(\\\r)*")(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|"(\n|(\\\r)*([^"\\\r\n]|\\[^\r]))*(\\\r)*"))*@([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]))*(\\\r)*])(\.([^][()<>@,;:\\". \x00-\x1F\x7F]+|\[(\n|(\\\r)*([^][\\\r\n]|\\[^\r]))*(\\\r)*]))*

RFC 5322

I arrived at the following regular expression. I invite everyone to try and break it. If you find any false positives or false negatives, please post them in a comment and I'll try to fix the expression as soon as possible.

([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*])

I believe it's fully complient with RFC 5322 including the errata. It only recognizes email addresses in their canonical form. For a regex that recognizes (folding) whitespace see the derivation below.

The derivation shows how I arrived at the expression. I list all the relevant grammar rules from the RFC exactly as they appear, followed by the corresponding regex. For rules that include semantically irrelevant (folding) whitespace, I give a separate regex marked "(normalized)" that doesn't accept this whitespace.

I ignored all the "obs-" rules from the RFC. This means that the regexes only match email addresses that are strictly RFC 5322 compliant. If you have to match "old" addresses (as the looser grammar including the "obs-" rules does), you can use one of the RFC 822 regexes from the previous paragraph.

VCHAR           =   %x21-7E
                =~  [!-~]

ALPHA           =   %x41-5A / %x61-7A
                =~  [A-Za-z]

DIGIT           =   %x30-39
                =~  [0-9]

HTAB            =   %x09
                =~  \t

CR              =   %x0D
                =~  \r

LF              =   %x0A
                =~  \n

SP              =   %x20
                =~  

DQUOTE          =   %x22
                =~  "

CRLF            =   CR LF
                =~  \r\n

WSP             =   SP / HTAB
                =~  [\t ]

quoted-pair     =   "\" (VCHAR / WSP)
                =~  \\[\t -~]

FWS             =   ([*WSP CRLF] 1*WSP)
                =~  ([\t ]*\r\n)?[\t ]+

ctext           =   %d33-39 / %d42-91 / %d93-126
                =~  []!-'*-[^-~]

("comment" is left out in the regex)
ccontent        =   ctext / quoted-pair / comment
                =~  []!-'*-[^-~]|(\\[\t -~])

(not regular)
comment         =   "(" *([FWS] ccontent) [FWS] ")"

(is equivalent to FWS when leaving out comments)
CFWS            =   (1*([FWS] comment) [FWS]) / FWS
                =~  ([\t ]*\r\n)?[\t ]+

atext           =   ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
                =~  [-!#-'*+/-9=?A-Z^-~]

dot-atom-text   =   1*atext *("." 1*atext)
                =~  [-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*

dot-atom        =   [CFWS] dot-atom-text [CFWS]
                =~  (([\t ]*\r\n)?[\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*(([\t ]*\r\n)?[\t ]+)?
(normalized)    =~  [-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*

qtext           =   %d33 / %d35-91 / %d93-126
                =~  []!#-[^-~]

qcontent        =   qtext / quoted-pair
                =~  []!#-[^-~]|(\\[\t -~])

(erratum)
quoted-string   =   [CFWS] DQUOTE ((1*([FWS] qcontent) [FWS]) / FWS) DQUOTE [CFWS]
                =~  (([\t ]*\r\n)?[\t ]+)?"(((([\t ]*\r\n)?[\t ]+)?([]!#-[^-~]|(\\[\t -~])))+(([\t ]*\r\n)?[\t ]+)?|(([\t ]*\r\n)?[\t ]+)?)"(([\t ]*\r\n)?[\t ]+)?
(normalized)    =~  "([]!#-[^-~ \t]|(\\[\t -~]))+"

dtext           =   %d33-90 / %d94-126
                =~  [!-Z^-~]

domain-literal  =   [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
                =~  (([\t ]*\r\n)?[\t ]+)?\[((([\t ]*\r\n)?[\t ]+)?[!-Z^-~])*(([\t ]*\r\n)?[\t ]+)?](([\t ]*\r\n)?[\t ]+)?
(normalized)    =~  \[[\t -Z^-~]*]

local-part      =   dot-atom / quoted-string
                =~  (([\t ]*\r\n)?[\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*(([\t ]*\r\n)?[\t ]+)?|(([\t ]*\r\n)?[\t ]+)?"(((([\t ]*\r\n)?[\t ]+)?([]!#-[^-~]|(\\[\t -~])))+(([\t ]*\r\n)?[\t ]+)?|(([\t ]*\r\n)?[\t ]+)?)"(([\t ]*\r\n)?[\t ]+)?
(normalized)    =~  [-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+"

domain          =   dot-atom / domain-literal
                =~  (([\t ]*\r\n)?[\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*(([\t ]*\r\n)?[\t ]+)?|(([\t ]*\r\n)?[\t ]+)?\[((([\t ]*\r\n)?[\t ]+)?[!-Z^-~])*(([\t ]*\r\n)?[\t ]+)?](([\t ]*\r\n)?[\t ]+)?
(normalized)    =~  [-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*]

addr-spec       =   local-part "@" domain
                =~  ((([\t ]*\r\n)?[\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*(([\t ]*\r\n)?[\t ]+)?|(([\t ]*\r\n)?[\t ]+)?"(((([\t ]*\r\n)?[\t ]+)?([]!#-[^-~]|(\\[\t -~])))+(([\t ]*\r\n)?[\t ]+)?|(([\t ]*\r\n)?[\t ]+)?)"(([\t ]*\r\n)?[\t ]+)?)@((([\t ]*\r\n)?[\t ]+)?[-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*(([\t ]*\r\n)?[\t ]+)?|(([\t ]*\r\n)?[\t ]+)?\[((([\t ]*\r\n)?[\t ]+)?[!-Z^-~])*(([\t ]*\r\n)?[\t ]+)?](([\t ]*\r\n)?[\t ]+)?)
(normalized)    =~  ([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*])

Note that some sources (notably w3c) claim that RFC 5322 is too strict on the local part (i.e. the part before the @-sign). This is because "..", "a..b" and "a." are not valid dot-atoms, while they may be used as mailbox names. The RFC, however, does allow for local parts like these, except that they have to be quoted. So instead of [email protected] you should write "a..b"@example.net, which is semantically equivalent.

Further restrictions

SMTP (as defined in RFC 5321) further restricts the set of valid email addresses (or actually: mailbox names). It seems reasonable to impose this stricter grammar, so that the matched email address can actually be used to send an email.

RFC 5321 basically leaves alone the "local" part (i.e. the part before the @-sign), but is stricter on the domain part (i.e. the part after the @-sign). It allows only host names in place of dot-atoms and address literals in place of domain literals.

The grammar presented in RFC 5321 is too lenient when it comes to both host names and IP addresses. I took the liberty of "correcting" the rules in question, using this draft and RFC 1034 as guidelines. Here's the resulting regex.

([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@([0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)*|\[((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)|(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+)])

Note that depending on the use case you may not want to allow for a "General-address-literal" in your regex. Also note that I used a negative lookahead (?!IPv6:) in the final regex to prevent the "General-address-literal" part to match malformed IPv6 addresses. Some regex processors don't support negative lookahead. Remove the substring |(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+ from the regex if you want to take the whole "General-address-literal" part out.

Here's the derivation:

Let-dig         =   ALPHA / DIGIT
                =~  [0-9A-Za-z]

Ldh-str         =   *( ALPHA / DIGIT / "-" ) Let-dig
                =~  [0-9A-Za-z-]*[0-9A-Za-z]

(regex is updated to make sure sub-domains are max. 63 charactes long - RFC 1034 section 3.5)
sub-domain      =   Let-dig [Ldh-str]
                =~  [0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?

Domain          =   sub-domain *("." sub-domain)
                =~  [0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)*

Snum            =   1*3DIGIT
                =~  [0-9]{1,3}

(suggested replacement for "Snum")
ip4-octet       =   DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35
                =~  25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9]

IPv4-address-literal    =   Snum 3("."  Snum)
                        =~  [0-9]{1,3}(\.[0-9]{1,3}){3}

(suggested replacement for "IPv4-address-literal")
ip4-address     =   ip4-octet 3("." ip4-octet)
                =~  (25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}

(suggested replacement for "IPv6-hex")
ip6-h16         =   "0" / ( (%x49-57 / %x65-70 /%x97-102) 0*3(%x48-57 / %x65-70 /%x97-102) )
                =~  0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}

(not from RFC)
ls32            =   ip6-h16 ":" ip6-h16 / ip4-address
                =~  (0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}

(suggested replacement of "IPv6-addr")
ip6-address     =                                      6(ip6-h16 ":") ls32
                    /                             "::" 5(ip6-h16 ":") ls32
                    / [                 ip6-h16 ] "::" 4(ip6-h16 ":") ls32
                    / [ *1(ip6-h16 ":") ip6-h16 ] "::" 3(ip6-h16 ":") ls32
                    / [ *2(ip6-h16 ":") ip6-h16 ] "::" 2(ip6-h16 ":") ls32
                    / [ *3(ip6-h16 ":") ip6-h16 ] "::"   ip6-h16 ":"  ls32
                    / [ *4(ip6-h16 ":") ip6-h16 ] "::"                ls32
                    / [ *5(ip6-h16 ":") ip6-h16 ] "::"   ip6-h16
                    / [ *6(ip6-h16 ":") ip6-h16 ] "::"
                =~  (((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::

IPv6-address-literal    =   "IPv6:" ip6-address
                        =~  IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)

Standardized-tag        =   Ldh-str
                        =~  [0-9A-Za-z-]*[0-9A-Za-z]

dcontent        =   %d33-90 / %d94-126
                =~  [!-Z^-~]

General-address-literal =   Standardized-tag ":" 1*dcontent
                        =~  [0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+

address-literal =   "[" ( IPv4-address-literal / IPv6-address-literal / General-address-literal ) "]"
                =~  \[((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)|(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+)]

Mailbox         =   Local-part "@" ( Domain / address-literal )
                =~  ([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@([0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)*|\[((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|IPv6:((((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){6}|::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){5}|[0-9A-Fa-f]{0,4}::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){4}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):)?(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){3}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,2}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){2}|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,3}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,4}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,5}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3})|(((0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}):){0,6}(0|[1-9A-Fa-f][0-9A-Fa-f]{0,3}))?::)|(?!IPv6:)[0-9A-Za-z-]*[0-9A-Za-z]:[!-Z^-~]+)])

User input validation

A common use case is user input validation, for example on an html form. In that case it's usually reasonable to preclude address-literals and to require at least two labels in the hostname. Taking the improved RFC 5321 regex from the previous section as a basis, the resulting expression would be:

([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)+

I do not recommend restricting the local part further, e.g. by precluding quoted strings, since we don't know what kind of mailbox names some hosts allow (like "a..b"@example.net or even "a b"@example.net).

I also do not recommend explicitly validating against a list of literal top-level domains or even imposing length-constraints (remember how ".museum" invalidated [a-z]{2,4}), but if you must:

([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@([0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?\.)*(net|org|com|info|etc...)

Make sure to keep your regex up-to-date if you decide to go down the path of explicit top-level domain validation.

Further considerations

When only accepting host names in the domain part (after the @-sign), the regexes above accept only labels with at most 63 characters, as they should. However, they don't enforce the fact that the entire host name must be at most 253 characters long (including the dots). Although this constraint is strictly speaking still regular, it's not feasible to make a regex that incorporates this rule.

Another consideration, especially when using the regexes for input validation, is feedback to the user. If a user enters an incorrect address, it would be nice to give a little more feedback than a simple "syntactically incorrect address". With "vanilla" regexes this is not possible.

These two considerations could be addressed by parsing the address. The extra length constraint on host names could in some cases also be addressed by using an extra regex that checks it, and matching the address against both expressions.

None of the regexes in this answer are optimized for performance. If performance is an issue, you should see if (and how) the regex of your choice can be optimized.

"break;" out of "if" statement?

This is actually the conventional use of the break statement. If the break statement wasn't nested in an if block the for loop could only ever execute one time.

MSDN lists this as their example for the break statement.

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

How to find out if you're using HTTPS without $_SERVER['HTTPS']

The REAL answer: ready for copy-paste into a [config] script

/* configuration settings; X=edit may 10th '11 */
$pv_sslport=443; /* for it might be different, as also Gabriel Sosa stated */
$pv_serverport=80; /* X */
$pv_servername="mysite.com"; /* X */

/* X appended after correction by Michael Kopinsky */
if(!isset($_SERVER["SERVER_NAME"]) || !$_SERVER["SERVER_NAME"]) {
    if(!isset($_ENV["SERVER_NAME"])) {
        getenv("SERVER_NAME");
        // Set to env server_name
        $_SERVER["SERVER_NAME"]=$_ENV["SERVER_NAME"];
    }
}
if(!$_SERVER["SERVER_NAME"]) (
    /* X server name still empty? ... you might set $_SERVER["SERVER_NAME"]=$pv_servername; */
}

if(!isset($_SERVER["SERVER_PORT"]) || !$_SERVER["SERVER_PORT"]) {
    if(!isset($_ENV["SERVER_PORT"])) {
        getenv("SERVER_PORT");
        $_SERVER["SERVER_PORT"]=$_ENV["SERVER_PORT"];
    }
}
if(!$_SERVER["SERVER_PORT"]) (
    /* X server port still empty? ... you might set $_SERVER["SERVER_PORT"]=$pv_serverport; */
}

$pv_URIprotocol = isset($_SERVER["HTTPS"]) ? (($_SERVER["HTTPS"]==="on" || $_SERVER["HTTPS"]===1 || $_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://") :  (($_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://");

$pv_URIprotocol is now correct and ready to be used; example $site=$pv_URIprotocol.$_SERVER["SERVER_NAME"]. Naturally, the string could be replaced with TRUE and FALSE also. PV stands for PortalPress Variable as it is a direct copy-paste which will always work. This piece can be used in a production script.

Phone number formatting an EditText in Android

Maybe below sample project helps you;

https://github.com/reinaldoarrosi/MaskedEditText

That project contains a view class call MaskedEditText. As first, you should add it in your project.

Then you add below xml part in res/values/attrs.xml file of project;

<resources>
    <declare-styleable name="MaskedEditText">
        <attr name="mask" format="string" />
        <attr name="placeholder" format="string" />
    </declare-styleable>
</resources>

Then you will be ready to use MaskedEditText view.

As last, you should add MaskedEditText in your xml file what you want like below;

<packagename.currentfolder.MaskedEditText
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/maskedEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:text="5"
    app:mask="(999) 999-9999"
    app:placeholder="_" >

Of course that, you can use it programmatically.

After those steps, adding MaskedEditText will appear like below;

enter image description here

As programmatically, if you want to take it's text value as unmasked, you may use below row;

maskedEditText.getText(true);

To take masked value, you may send false value instead of true value in the getText method.

How to empty a file using Python

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass

Maximum number of threads in a .NET app?

Jeff Richter in CLR via C#:

"With version 2.0 of the CLR, the maximum number of worker threads default to 25 per CPU in the machine and the maximum number of I/O threads defaults to 1000. A limit of 1000 is effectively no limit at all."

Note this is based on .NET 2.0. This may have changed in .NET 3.5.

[Edit] As @Mitch pointed out, this is specific to the CLR ThreadPool. If you're creating threads directly see the @Mitch and others comments.

How to determine if binary tree is balanced?

RE: @lucky's solution using a BFS to do a level-order traversal.

We traverse the tree and keep a reference to vars min/max-level which describe the minimum level at which a node is a leaf.

I believe that the @lucky solution requires a modification. As suggested by @codaddict, rather than checking if a node is a leaf, we must check if EITHER the left or right children is null (not both). Otherwise, the algorithm would consider this a valid balanced tree:

     1
    / \
   2   4
    \   \
     3   1

In Python:

def is_bal(root):
    if root is None:
        return True

    import queue

    Q = queue.Queue()
    Q.put(root)

    level = 0
    min_level, max_level = sys.maxsize, sys.minsize

    while not Q.empty():
        level_size = Q.qsize()

        for i in range(level_size):
            node = Q.get()

            if not node.left or node.right:
                min_level, max_level = min(min_level, level), max(max_level, level)

            if node.left:
                Q.put(node.left)
            if node.right:
                Q.put(node.right)

        level += 1

        if abs(max_level - min_level) > 1:
            return False

    return True

This solution should satisfy all the stipulations provided in the initial question, operating in O(n) time and O(n) space. Memory overflow would be directed to the heap rather than blowing a recursive call-stack.

Alternatively, we could initially traverse the tree to compute + cache max heights for each root subtree iteratively. Then in another iterative run, check if the cached heights of the left and right subtrees for each root never differ by more than one. This would also run in O(n) time and O(n) space but iteratively so as not to cause stack overflow.

Declaring variable workbook / Worksheet vba

I had the same issue. I used Worksheet instead of Worksheets and it was resolved. Not sure what the difference is between them.

Access event to call preventdefault from custom function originating from onclick attribute of tag

Add a unique class to the links and a javascript that prevents default on links with this class:

<a href="#" class="prevent-default" 
   onclick="$('.comment .hidden').toggle();">Show comments</a>

<script>
  $(document).ready(function(){

    $("a.prevent-default").click(function(event) {
         event.preventDefault(); 
          });
  });
</script>

How to specify a min but no max decimal using the range data annotation attribute?

If you're working with prices, I'm sure you can safely assume nothing will cost more than 1 trillion dollars.

I'd use:

[Range(0.0, 1000000000000)]

Or if you really need it, just paste in the value of Decimal.MaxValue (without the commas): 79,228,162,514,264,337,593,543,950,335

Either one of these will work well if you're not from Zimbabwe.

Getting each individual digit from a whole integer

You use the modulo operator:

while(score)
{
    printf("%d\n", score % 10);
    score /= 10;
}

Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.

Windows command to convert Unix line endings?

This can actually be done very easily using the more command which is included in Windows NT and later. To convert input_filename which contains UNIX EOL (End Of Line) \n to output_filename which contains Windows EOL \r\n, just do this:

TYPE input_filename | MORE /P > output_filename

The more command has additional formatting options that you may not be aware of. Run more/? to learn what else more can do.

What is the purpose of "&&" in a shell command?

A quite common usage for '&&' is compiling software with autotools. For example:

./configure --prefix=/usr && make && sudo make install

Basically if the configure succeeds, make is run to compile, and if that succeeds, make is run as root to install the program. I use this when I am mostly sure that things will work, and it allows me to do other important things like look at stackoverflow an not 'monitor' the progress.

Sometimes I get really carried away...

tar xf package.tar.gz && ( cd package; ./configure && make && sudo make install ) && rm package -rf

I do this when for example making a linux from scratch box.

How can I parse a CSV string with JavaScript, which contains comma in data?

You can use papaparse.js like the example below:

<!DOCTYPE html>
<html lang="en">

    <head>
        <title>CSV</title>
    </head>

    <body>
        <input type="file" id="files" multiple="">
        <button onclick="csvGetter()">CSV Getter</button>
        <h3>The Result will be in the Console.</h3>

        <script src="papaparse.min.js"></script>

        <script>
            function csvGetter() {

                var file = document.getElementById('files').files[0];
                Papa.parse(file, {
                    complete: function(results) {
                        console.log(results.data);
                    }
                });
            }
          </script>
    </body>

</html>

Don't forget to include papaparse.js in the same folder.

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

Copy to Clipboard for all Browsers using javascript

This works on firefox 3.6.x and IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

Matching an empty input box using CSS

It worked for me to add a class name to the input and then apply CSS rules to that:

<input type="text" name="product" class="product" />

<style>
input[value=""].product {
    display: none;
}
</style>

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Accessing localhost of PC from USB connected Android mobile device

How to Easily access LocalHost in Actual Android Device -> Connect your pc with the android device via USB

  1. Go to Chrome inspection click 'f12' or Control+Shift+C

Chrome Inspection tool

  1. Check the bottom of the chrome inspection tool.

  2. Now go to settings in Remote Device Tab.

Remote Devices Tab

  1. check on "Discover USB Device" option as well as check on "Port Forwarding" option.

  2. Now Click on Add Rules, Enter Any Device Port e.g(4880) and in Local Address Enter the Actual Address of the local host in my case e.g (127.0.0.1:480)

  3. After Adding the Rule go to your android studio -> inside your code URL(http://127.0.0.1:4880). Remember to change the port from 480 -> 4880.

  4. Go to Remote Device Tab in Chrome and Click on your connected Device. Add New URL(127.0.0.1:4880) Inspect the Android Device Chrome Browser

Check your Actual Device Chrome Browser and start Debugging the code on Actual Android device.

How do you express binary literals in Python?

I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().

EDIT: lbrandy's answer is correct in all cases.

How can I make the cursor turn to the wait cursor?

You can use Cursor.Current.

// Set cursor as hourglass
Cursor.Current = Cursors.WaitCursor;

// Execute your time-intensive hashing code here...

// Set cursor as default arrow
Cursor.Current = Cursors.Default;

However, if the hashing operation is really lengthy (MSDN defines this as more than 2-7 seconds), you should probably use a visual feedback indicator other than the cursor to notify the user of the progress. For a more in-depth set of guidelines, see this article.

Edit:
As @Am pointed out, you may need to call Application.DoEvents(); after Cursor.Current = Cursors.WaitCursor; to ensure that the hourglass is actually displayed.

How to create an executable .exe file from a .m file

Try:

mcc -m yourfile

Also see help mcc

What is the maximum length of a Push Notification alert text?

Here're some screenshots (banner, alert, & notification center)

AlertBannerNotification Center

Display encoded html with razor

this is pretty simple:

HttpUtility.HtmlDecode(Model.Content)

Another Solution, you could also return a HTMLString, Razor will output the correct formatting:

in the view itself:

@Html.GetSomeHtml()

in controller:

public static HtmlString GetSomeHtml()
{
    var Data = "abc<br/>123";
    return new HtmlString(Data);
}

com.jcraft.jsch.JSchException: UnknownHostKey

Supply the public rsa key of the host :-

String knownHostPublicKey = "mywebsite.com ssh-rsa AAAAB3NzaC1.....XL4Jpmp/";

session.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

How do I get a reference to the app delegate in Swift?

it is very simple

App delegate instance

let app = UIApplication.shared.delegate as! AppDelegate

you can call a method with one line syntax

app.callingMethod()

you can access a variable with this code

app.yourVariable = "Assigning a value"

Is Python strongly typed?

It's already been answered a few times, but Python is a strongly typed language:

>>> x = 3
>>> y = '4'
>>> print(x+y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The following in JavaScript:

var x = 3    
var y = '4'
alert(x + y) //Produces "34"

That's the difference between weak typing and strong typing. Weak types automatically try to convert from one type to another, depending on context (e.g. Perl). Strong types never convert implicitly.

Your confusion lies in a misunderstanding of how Python binds values to names (commonly referred to as variables).

In Python, names have no types, so you can do things like:

bob = 1
bob = "bob"
bob = "An Ex-Parrot!"

And names can be bound to anything:

>>> def spam():
...     print("Spam, spam, spam, spam")
...
>>> spam_on_eggs = spam
>>> spam_on_eggs()
Spam, spam, spam, spam

For further reading:

https://en.wikipedia.org/wiki/Dynamic_dispatch

and the slightly related but more advanced:

http://effbot.org/zone/call-by-object.htm

How can I remove non-ASCII characters but leave periods and spaces using Python?

You can filter all characters from the string that are not printable using string.printable, like this:

>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'

string.printable on my machine contains:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c

EDIT: On Python 3, filter will return an iterable. The correct way to obtain a string back would be:

''.join(filter(lambda x: x in printable, s))

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

How to use git merge --squash?

What finally cleared this up for me was a comment showing that:

git checkout main
git merge --squash feature

is the equivalent of doing:

git checkout feature
git diff main > feature.patch
git checkout main
patch -p1 < feature.patch
git add .

When I want to merge a feature branch with 105(!!) commits and have them all squashed into one, I don't want to git rebase -i origin/master because I need to separately resolve merge conflicts for each of the intermediate commits (or at least the ones which git can't figure out itself). Using git merge --squash gets me the result I want, of a single commit for merging an entire feature branch. And, I only need to do at most one manual conflict resolution.

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

Why does Java have an "unreachable statement" compiler error?

It is Nanny. I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).

How can I get the current PowerShell executing file?

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

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

Write-Host $currentExecutingPath

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

Change visibility of ASP.NET label with JavaScript

Continuing with what Dave Ward said:

  • You can't set the Visible property to false because the control will not be rendered.
  • You should use the Style property to set it's display to none.

Page/Control design

<asp:Label runat="server" ID="Label1" Style="display: none;" />

<asp:Button runat="server" ID="Button1" />

Code behind

Somewhere in the load section:

Label label1 = (Label)FindControl("Label1");
((Label)FindControl("Button1")).OnClientClick = "ToggleVisibility('" + label1.ClientID + "')";

Javascript file

function ToggleVisibility(elementID)
{
    var element = document.getElementByID(elementID);

    if (element.style.display = 'none')
    {
        element.style.display = 'inherit';
    }
    else
    {
        element.style.display = 'none';
    }
}

Of course, if you don't want to toggle but just to show the button/label then adjust the javascript method accordingly.

The important point here is that you need to send the information about the ClientID of the control that you want to manipulate on the client side to the javascript file either setting global variables or through a function parameter as in my example.

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

Benchmark time!

_x000D_
_x000D_
function log(data) {_x000D_
  document.getElementById("log").textContent += data + "\n";_x000D_
}_x000D_
_x000D_
benchmark = (() => {_x000D_
  time_function = function(ms, f, num) {_x000D_
    var z = 0;_x000D_
    var t = new Date().getTime();_x000D_
    for (z = 0;_x000D_
      ((new Date().getTime() - t) < ms); z++)_x000D_
      f(num);_x000D_
    return (z)_x000D_
  }_x000D_
_x000D_
  function clone1(arr) {_x000D_
    return arr.slice(0);_x000D_
  }_x000D_
_x000D_
  function clone2(arr) {_x000D_
    return [...arr]_x000D_
  }_x000D_
_x000D_
  function clone3(arr) {_x000D_
    return [].concat(arr);_x000D_
  }_x000D_
_x000D_
  Array.prototype.clone = function() {_x000D_
    return this.map(e => Array.isArray(e) ? e.clone() : e);_x000D_
  };_x000D_
_x000D_
  function clone4(arr) {_x000D_
    return arr.clone();_x000D_
  }_x000D_
_x000D_
_x000D_
  function benchmark() {_x000D_
    function compare(a, b) {_x000D_
      if (a[1] > b[1]) {_x000D_
        return -1;_x000D_
      }_x000D_
      if (a[1] < b[1]) {_x000D_
        return 1;_x000D_
      }_x000D_
      return 0;_x000D_
    }_x000D_
_x000D_
    funcs = [clone1, clone2, clone3, clone4];_x000D_
    results = [];_x000D_
    funcs.forEach((ff) => {_x000D_
      console.log("Benchmarking: " + ff.name);_x000D_
      var s = time_function(2500, ff, Array(1024));_x000D_
      results.push([ff, s]);_x000D_
      console.log("Score: " + s);_x000D_
_x000D_
    })_x000D_
    return results.sort(compare);_x000D_
  }_x000D_
  return benchmark;_x000D_
})()_x000D_
log("Starting benchmark...\n");_x000D_
res = benchmark();_x000D_
_x000D_
console.log("Winner: " + res[0][0].name + " !!!");_x000D_
count = 1;_x000D_
res.forEach((r) => {_x000D_
  log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");_x000D_
});_x000D_
log("\nWinner code:\n");_x000D_
log(res[0][0].toString());
_x000D_
<textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>
_x000D_
_x000D_
_x000D_

The benchmark will run for 10s since you click the button.

My results:

Chrome (V8 engine):

1. clone1 score: 100% *winner* (4110764)
2. clone3 score: 74.32% speed of winner. (3055225)
3. clone2 score: 30.75% speed of winner. (1264182)
4. clone4 score: 21.96% speed of winner. (902929)

Firefox (SpiderMonkey Engine):

1. clone1 score: 100% *winner* (8448353)
2. clone3 score: 16.44% speed of winner. (1389241)
3. clone4 score: 5.69% speed of winner. (481162)
4. clone2 score: 2.27% speed of winner. (192433)

Winner code:

function clone1(arr) {
    return arr.slice(0);
}

Winner engine:

SpiderMonkey (Mozilla/Firefox)

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

How to establish ssh key pair when "Host key verification failed"

Also sometimes there is situation when you are working on serial console, then checking above command in verbose mode -v will show you /dev/tty does not exists, while it does.

In above case just remove /dev/tty and create a symlink of /dev/ttyS0 to /dev/tty.

$.widget is not a function

I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.

No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.

A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I have just copied UUID toString() method and just updated it to remove "-" from it. It will be much more faster and straight forward than any other solution

public String generateUUIDString(UUID uuid) {
    return (digits(uuid.getMostSignificantBits() >> 32, 8) +
            digits(uuid.getMostSignificantBits() >> 16, 4) +
            digits(uuid.getMostSignificantBits(), 4) +
            digits(uuid.getLeastSignificantBits() >> 48, 4) +
            digits(uuid.getLeastSignificantBits(), 12));
}

/** Returns val represented by the specified number of hex digits. */
private String digits(long val, int digits) {
    long hi = 1L << (digits * 4);
    return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}

Usage:

generateUUIDString(UUID.randomUUID())

Another implementation using reflection

public String generateString(UUID uuid) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    if (uuid == null) {
        return "";
    }

    Method digits = UUID.class.getDeclaredMethod("digits", long.class, int.class);
    digits.setAccessible(true);

    return ( (String) digits.invoke(uuid, uuid.getMostSignificantBits() >> 32, 8) +
            digits.invoke(uuid, uuid.getMostSignificantBits() >> 16, 4) +
            digits.invoke(uuid, uuid.getMostSignificantBits(), 4) +
            digits.invoke(uuid, uuid.getLeastSignificantBits() >> 48, 4) +
            digits.invoke(uuid, uuid.getLeastSignificantBits(), 12));

}

Get the first element of an array

PHP 5.4+:

array_values($array)[0];

Set ANDROID_HOME environment variable in mac

try with this after add ANDROID_HOME on your Environment Variable, work well on my mac

flutter config --android-sdk ANDROID_HOME

How to query first 10 rows and next time query other 10 rows from table

Just use the LIMIT clause.

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10

And from the next call you can do this way:

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10 OFFSET 10

More information on OFFSET and LIMIT on LIMIT and OFFSET.

Using scp to copy a file to Amazon EC2 instance?

First you should change the mode of .pem file from read and write mode to read only mode. This can be done just by a single command in terminal sudo chmod 400 your_public_key.pem

When to use Spring Security`s antMatcher()?

I'm updating my answer...

antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.

Changing three.js background to transparent or other color

In 2020 using r115 it works very good with this:

const renderer = new THREE.WebGLRenderer({ alpha: true }); const scene = new THREE.Scene(); scene.background = null;

How to initialize a nested struct?

Well, any specific reason to not make Proxy its own struct?

Anyway you have 2 options:

The proper way, simply move proxy to its own struct, for example:

type Configuration struct {
    Val string
    Proxy Proxy
}

type Proxy struct {
    Address string
    Port    string
}

func main() {

    c := &Configuration{
        Val: "test",
        Proxy: Proxy{
            Address: "addr",
            Port:    "port",
        },
    }
    fmt.Println(c)
    fmt.Println(c.Proxy.Address)
}

The less proper and ugly way but still works:

c := &Configuration{
    Val: "test",
    Proxy: struct {
        Address string
        Port    string
    }{
        Address: "addr",
        Port:    "80",
    },
}

jQuery.css() - marginLeft vs. margin-left?

jQuery is simply supporting the way CSS is written.

Also, it ensures that no matter how a browser returns a value, it will be understood

jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').

How to close an iframe within iframe itself

function closeWin()   // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframe_callback'));
}


<input class="question" name="Close" type="button" value="Close" onClick="closeWin()" tabindex="10" /> 

Http Post With Body

 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

then add elements for each pair

 nameValuePairs.add(new BasicNameValuePair("yourReqVar", Value);
 nameValuePairs.add( ..... );

Then use the HttpPost:

HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

and use the HttpClient and Response to get the response from the server

Inserting an item in a Tuple

You can cast it to a list, insert the item, then cast it back to a tuple.

a = ('Product', '500.00', '1200.00')
a = list(a)
a.insert(3, 'foobar')
a = tuple(a)
print a

>> ('Product', '500.00', '1200.00', 'foobar')

if, elif, else statement issues in Bash

There is a space missing between elif and [:

elif[ "$seconds" -gt 0 ]

should be

elif [ "$seconds" -gt 0 ]

As I see this question is getting a lot of views, it is important to indicate that the syntax to follow is:

if [ conditions ]
# ^ ^          ^

meaning that spaces are needed around the brackets. Otherwise, it won't work. This is because [ itself is a command.

The reason why you are not seeing something like elif[: command not found (or similar) is that after seeing if and then, the shell is looking for either elif, else, or fi. However it finds another then (after the mis-formatted elif[). Only after having parsed the statement it would be executed (and an error message like elif[: command not found would be output).

What are App Domains in Facebook Apps?

I think it is the domain that you run your app.

For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com

Can we use JSch for SSH key-based communication?

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

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

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

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

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

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

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

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

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

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

            ChannelSftp c = (ChannelSftp) channel;

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

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

IE6/IE7 css border on select element

Using ONLY css is impossbile. In fact, all form elements are impossible to customize to look in the same way on all browsers only with css. You can try niceforms though ;)

Matching a space in regex

In Perl the switch is \s (whitespace).

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Cannot make Project Lombok work on Eclipse

I am using windows 10. I followed below steps :

  • Added lombok dependency in pom.xml of my project
  • Added "-javaagent:{pathOfLombokJarInSystem}" in eclipse.ini file. Path in my case was "-javaagent:C:\Users\ {username} .m2\repository\org\projectlombok\lombok\1.18.6\lombok-1.18.6.jar"
  • Started the eclipse and did Maven > Update Project.

This resolved the issue for me.

"relocation R_X86_64_32S against " linking Error

I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:

/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]

This contrary to the fact that I was already passing -fPIC flags though CFLAGS variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf scripts and need --with-pic switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS. Pass the switch to configure script and the dependencies will be correctly compiled with -fPIC.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.

The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.

If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).

If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

ImportError: No module named PyQt4

After brew install pyqt, you can brew test pyqt which will use the python you have got in your PATH in oder to do the test (show a Qt window).

For non-brewed Python, you'll have to set your PYTHONPATH as brew info pyqt will tell.

Sometimes it is necessary to open a new shell or tap in order to use the freshly brewed binaries.

I frequently check these issues by printing the sys.path from inside of python: python -c "import sys; print(sys.path)" The $(brew --prefix)/lib/pythonX.Y/site-packages have to be in the sys.path in order to be able to import stuff. As said, for brewed python, this is default but for any other python, you will have to set the PYTHONPATH.

Using PHP with Socket.io

If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.

https://github.com/walkor/phpsocket.io

https://github.com/RickySu/phpsocket.io

Exmaple codes for the first repository like this.

use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
  $socket->on('chat message', function($msg)use($io){
    $io->emit('chat message', $msg);
  });
});

How to use radio on change event?

You can use this which refers to the current input element.

$('input[type=radio][name=bedStatus]').change(function() {
    if (this.value == 'allot') {
        alert("Allot Thai Gayo Bhai");
    }
    else if (this.value == 'transfer') {
        alert("Transfer Thai Gayo");
    }
});

http://jsfiddle.net/4gZAT/

Note that you are comparing the value against allot in both if statements and :radio selector is deprecated.

In case that you are not using jQuery, you can use the document.querySelectorAll and HTMLElement.addEventListener methods:

var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');

function changeHandler(event) {
   if ( this.value === 'allot' ) {
     console.log('value', 'allot');
   } else if ( this.value === 'transfer' ) {
      console.log('value', 'transfer');
   }  
}

Array.prototype.forEach.call(radios, function(radio) {
   radio.addEventListener('change', changeHandler);
});

What is cURL in PHP?

Php curl function (POST,GET,DELETE,PUT)

function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = true){
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    if($method == 'POST'){
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    if($json == true){
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json','Authorization: Bearer '.$token,'Content-Length: ' . strlen($post)));
    }else{
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSLVERSION, 6);
    if($ssl == false){
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    }
    // curl_setopt($ch, CURLOPT_HEADER, 0);     
    $r = curl_exec($ch);    
    if (curl_error($ch)) {
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        print_r('Error: ' . $err . ' Status: ' . $statusCode);
        // Add error
        $this->error = $err;
    }
    curl_close($ch);
    return $r;
}

Calculating and printing the nth prime number

You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n) that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.