Programs & Examples On #Annotations

In programming, annotations are used to add information to a code element which cannot be expressed by the type system.

@Value annotation type casting to Integer from String

Since using the @Value("new Long("myconfig")") with cast could throw error on startup if the config is not found or if not in the same expected number format

We used the following approach and is working as expected with fail safe check.

@Configuration()
public class MyConfiguration {

   Long DEFAULT_MAX_IDLE_TIMEOUT = 5l;

   @Value("db.timeoutInString")
   private String timeout;

   public Long getTimout() {
        final Long timoutVal = StringUtil.parseLong(timeout);
        if (null == timoutVal) {
            return DEFAULT_MAX_IDLE_TIMEOUT;
        }
        return timoutVal;
    }
}
   

How to use @Nullable and @Nonnull annotations more effectively?

What I do in my projects is to activate the following option in the "Constant conditions & exceptions" code inspection:
Suggest @Nullable annotation for methods that may possibly return null and report nullable values passed to non-annotated parameters Inspections

When activated, all non-annotated parameters will be treated as non-null and thus you will also see a warning on your indirect call:

clazz.indirectPathToA(null); 

For even stronger checks the Checker Framework may be a good choice (see this nice tutorial.
Note: I have not used that yet and there may be problems with the Jack compiler: see this bugreport

annotation to make a private method public only for test classes

You can't do this, since then how could you even compile your tests? The compiler won't take the annotation into account.

There are two general approaches to this

The first is to use reflection to access the methods anyway

The second is to use package-private instead of private, then have your tests in the same package (but in a different module). They will essentially be private to other code, but your tests will still be able to access them.

Of course, if you do black-box testing, you shouldn't be accessing the private members anyway.

How and where are Annotations used in Java?

Annotations in Java, provide a mean to describe classes, fields and methods. Essentially, they are a form of metadata added to a Java source file, they can't affect the semantics of a program directly. However, annotations can be read at run-time using Reflection & this process is known as Introspection. Then it could be used to modify classes, fields or methods.

This feature, is often exploited by Libraries & SDKs (hibernate, JUnit, Spring Framework) to simplify or reduce the amount of code that a programmer would unless do in orer to work with these Libraries or SDKs.Therefore, it's fair to say Annotations and Reflection work hand-in hand in Java.

We also get to limit the availability of an annotation to either compile-time or runtime.Below is a simple example on creating a custom annotation

Driver.java

package io.hamzeen;

import java.lang.annotation.Annotation;

public class Driver {

    public static void main(String[] args) {
        Class<TestAlpha> obj = TestAlpha.class;
        if (obj.isAnnotationPresent(IssueInfo.class)) {

            Annotation annotation = obj.getAnnotation(IssueInfo.class);
            IssueInfo testerInfo = (IssueInfo) annotation;

            System.out.printf("%nType: %s", testerInfo.type());
            System.out.printf("%nReporter: %s", testerInfo.reporter());
            System.out.printf("%nCreated On: %s%n%n",
                    testerInfo.created());
        }
    }
}

TestAlpha.java

package io.hamzeen;

import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;

@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {

}

IssueInfo.java

package io.hamzeen;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Hamzeen. H.
 * @created 10/01/2015
 * 
 * IssueInfo annotation definition
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {

    public enum Type {
        BUG, IMPROVEMENT, FEATURE
    }

    Type type() default Type.BUG;

    String reporter() default "Vimesh";

    String created() default "10/01/2015";
}

Difference between <context:annotation-config> and <context:component-scan>

I found this nice summary of which annotations are picked up by which declarations. By studying it you will find that <context:component-scan/> recognizes a superset of annotations recognized by <context:annotation-config/>, namely:

  • @Component, @Service, @Repository, @Controller, @Endpoint
  • @Configuration, @Bean, @Lazy, @Scope, @Order, @Primary, @Profile, @DependsOn, @Import, @ImportResource

As you can see <context:component-scan/> logically extends <context:annotation-config/> with CLASSPATH component scanning and Java @Configuration features.

intellij incorrectly saying no beans of type found for autowired repository

Use @EnableAutoConfiguration annotation with @Component at class level. It will resolve this problem.

For example:

@Component
@EnableAutoConfiguration  
public class ItemDataInitializer  {

    @Autowired
    private ItemReactiveRepository itemReactiveRepository;

    @Autowired
    private MongoOperations mongoOperations;
}

@Autowired - No qualifying bean of type found for dependency

I was facing the same issue while auto-wiring the class from one of my jar file. I fixed the issue by using @Lazy annotation:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

    @Autowired
    @Lazy
    private IGalaxyCommand iGalaxyCommand;

How to inject a Map using the @Value Spring Annotation?

To get this working with YAML, do this:

property-name: '{
  key1: "value1",
  key2: "value2"
}'

Multi-Column Join in Hibernate/JPA Annotations

This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key

i.e., one to one mapping based on 3 different columns

@Entity
@Table(name = "foo")
public class foo implements Serializable
{
    @Column(name="foocol1")
    private String foocol1;
    //add getter setter
    @Column(name="foocol2")
    private String foocol2;
    //add getter setter
    @Column(name="foocol3")
    private String foocol3;
    //add getter setter
    private Boo boo;
    private int id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "brsitem_id", updatable = false)
    public int getId()
    {
        return this.id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @OneToOne
    @JoinColumns(
    {
        @JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
        @JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
        @JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
    }
    )
    public Boo getBoo()
    {
        return boo;
    }
    public void setBoo(Boo boo)
    {
        this.boo = boo;
    }
}





@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
    private int id;
    @Column(name="boocol1")
    private String boocol1;
    //add getter setter
    @Column(name="boocol2")
    private String boocol2;
    //add getter setter
    @Column(name="boocol3")
    private String boocol3;
    //add getter setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id", updatable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
}

Which @NotNull Java annotation should I use?

Android

This answer is Android specific. Android has support package called support-annotations. This provides dozens of Android specific annotations and also provides common ones like NonNull, Nullable etc.

To add support-annotations package, add the following dependency in your build.gradle:

compile 'com.android.support:support-annotations:23.1.1'

and then use:

import android.support.annotation.NonNull;

void foobar(@NonNull Foo bar) {}

Annotations from javax.validation.constraints not working

After the Version 2.3.0 the "spring-boot-strarter-test" (that included the NotNull/NotBlank/etc) is now "sprnig boot-strarter-validation"

Just change it from ....-test to ...-validation and it should work.

If not downgrading the version that you are using to 2.1.3 also will solve it.

Is it possible to read the value of a annotation in java?

While all the answers given so far are perfectly valid, one should also keep in mind the google reflections library for a more generic and easy approach to annotation scanning, e.g.

 Reflections reflections = new Reflections("my.project.prefix");

 Set<Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

import org.junit.Assert
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test

class FeatureTest {
    companion object {
        private lateinit var heavyFeature: HeavyFeature
        @BeforeClass
        @JvmStatic
        fun beforeHeavy() {
            heavyFeature = HeavyFeature()
        }
    }

    private lateinit var feature: Feature

    @Before
    fun before() {
        feature = Feature()
    }

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}

Same as

import org.junit.Assert
import org.junit.Test

 class FeatureTest {
    companion object {
        private val heavyFeature = HeavyFeature()
    }

    private val feature = Feature()

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}

@RequestBody and @ResponseBody annotations in Spring

There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody javadocs, @ResponseBody javadocs

Usage examples would be something like this:

Using a JavaScript-library like JQuery, you would post a JSON-Object like this:

{ "firstName" : "Elmer", "lastName" : "Fudd" }

Your controller method would look like this:

// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
    return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}

// domain / value objects
public class UserStats{
    private String firstName;
    private String lastName;
    // + getters, setters
}
public class Description{
    private String description;
    // + getters, setters, constructor
}

Now if you have Jackson on your classpath (and have an <mvc:annotation-driven> setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation). So the Browser / Client would see this JSON result:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852

Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.


Update

Ever since Spring 4.x, you usually won't use @ResponseBody on method level, but rather @RestController on class level, with the same effect.

Here is a quote from the official Spring MVC documentation:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody to indicate a controller whose every method inherits the type-level @ResponseBody annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.

What does -> mean in Python function definitions?

These are function annotations covered in PEP 3107. Specifically, the -> marks the return function annotation.

Examples:

>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': 
...    return 1/2*m*v**2
... 
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

Annotations are dictionaries, so you can do this:

>>> '{:,} {}'.format(kinetic_energy(20,3000),
      kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'

You can also have a python data structure rather than just a string:

>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'}
>>> def f()->rd:
...    pass
>>> f.__annotations__['return']['type']
<class 'float'>
>>> f.__annotations__['return']['units']
'Joules'
>>> f.__annotations__['return']['docstring']
'Given mass and velocity returns kinetic energy in Joules'

Or, you can use function attributes to validate called values:

def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        try: 
            pr=test.__name__+': '+test.__docstring__
        except AttributeError:
            pr=test.__name__   
        msg = '{}=={}; Test: {}'.format(var, value, pr)
        assert test(value), msg

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    _between.__docstring__='must be between {} and {}'.format(lo,hi)       
    return _between

def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
    validate(f, locals())
    print(x,y)

Prints

>>> f(2,2) 
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>

Implement a simple factory pattern with Spring 3 annotations

The following worked for me:

The interface consist of you logic methods plus additional identity method:

public interface MyService {
    String getType();
    void checkStatus();
}

Some implementations:

@Component
public class MyServiceOne implements MyService {
    @Override
    public String getType() {
        return "one";
    }

    @Override
    public void checkStatus() {
      // Your code
    }
}

@Component
public class MyServiceTwo implements MyService {
    @Override
    public String getType() {
        return "two";
    }

    @Override
    public void checkStatus() {
      // Your code
    }
}

@Component
public class MyServiceThree implements MyService {
    @Override
    public String getType() {
        return "three";
    }

    @Override
    public void checkStatus() {
      // Your code
    }
}

And the factory itself as following:

@Service
public class MyServiceFactory {

    @Autowired
    private List<MyService> services;

    private static final Map<String, MyService> myServiceCache = new HashMap<>();

    @PostConstruct
    public void initMyServiceCache() {
        for(MyService service : services) {
            myServiceCache.put(service.getType(), service);
        }
    }

    public static MyService getService(String type) {
        MyService service = myServiceCache.get(type);
        if(service == null) throw new RuntimeException("Unknown service type: " + type);
        return service;
    }
}

I've found such implementation easier, cleaner and much more extensible. Adding new MyService is as easy as creating another spring bean implementing same interface without making any changes in other places.

@Resource vs @Autowired

When you analyze critically from the base classes of these two annotations.You will realize the following differences.

@Autowired uses AutowiredAnnotationBeanPostProcessor to inject dependencies.
@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies.

Even though they use different post processor classes they all behave nearly identically. The differences critically lie in their execution paths, which I have highlighted below.

@Autowired / @Inject

1.Matches by Type
2.Restricts by Qualifiers
3.Matches by Name

@Resource

1.Matches by Name
2.Matches by Type
3.Restricts by Qualifiers (ignored if match is found by name)

Setting a JPA timestamp column to be generated by the database?

I'm posting this for people searching for an answer when using MySQL and Java Spring Boot JPA, like @immanuelRocha says, only have too @CreationTimeStamp to the @Column in Spring, and in MySQL set the default value to "CURRENT_TIMESTAMP".

In Spring add just the line :

_x000D_
_x000D_
@Column(name = "insert_date")_x000D_
@CreationTimestamp_x000D_
private Timestamp insert_date;
_x000D_
_x000D_
_x000D_

difference between @size(max = value ) and @min(value) @max(value)

package com.mycompany;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 2, max = 14)
    private String licensePlate;

    @Min(2)
    private int seatCount;

    public Car(String manufacturer, String licencePlate, int seatCount) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }

    //getters and setters ...
}

@NotNull, @Size and @Min are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:

manufacturer shall never be null

licensePlate shall never be null and must be between 2 and 14 characters long

seatCount shall be at least 2.

What's the difference between interface and @interface in java?

The @ symbol denotes an annotation type definition.

That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.

See this javadocs entry on the subject.

How to get annotations of a member variable?

for(Field field : cls.getDeclaredFields()){
  Class type = field.getType();
  String name = field.getName();
  Annotation[] annotations = field.getDeclaredAnnotations();
}

See also: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html

How do I assert my exception message with JUnit Test annotation?

Import the catch-exception library, and use that. It's much cleaner than the ExpectedException rule or a try-catch.

Example form their docs:

import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;

// given: an empty list
List myList = new ArrayList();

// when: we try to get the first element of the list
catchException(myList).get(1);

// then: we expect an IndexOutOfBoundsException with message "Index: 1, Size: 0"
assertThat(caughtException(),
  allOf(
    instanceOf(IndexOutOfBoundsException.class),
    hasMessage("Index: 1, Size: 0"),
    hasNoCause()
  )
);

@Nullable annotation usage

Granted, there are definitely different thinking, in my world, I cannot enforce "Never pass a null" because I am dealing with uncontrollable third parties like API callers, database records, former programmers etc... so I am paranoid and defensive in approaches. Since you are on Java8 or later there is a bit cleaner approach than an if block.

public String foo(@Nullable String mayBeNothing) {
   return Optional.ofNullable(mayBeNothing).orElse("Really Nothing");
}

You can also throw some exception in there by swapping .orElse to orElseThrow(() -> new Exception("Dont' send a null")).

If you don't want to use @Nullable, which adds nothing functionally, why not just name the parameter with mayBe... so your intention is clear.

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

org.hibernate.MappingException: Unknown entity

I encountered the same problem when I switched to AnnotationSessionFactoryBean. I was using entity.hbm.xml before.

I found that My class was missing following annotation which resolved the issue in my case:

@Entity
@Table(name = "MyTestEntity")
@XmlRootElement

@Transactional(propagation=Propagation.REQUIRED)

In Spring applications, if you enable annotation based transaction support using <tx:annotation-driven/> and annotate any class/method with @Transactional(propagation=Propagation.REQUIRED) then Spring framework will start a transaction and executes the method and commits the transaction. If any RuntimeException occurred then the transaction will be rolled back.

Actually propagation=Propagation.REQUIRED is default propagation level, you don't need to explicitly mentioned it.

For further info : http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations

Why does Eclipse complain about @Override on interface methods?

Even after changing the compiler compliance setting to 1.6 or 1.7 from windows tab, then prefernces, then java, then compiler and setting the compiler compliance, I was still having this issue. The idea is that we need to go the the project folder, right click, Java and set compiler compliance to 1.6 or higer. This worked for me.

Do I need <class> elements in persistence.xml?

Hibernate doesn't support <exclude-unlisted-classes>false</exclude-unlisted-classes> under SE, (another poster mentioned this works with TopLink and EclipseLink).

There are tools that will auto-generate the list of classes to persistence.xml e.g. the Import Database Schema wizard in IntelliJ. Once you've got your project's initial classes in persistence.xml it should be simple to add/remove single classes by hand as your project progresses.

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

How to scan multiple paths using the @ComponentScan annotation?

You can also use @ComponentScans annotation:

@ComponentScans(value = { @ComponentScan("com.my.package.first"),
                          @ComponentScan("com.my.package.second") })

Name attribute in @Entity and @Table

@Table's name attribute is the actual table name. @Entitiy's name is useful if you have two @Entity classes with the same name and you need a way to differentiate them when running queries.

Only using @JsonIgnore during serialization, but not deserialization

You can use @JsonIgnoreProperties at class level and put variables you want to igonre in json in "value" parameter.Worked for me fine.

@JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
      private int myVariable1;,
      private int myVariable2;
}

Why does JPA have a @Transient annotation?

Purpose is different:

The transient keyword and @Transient annotation have two different purposes: one deals with serialization and one deals with persistence. As programmers, we often marry these two concepts into one, but this is not accurate in general. Persistence refers to the characteristic of state that outlives the process that created it. Serialization in Java refers to the process of encoding/decoding an object's state as a byte stream.

The transient keyword is a stronger condition than @Transient:

If a field uses the transient keyword, that field will not be serialized when the object is converted to a byte stream. Furthermore, since JPA treats fields marked with the transient keyword as having the @Transient annotation, the field will not be persisted by JPA either.

On the other hand, fields annotated @Transient alone will be converted to a byte stream when the object is serialized, but it will not be persisted by JPA. Therefore, the transient keyword is a stronger condition than the @Transient annotation.

Example

This begs the question: Why would anyone want to serialize a field that is not persisted to the application's database? The reality is that serialization is used for more than just persistence. In an Enterprise Java application there needs to be a mechanism to exchange objects between distributed components; serialization provides a common communication protocol to handle this. Thus, a field may hold critical information for the purpose of inter-component communication; but that same field may have no value from a persistence perspective.

For example, suppose an optimization algorithm is run on a server, and suppose this algorithm takes several hours to complete. To a client, having the most up-to-date set of solutions is important. So, a client can subscribe to the server and receive periodic updates during the algorithm's execution phase. These updates are provided using the ProgressReport object:

@Entity
public class ProgressReport implements Serializable{

    private static final long serialVersionUID = 1L;

    @Transient
    long estimatedMinutesRemaining;
    String statusMessage;
    Solution currentBestSolution;

}

The Solution class might look like this:

@Entity
public class Solution implements Serializable{

    private static final long serialVersionUID = 1L;

    double[][] dataArray;
    Properties properties;
}

The server persists each ProgressReport to its database. The server does not care to persist estimatedMinutesRemaining, but the client certainly cares about this information. Therefore, the estimatedMinutesRemaining is annotated using @Transient. When the final Solution is located by the algorithm, it is persisted by JPA directly without using a ProgressReport.

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.

Should we @Override an interface's method implementation?

For me, often times this is the only reason some code requires Java 6 to compile. Not sure if it's worth it.

Spring @ContextConfiguration how to put the right location for the xml

That's the reason not to put configuration into webapp.

As far as I know, there are no good ways to access files in webapp folder from the unit tests. You can put your configuration into src/main/resources instead, so that you can access it from your unit tests (as described in the docs), as well as from the webapp (using classpath: prefix in contextConfigLocation).

See also:

Neither BindingResult nor plain target object for bean name available as request attribute

the first time when you are returning your form make sure you pass the model attribute the form requires which can be done by adding the below code

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Login login)
    return "test";
}

By default the model attribute name is taken as Bean class's name with first lowercase letter

By doing this the form which expects a backing object naming "login" will be made available to it

after the form is submitted you can do the validation by passing your bean object and bindingresult as the method parameters as shown below

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(    @ModelAttribute("login") Login login,
                        BindingResult result) 

Where does the @Transactional annotation belong?

enter image description here

The @Transactional should be used on service layer as it contains the business logic. The DAO layer usually has only database CRUD operations.

// the service class that we want to make transactional
@Transactional
public class DefaultFooService implements FooService {

    Foo getFoo(String fooName);

    Foo getFoo(String fooName, String barName);

    void insertFoo(Foo foo);

    void updateFoo(Foo foo);
}

Spring doc : https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html

How to annotate MYSQL autoincrement field with JPA annotations

can you check whether you connected to the correct database. as i was faced same issue, but finally i found that i connected to different database.

identity supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

More Info : http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/mapping.html#mapping-declaration-id

Hibernate Annotations - Which is better, field or property access?

We created entity beans and used getter annotations. The problem we ran into is this: some entities have complex rules for some properties regarding when they can be updated. The solution was to have some business logic in each setter that determines whether or not the actual value changed and, if so, whether the change should be allowed. Of course, Hibernate can always set the properties, so we ended up with two groups of setters. Pretty ugly.

Reading previous posts, I also see that referencing the properties from inside the entity could lead to issues with collections not loading.

Bottom line, I would lean toward annotating the fields in the future.

Init method in Spring Controller (annotation version)

Alternatively you can have your class implement the InitializingBean interface to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed.

When do you use Java's @Override annotation and why?

Override annotation is used to take advantage of the compiler, for checking whether you actually are overriding a method from parent class. It is used to notify if you make any mistake like mistake of misspelling a method name, mistake of not correctly matching the parameters

Scanning Java annotations at runtime

Google Reflection if you want to discover interfaces as well.

Spring ClassPathScanningCandidateComponentProvider is not discovering interfaces.

Injecting Mockito mocks into a Spring bean

The best way is:

<bean id="dao" class="org.mockito.Mockito" factory-method="mock"> 
    <constructor-arg value="com.package.Dao" /> 
</bean> 

Update
In the context file this mock must be listed before any autowired field depending on it is declared.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

This happens for these reasons:

  1. your inner class should be defined as static

    private static class Condition {  //jackson specific    
    }
    
  2. It might be that you got no default constructor in your class (UPDATE: This seems not to be the case)

    private static class Condition {
        private Long id;
    
        public Condition() {
        }
    
        // Setters and Getters
    }
    
  3. It could be your Setters are not defined properly or are not visible (e.g. private setter)

Does Spring @Transactional attribute work on a private method?

By default the @Transactional attribute works only when calling an annotated method on a reference obtained from applicationContext.

public class Bean {
  public void doStuff() {
    doTransactionStuff();
  }
  @Transactional
  public void doTransactionStuff() {

  }
}

This will open a transaction:

Bean bean = (Bean)appContext.getBean("bean");
bean.doTransactionStuff();

This will not:

Bean bean = (Bean)appContext.getBean("bean");
bean.doStuff();

Spring Reference: Using @Transactional

Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

Consider the use of AspectJ mode (see below) if you expect self-invocations to be wrapped with transactions as well. In this case, there won't be a proxy in the first place; instead, the target class will be 'weaved' (i.e. its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

Can't find @Nullable inside javax.annotation.*

If anyone has this issue when building a Maven project created in IntelliJ IDEA externally, I used the following dependency instead of the answer:

<dependency>
  <groupId>org.jetbrains</groupId>
  <artifactId>annotations</artifactId>
  <version>15.0</version>
</dependency>

Using this will allow the project to build on IntelliJ IDEA and by itself using Maven.

You can find it here.

Spring: @Component versus @Bean

When you use the @Component tag, it's the same as having a POJO (Plain Old Java Object) with a vanilla bean declaration method (annotated with @Bean). For example, the following method 1 and 2 will give the same result.

Method 1

@Component
public class SomeClass {

    private int number;

    public SomeClass(Integer theNumber){
        this.number = theNumber.intValue();
    }

    public int getNumber(){
        return this.number;
    }
}

with a bean for 'theNumber':

@Bean
Integer theNumber(){
    return new Integer(3456);
}

Method 2

//Note: no @Component tag
public class SomeClass {

    private int number;

    public SomeClass(Integer theNumber){
        this.number = theNumber.intValue();
    }

    public int getNumber(){
        return this.number;
    }
}

with the beans for both:

@Bean
Integer theNumber(){
    return new Integer(3456);
}

@Bean
SomeClass someClass(Integer theNumber){
    return new SomeClass(theNumber);
}

Method 2 allows you to keep bean declarations together, it's a bit more flexible etc. You may even want to add another non-vanilla SomeClass bean like the following:

@Bean
SomeClass strawberryClass(){
    return new SomeClass(new Integer(1));
}

What's the difference between @Component, @Repository & @Service annotations in Spring?

@Component: you annotate a class @Component, it tells hibernate that it is a Bean.

@Repository: you annotate a class @Repository, it tells hibernate it is a DAO class and treat it as DAO class. Means it makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

@Service: This tells hibernate it is a Service class where you will have @Transactional etc Service layer annotations so hibernate treats it as a Service component.

Plus @Service is advance of @Component. Assume the bean class name is CustomerService, since you did not choose XML bean configuration way so you annotated the bean with @Component to indicate it as a Bean. So while getting the bean object CustomerService cust = (CustomerService)context.getBean("customerService"); By default, Spring will lower case the first character of the component – from ‘CustomerService’ to ‘customerService’. And you can retrieve this component with name ‘customerService’. But if you use @Service annotation for the bean class you can provide a specific bean name by

@Service("AAA")
public class CustomerService{

and you can get the bean object by

CustomerService cust = (CustomerService)context.getBean("AAA");

How to supply value to an annotation from a Constant java

You can use a constant (i.e. a static, final variable) as the parameter for an annotation. As a quick example, I use something like this fairly often:

import org.junit.Test;
import static org.junit.Assert.*;

public class MyTestClass
{
    private static final int TEST_TIMEOUT = 60000; // one minute per test

    @Test(timeout=TEST_TIMEOUT)
    public void testJDK()
    {
        assertTrue("Something is very wrong", Boolean.TRUE);
    }
}

Note that it's possible to pass the TEST_TIMEOUT constant straight into the annotation.

Offhand, I don't recall ever having tried this with an array, so you may be running into some issues with slight differences in how arrays are represented as annotation parameters compared to Java variables? But as for the other part of your question, you could definitely use a constant String without any problems.

EDIT: I've just tried this with a String array, and didn't run into the problem you mentioned - however the compiler did tell me that the "attribute value must be constant" despite the array being defined as public static final String[]. Perhaps it doesn't like the fact that arrays are mutable? Hmm...

org.hibernate.MappingException: Could not determine type for: java.util.Set

I got the same problem with @ManyToOne column. It was solved... in stupid way. I had all other annotations for public getter methods, because they were overridden from parent class. But last field was annotated for private variable like in all other classes in my project. So I got the same MappingException without the reason.

Solution: I placed all annotations at public getter methods. I suppose, Hibernate can't handle cases, when annotations for private fields and public getters are mixed in one class.

Setting default values for columns in JPA

This isn't possible in JPA.

Here's what you can do with the Column annotation: http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html

Assigning default values to shell variables with a single command in bash

To answer your question and on all variable substitutions

echo "$\{var}"
echo "Substitute the value of var."


echo "$\{var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."


echo "$\{var:=word}"
echo "If var is null or unset, var is set to the value of word."


echo "$\{var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."


echo "$\{var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

Adding a newline character within a cell (CSV)

I was concatenating the variable and adding multiple items in same row. so below code work for me. "\n" new line code is mandatory to add first and last of each line if you will add it on last only it will append last 1-2 character to new lines.

  $itemCode =  '';
foreach($returnData['repairdetail'] as $checkkey=>$repairDetailData){

    if($checkkey >0){
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";
    }else{
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";             
    }
    $repairDetaile[]= array(
        $itemCode,
    )
}
// pass all array to here 
foreach ($repairDetaile as $csvData) { 
    fputcsv($csv_file,$csvData,',','"');
}
fclose($csv_file);  

How can a web application send push notifications to iOS devices?

To be more specific, in order for a web application to send push notifications to a mobile device, such as the iPhone, the mobile device must have registered to receive push notifications for a particular application. The registration for push notification is done through a native app and can only be performed through a native app. Once the native app is registered for push notification, it can send the authorization token to the server, which can be used in conjunction with the certificate used to provision the native client, to send the push notifications to the mobile device.

As specified in another answer, one option is to 'wrap' your web application in a native application. Meaning that you would create a native application that basically presents a UIWebView (for iPhone dev) to the user showing your web application. While this pretty much functions in the same manner as the native browser, you would be able to add the ability to register for push notifications using the native controls.

It would be beneficial to you to review the Apple's push notification document as it provides some pretty good information on how push messaging functions on the iPhone.

See these links provided by Peter Hosey:

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

How to download a Nuget package without nuget.exe or Visual Studio extension?

To obtain the current stable version of the NuGet package use:

https://www.nuget.org/api/v2/package/{packageID}

What is callback in Android?

It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

T-SQL Subquery Max(Date) and Joins

Here's another way to do it without subqueries. This method will often outperform others, so it's worth testing both methods to see which gives the best performance.

SELECT
     PRT.PartID,
     PRT.PartNumber,
     PRT.Description,
     PRC1.Price,
     PRC1.PriceDate
FROM
     MyParts PRT
LEFT OUTER JOIN MyPrices PRC1 ON
     PRC1.PartID = PRT.PartID
LEFT OUTER JOIN MyPrices PRC2 ON
     PRC2.PartID = PRC1.PartID AND
     PRC2.PriceDate > PRC1.PriceDate
WHERE
     PRC2.PartID IS NULL

This will give multiple results if you have two prices with the same EXACT PriceDate (Most other solutions will do the same). Also, I there is nothing to account for the last price date being in the future. You may want to consider a check for that regardless of which method you end up using.

How to remove a character at the end of each line in unix

This Perl code removes commas at the end of the line:

perl -pe 's/,$//' file > file.nocomma

This variation still works if there is whitespace after the comma:

perl -lpe 's/,\s*$//' file > file.nocomma

This variation edits the file in-place:

perl -i -lpe 's/,\s*$//' file

This variation edits the file in-place, and makes a backup file.bak:

perl -i.bak -lpe 's/,\s*$//' file

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

mysql $link generally means, the resource object of the established mysqli connection to query the database.

So there are two ways of solving this problem

mysqli_query();

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql"); 
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));

Or, Using mysql_query() (This is now obselete)

$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());

As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

If you by any chance using java for configuration, you may need to check the below bean declaration if you have package level changes. Eg: com.abc.spring package changed to com.bbc.spring

@Bean
    public SessionFactory sessionFactory() {

        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
        //builder.scanPackages("com.abc.spring");    //Comment this line as this package no longer valid.
        builder.scanPackages("com.bbc.spring");
        builder.addProperties(getHibernationProperties());

        return builder.buildSessionFactory();
    }

Change One Cell's Data in mysql

My answer is repeating what others have said before, but I thought I'd add an example, using MySQL, only because the previous answers were a little bit cryptic to me.

The general form of the command you need to use to update a single row's column:

UPDATE my_table SET my_column='new value' WHERE something='some value';

And here's an example.

BEFORE

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10104 | 
+------------+-------+
2 rows in set (0.00 sec)

MAKING THE CHANGE

mysql> update ae set port='10105' where aet='CDRECORD';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

AFTER

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10105 | 
+------------+-------+
2 rows in set (0.00 sec)

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Python: Find a substring in a string and returning the index of the substring

There's a builtin method find on string objects.

s = "Happy Birthday"
s2 = "py"

print(s.find(s2))

Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)

find returns -1 if the string cannot be found.

Unix command to find lines common in two files

Maybe you mean comm ?

Compare sorted files FILE1 and FILE2 line by line.

With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files.

The secret in finding these information are the info pages. For GNU programs, they are much more detailed than their man-pages. Try info coreutils and it will list you all the small useful utils.

Check if item is in an array / list

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

In Python, how do I use urllib to see if a website is 404 or 200?

import urllib2

try:
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
    data = fileHandle.read()
    fileHandle.close()
except urllib2.URLError, e:
    print 'you got an error with the code', e

Is there a way to make numbers in an ordered list bold?

Answer https://stackoverflow.com/a/21369918/2526049 from dcodesmith has a side effect that turns all types of lists numeric. <ol type="a"> will show 1. 2. 3. 4. rather than a. b. c. d.

ol {
  margin: 0 0 1.5em;
  padding: 0;
  counter-reset: item;
}

ol > li {
  margin: 0;
  padding: 0 0 0 2em;
  text-indent: -2em;
  list-style-type: none;
  counter-increment: item;
}

ol > li:before {
  display: inline-block;
  width: 1em;
  padding-right: 0.5em;
  font-weight: bold;
  text-align: right;
  content: counter(item) ".";
}

/* Add support for non-numeric lists */

ol[type="a"] > li:before {
  content: counter(item, lower-alpha) ".";
}
ol[type="i"] > li:before {
  content: counter(item, lower-roman) ".";
}

The above code adds support for lowercase letters, lowercase roman numerals. At the time of writing browsers do not differentiate between upper and lower case selectors for type so you can only pick uppercase or lowercase for your alternate ol types I guess.

linq where list contains any in list

Sounds like you want:

var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());

How to convert a ruby hash object to JSON?

You can also use JSON.generate:

require 'json'

JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse:

require 'json'

JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

Turning Sonar off for certain code

Use //NOSONAR on the line you get warning if it is something you cannot help your code with. It works!

How to send email to multiple address using System.Net.Mail

I think you can use this code in order to have List of outgoing Addresses having a display Name (also different):

//1.The ACCOUNT
MailAddress fromAddress = new MailAddress("[email protected]", "my display name");
String fromPassword = "password";

//2.The Destination email Addresses
MailAddressCollection TO_addressList = new MailAddressCollection();

//3.Prepare the Destination email Addresses list
foreach (var curr_address in mailto.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    MailAddress mytoAddress = new MailAddress(curr_address, "Custom display name");
    TO_addressList.Add(mytoAddress);
}

//4.The Email Body Message
String body = bodymsg;

//5.Prepare GMAIL SMTP: with SSL on port 587
var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 30000
};


//6.Complete the message and SEND the email:
using (var message = new MailMessage()
        {
            From = fromAddress,
            Subject = subject,
            Body = body,
        })
{
    message.To.Add(TO_addressList.ToString());
    smtp.Send(message);
}

Finding child element of parent pure javascript

If you already have var parent = document.querySelector('.parent'); you can do this to scope the search to parent's children:

parent.querySelector('.child')

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

If you have previously installed node using brew, then you will have a bunch of extra files that you should clean up before installing node "the right way". Plus, I had to add a few settings to my startup script to make things work smoothly.

I wrote a script to make this easy.

# filename:  install-nvm-npm-node
# author:    Lex Sheehan
# purpose:   To cleanly install NVM, NODE and NPM
# dependencies:  brew

NOW=$(date +%x\ %H:%M:%S)
CR=$'\n'
REV=$(tput rev)
OFF=$(tput sgr0)
BACKUP_DIR=$HOME/backups/nvm-npm-bower-caches/$NOW
MY_NAME=$(basename $0)
NODE_VER_TO_INSTALL=$1
if [ "$NODE_VER_TO_INSTALL" == "" ]; then
    NODE_VER_TO_INSTALL=v0.12.2
fi
if [ "`echo "$NODE_VER_TO_INSTALL" | cut -c1-1`" != "v" ]; then
    echo """$CR""Usage:   $ $MY_NAME <NODE_VERSION_TO_INSALL>"
    echo "Example: $ $MY_NAME v0.12.1"
    echo "Example: $ $MY_NAME $CR"
    exit 1
fi
echo """$CR""First, run:  $ brew update"
echo "Likely, you'll need to do what it suggests."
echo "Likely, you'll need to run: $ brew update$CR"
echo "To install latest node version, run the following command to get the latest version:  $ nvm ls-remote"
echo "... and pass the version number you want as the only param to $MY_NAME. $CR"
echo "Are you ready to install the latest version of nvm and npm and node version $NODE_VER_TO_INSTALL ?$CR"
echo "Press CTL+C to exit --or-- Enter to continue..."
read x

echo """$REV""Uninstalling nvm...$CR$OFF"
# Making backups, but in all likelyhood you'll just reinstall them (and won't need these backups)
if [ ! -d "$BACKUP_DIR" ]; then 
    echo "Creating directory to store $HOME/.nvm .npm and .bower cache backups: $BACKUP_DIR"
    mkdir -p $BACKUP_DIR
fi 
set -x
mv $HOME/.nvm   $BACKUP_DIR  2>/dev/null
mv $HOME/.npm   $BACKUP_DIR  2>/dev/null
mv $HOME/.bower $BACKUP_DIR  2>/dev/null
{ set +x; } &>/dev/null

echo "$REV""$CR""Uninstalling node...$CR$OFF"
echo "Enter your password to remove user some node-related /usr/local directories"
set -x
sudo rm -rf /usr/local/lib/node_modules
rm -rf /usr/local/lib/node
rm -rf /usr/local/include/node
rm -rf /usr/local/include/node_modules
rm /usr/local/bin/npm
rm /usr/local/lib/dtrace/node.d
rm -rf $HOME/.node
rm -rf $HOME/.node-gyp
rm /opt/local/bin/node
rm /opt/local/include/node
rm -rf /opt/local/lib/node_modules
rm -rf /usr/local/Cellar/nvm
brew uninstall node 2>/dev/null
{ set +x; } &>/dev/null

echo "$REV""$CR""Installing nvm...$CR$OFF"

echo "++brew install nvm"
brew install nvm 
echo '$(brew --prefix nvm)/nvm.sh'
source $(brew --prefix nvm)/nvm.sh

echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc):$CR$OFF"
echo "export NVM_DIR=\"\$(brew --prefix nvm)\"; [ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"$CR"
NVM_DIR="$(brew --prefix nvm)"

echo """$CR""Using nvm install node...$CR"
echo "++ nvm install $NODE_VER_TO_INSTALL"
nvm install $NODE_VER_TO_INSTALL
NODE_BINARY_PATH="`find /usr/local/Cellar/nvm -name node -type d|head -n 1`/$NODE_VER_TO_INSTALL/bin"
echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc) and then restart your shell:$CR$OFF"
echo "export PATH=\$PATH:$NODE_BINARY_PATH:$HOME/.node/bin"

echo """$CR""Upgrading npm...$CR"
echo '++ install -g npm@latest'
npm install -g npm@latest
{ set +x; } &>/dev/null
echo "$REV""$CR""Insert following line in your $HOME/.npmrc file:$OFF"
echo """$CR""prefix=$HOME/.node$CR"
echo "Now, all is likley well if you can run the following without errors:  npm install -g grunt-cli$CR"
echo "Other recommended global installs: bower, gulp, yo, node-inspector$CR"

I wrote a short article here that details why this is "the right way".

If you need to install iojs, do so using nvm like this:

nvm install iojs-v1.7.1

To install brew, just see its home page.

See alexpods answer for the rest.

Excluding directory when creating a .tar.gz file

tar -pczf <target_file.tar.gz> --exclude /path/to/exclude --exclude /another/path/to/exclude/* /path/to/include/ /another/path/to/include/*

Tested in Ubuntu 19.10.

  1. The = after exclude is optional. You can use = instead of space after keyword exclude if you like.
  2. Parameter exclude must be placed before the source.
  3. The difference between use folder name (like the 1st) or the * (like the 2nd) is: the 2nd one will include an empty folder in package but the 1st will not.

How to download source in ZIP format from GitHub?

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch:

http://github.com/user/repository/ -to-> http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Open PDF in new browser full window

I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

Source file 'Properties\AssemblyInfo.cs' could not be found

delete the assemeblyinfo.cs file from project under properties menu and rebulid it.

How to square all the values in a vector in R?

How about sapply (not really necessary for this simple case):

newData<- sapply(data, function(x) x^2)

Add column with number of days between dates in DataFrame pandas

To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html

So,

df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days

which returns:

             A          B   C
one 2014-01-01 2014-02-28  58
two 2014-02-03 2014-03-01  26

Extract a substring using PowerShell

Since the string is not complex, no need to add RegEx strings. A simple match will do the trick

$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World

$result = $matches[0]
$result
Hello World

Dealing with commas in a CSV file

You can read the csv file like this.

this makes use of splits and takes care of spaces.

ArrayList List = new ArrayList();
static ServerSocket Server;
static Socket socket;
static ArrayList<Object> list = new ArrayList<Object>();


public static void ReadFromXcel() throws FileNotFoundException
{   
    File f = new File("Book.csv");
    Scanner in = new Scanner(f);
    int count  =0;
    String[] date;
    String[] name;
    String[] Temp = new String[10];
    String[] Temp2 = new String[10];
    String[] numbers;
    ArrayList<String[]> List = new ArrayList<String[]>();
    HashMap m = new HashMap();

         in.nextLine();
         date = in.nextLine().split(",");
         name = in.nextLine().split(",");
         numbers = in.nextLine().split(",");
         while(in.hasNext())
         {
             String[] one = in.nextLine().split(",");
             List.add(one);
         }
         int xount = 0;
         //Making sure the lines don't start with a blank
         for(int y = 0; y<= date.length-1; y++)
         {
             if(!date[y].equals(""))
             {   
                 Temp[xount] = date[y];
                 Temp2[xount] = name[y];
                 xount++;
             }
         }

         date = Temp;
         name =Temp2;
         int counter = 0;
         while(counter < List.size())
         {
             String[] list = List.get(counter);
             String sNo = list[0];
             String Surname = list[1];
             String Name = list[2];
             for(int x = 3; x < list.length; x++)
             {           
                 m.put(numbers[x], list[x]);
             }
            Object newOne = new newOne(sNo, Name, Surname, m, false);
             StudentList.add(s);
             System.out.println(s.sNo);
             counter++;
         }

tmux status bar configuration

Do C-b, :show which will show you all your current settings. /green, nnn will find you which properties have been set to green, the default. Do C-b, :set window-status-bg cyan and the bottom bar should change colour.

List available colours for tmux

You can tell more easily by the titles and the colours as they're actually set in your live session :show, than by searching through the man page, in my opinion. It is a very well-written man page when you have the time though.

If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf with a line like set window-status-bg -g cyan. Here's mine: https://gist.github.com/9083598

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

How do I see what character set a MySQL database / table / column is?

For all the databases you have on the server:

mysql> SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA;

Output:

+----------------------------+---------+--------------------+
| database                   | charset | collation          |
+----------------------------+---------+--------------------+
| information_schema         | utf8    | utf8_general_ci    |
| my_database                | latin1  | latin1_swedish_ci  |
...
+----------------------------+---------+--------------------+

For a single Database:

mysql> USE my_database;
mysql> show variables like "character_set_database";

Output:

    +----------------------------+---------+
    | Variable_name              |  Value  |
    +----------------------------+---------+
    | character_set_database     |  latin1 | 
    +----------------------------+---------+

Getting the collation for Tables:

mysql> USE my_database;
mysql> SHOW TABLE STATUS WHERE NAME LIKE 'my_tablename';

OR - will output the complete SQL for create table:

mysql> show create table my_tablename


Getting the collation of columns:

mysql> SHOW FULL COLUMNS FROM my_tablename;

output:

+---------+--------------+--------------------+ ....
| field   | type         | collation          |
+---------+--------------+--------------------+ ....
| id      | int(10)      | (NULL)             |
| key     | varchar(255) | latin1_swedish_ci  |
| value   | varchar(255) | latin1_swedish_ci  |
+---------+--------------+--------------------+ ....

how to toggle (hide/show) a table onClick of <a> tag in java script

inside your function toggleTable when you do this line

document.getElementById("loginLink").onclick = toggleTable(....

you are actually calling the function again. so toggleTable gets called again, and again and again, you're falling in an infinite recursive call.

make it simple.

function toggleTable()
{
     var elem=document.getElementById("loginTable");
     var hide = elem.style.display =="none";
     if (hide) {
         elem.style.display="table";
    } 
    else {
       elem.style.display="none";
    }
}

see this fiddle

Java String import

Java compiler imports 3 packages by default. 1. The package without name 2. The java.lang package(That's why you can declare String, Integer, System classes without import) 3. The current package (current file's package)

That's why you don't need to declare import statement for the java.lang package.

Filter rows which contain a certain string

This answer similar to others, but using preferred stringr::str_detect and dplyr rownames_to_column.

library(tidyverse)

mtcars %>% 
  rownames_to_column("type") %>% 
  filter(stringr::str_detect(type, 'Toyota|Mazda') )

#>             type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1      Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> 2  Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> 3 Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#> 4  Toyota Corona 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1

Created on 2018-06-26 by the reprex package (v0.2.0).

Getting execute permission to xp_cmdshell

I want to complete the answer from tchester.

(1) Enable the xp_cmdshell procedure:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database

(3) Grant EXEC permission on the xp_cmdshell stored procedure:

GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]

(4) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'pwd'
-- Note: pwd means windows password for [Domain\TestUser] account id on the box.
--       Don't include square brackets around Domain\TestUser.

(5) Grant control server permission to user

USE master;
GRANT CONTROL SERVER TO [Domain\TestUser]
GO

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.

EDIT: Old. My testing was done largely on SQL 2005. Most of these seem to not exist anymore, but every once in awhile we question the assumption when SQL 2014 does something dumb and we go back to the old way and it works. We never managed to demonstrate that it wasn't just a bad plan generation on more recent cases though since SQL server can be relied on to get the old way right in newer versions. Since all cases were IO bound queries MAXDOP 1 doesn't hurt.

No grammar constraints (DTD or XML schema) detected for the document

What I found to be the solution was something very very simple that I think you should try before tinkering with the preferences. In my case I had this problem in a strings file that had as a base tag "resources" ...all I did was delete the tag from the top and the bottom, clean the project, save the file and reinsert the tag. The problem has since disappeared and never gave me any warnings. It may sound to simple to be true but hey, sometimes it's the simplest things that solve the problems. Cheers

How to check for null in Twig?

I don't think you can. This is because if a variable is undefined (not set) in the twig template, it looks like NULL or none (in twig terms). I'm pretty sure this is to suppress bad access errors from occurring in the template.

Due to the lack of a "identity" in Twig (===) this is the best you can do

{% if var == null %}
    stuff in here
{% endif %}

Which translates to:

if ((isset($context['somethingnull']) ? $context['somethingnull'] : null) == null)
{
  echo "stuff in here";
}

Which if your good at your type juggling, means that things such as 0, '', FALSE, NULL, and an undefined var will also make that statement true.

My suggest is to ask for the identity to be implemented into Twig.

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

How can I format date by locale in Java?

SimpleDateFormat has a constructor which takes the locale, have you tried that?

http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Something like new SimpleDateFormat("your-pattern-here", Locale.getDefault());

Writing a VLOOKUP function in vba

How about just using:

result = [VLOOKUP(DATA!AN2, DATA!AA9:AF20, 5, FALSE)]

Note the [ and ].

Django -- Template tag in {% if %} block

{% for source in sources %}
  <tr>
    <td>{{ source }}</td>
    <td>
      {% ifequal title source %}
        Just now!
      {% endifequal %}
    </td>
  </tr>
{% endfor %}

                or


{% for source in sources %}
      <tr>
        <td>{{ source }}</td>
        <td>
          {% if title == source %}
            Just now!
          {% endif %}
        </td>
      </tr>
    {% endfor %}

See Django Doc

Python: How would you save a simple settings/config file?

Try using ReadSettings:

from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"

Visual Studio Code compile on save

May 2018 update:

As of May 2018 you no longer need to create tsconfig.json manually or configure task runner.

  1. Run tsc --init in your project folder to create tsconfig.json file (if you don't have one already).
  2. Press Ctrl+Shift+B to open a list of tasks in VS Code and select tsc: watch - tsconfig.json.
  3. Done! Your project is recompiled on every file save.

You can have several tsconfig.json files in your workspace and run multiple compilations at once if you want (e.g. frontend and backend separately).

Original answer:

You can do this with Build commands:

Create a simple tsconfig.json with "watch": true (this will instruct compiler to watch all compiled files):

{
    "compilerOptions": {
        "target": "es5",
        "out": "js/script.js",
        "watch": true
    }
}

Note that files array is omitted, by default all *.ts files in all subdirectories will be compiled. You can provide any other parameters or change target/out, just make sure that watch is set to true.

Configure your task (Ctrl+Shift+P -> Configure Task Runner):

{
    "version": "0.1.0",
    "command": "tsc",
    "showOutput": "silent",
    "isShellCommand": true,
    "problemMatcher": "$tsc"
}

Now press Ctrl+Shift+B to build the project. You will see compiler output in the output window (Ctrl+Shift+U).

The compiler will compile files automatically when saved. To stop the compilation, press Ctrl+P -> > Tasks: Terminate Running Task

I've created a project template specifically for this answer: typescript-node-basic

Mongoose: Find, modify, save

If you want to use find, like I would for any validation you want to do on the client side.

find returns an ARRAY of objects

findOne returns only an object

Adding user = user[0] made the save method work for me.

Here is where you put it.

User.find({username: oldUsername}, function (err, user) {
    user = user[0];
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

installing apache: no VCRUNTIME140.dll

Check if your OS is Windows 7 Service Pack 1.. use "winver" to verify.

Make sure Service Pack 1 is there after "Build #### : Service Pack 1"

How do I disable the security certificate check in Python requests

If you are writing a scraper and really don't care about the SSL certificate you can set it global:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

DO NOT USE IN PRODUCTION

The request was rejected because no multipart boundary was found in springboot

I met this problem because I use request.js which writen base on axios
And I already set a defaults.headers in request.js

import axios from 'axios'
const request = axios.create({
  baseURL: '', 
  timeout: 15000 
})
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

here is how I solve this
instead of

request.post('/manage/product/upload.do',
      param,config
    )

I use axios directly send request,and didn't add config

axios.post('/manage/product/upload.do',
      param
    )

hope this can solve your problem

String vs. StringBuilder

If you're doing a lot of string concatenation, use a StringBuilder. When you concatenate with a String, you create a new String each time, using up more memory.

Alex

Converting a String to Object

A Java String is an Object. (String extends Object.)

So you can get an Object reference via assignment/initialisation:

String a = "abc";
Object b = a;

How do I convert seconds to hours, minutes and seconds?

You can use datetime.timedelta function:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

Query to get the names of all tables in SQL Server 2008 Database

To get the fields info too, you can use the following:

SELECT TABLE_SCHEMA, TABLE_NAME, 
       COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema") 
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION

github: server certificate verification failed

It can be also self-signed certificate, etc. Turning off SSL verification globally is unsafe. You can install the certificate so it will be visible for the system, but the certificate should be perfectly correct.

Or you can clone with one time configuration parameter, so the command will be:

git clone -c http.sslverify=false https://myserver/<user>/<project>.git;

GIT will remember the false value, you can check it in the <project>/.git/config file.

How to disable/enable select field using jQuery?

Your select doesn't have an ID, only a name. You'll need to modify your selector:

$("#pizza").on("click", function(){
  $("select[name='pizza_kind']").prop("disabled", !this.checked);
});

Demo: http://jsbin.com/imokuj/2/edit

Traverse all the Nodes of a JSON Object Tree with JavaScript

You can get all keys / values and preserve the hierarchy with this

// get keys of an object or array
function getkeys(z){
  var out=[]; 
  for(var i in z){out.push(i)};
  return out;
}

// print all inside an object
function allInternalObjs(data, name) {
  name = name || 'data';
  return getkeys(data).reduce(function(olist, k){
    var v = data[k];
    if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
    else { olist.push(name + '.' + k + ' = ' + v); }
    return olist;
  }, []);
}

// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')

This is a modification on (https://stackoverflow.com/a/25063574/1484447)

How to replace case-insensitive literal substrings in Java

Not as elegant perhaps as other approaches but it's pretty solid and easy to follow, esp. for people newer to Java. One thing that gets me about the String class is this: It's been around for a very long time and while it supports a global replace with regexp and a global replace with Strings (via CharSequences), that last doesn't have a simple boolean parameter: 'isCaseInsensitive'. Really, you'd've thought that just by adding that one little switch, all the trouble its absence causes for beginners especially could have been avoided. Now on JDK 7, String still doesn't support this one little addition!

Well anyway, I'll stop griping. For everyone in particular newer to Java, here's your cut-and-paste deus ex machina. As I said, not as elegant and won't win you any slick coding prizes, but it works and is reliable. Any comments, feel free to contribute. (Yes, I know, StringBuffer is probably a better choice of managing the two character string mutation lines, but it's easy enough to swap the techniques.)

public String replaceAll(String findtxt, String replacetxt, String str, 
        boolean isCaseInsensitive) {
    if (str == null) {
        return null;
    }
    if (findtxt == null || findtxt.length() == 0) {
        return str;
    }
    if (findtxt.length() > str.length()) {
        return str;
    }
    int counter = 0;
    String thesubstr = "";
    while ((counter < str.length()) 
            && (str.substring(counter).length() >= findtxt.length())) {
        thesubstr = str.substring(counter, counter + findtxt.length());
        if (isCaseInsensitive) {
            if (thesubstr.equalsIgnoreCase(findtxt)) {
                str = str.substring(0, counter) + replacetxt 
                    + str.substring(counter + findtxt.length());
                // Failing to increment counter by replacetxt.length() leaves you open
                // to an infinite-replacement loop scenario: Go to replace "a" with "aa" but
                // increment counter by only 1 and you'll be replacing 'a's forever.
                counter += replacetxt.length();
            } else {
                counter++; // No match so move on to the next character from
                           // which to check for a findtxt string match.
            }
        } else {
            if (thesubstr.equals(findtxt)) {
                str = str.substring(0, counter) + replacetxt 
                    + str.substring(counter + findtxt.length());
                counter += replacetxt.length();
            } else {
                counter++;
            }
        }
    }
    return str;
}

SQL Server: converting UniqueIdentifier to string in a case statement

I think I found the answer:

convert(nvarchar(50), RequestID)

Here's the link where I found this info:

http://msdn.microsoft.com/en-us/library/ms187928.aspx

Set custom attribute using JavaScript

For people coming from Google, this question is not about data attributes - OP added a non-standard attribute to their HTML object, and wondered how to set it.

However, you should not add custom attributes to your properties - you should use data attributes - e.g. OP should have used data-icon, data-url, data-target, etc.

In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:

ele.setAttribute(attributeName, value);

to change the given attribute attributeName to value for the DOM element ele.

For example:

document.getElementById("someElement").setAttribute("data-id", 2);

Note that you can also use .dataset to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute method instead.

How do I capture all of my compiler's output to a file?

The compiler warnings happen on stderr, not stdout, which is why you don't see them when you just redirect make somewhere else. Instead, try this if you're using Bash:

$ make &> results.txt

The & means "redirect stdout and stderr to this location". Other shells often have similar constructs.

Generating (pseudo)random alpha-numeric strings

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo generateRandomString();

How to catch all exceptions in c# using try and catch?

Both ways are correct.

If you need to do something with the Exception object in the catch block then you should use

try {
    // code....
}
catch (Exception ex){}

and then use ex in the catch block.

Anyway, it is not always a good practice to catch the Exception class, it is a better practice to catch a more specific exception - an exception which you expect.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Revert to Eclipse default settings

It is simple.

First, you open eclipse but with workspace different with workspace you have working. then, you choose File / Export / --> General / Preferences --> choose to folder which you want to pick the file *.epf

Second, you open eclipse with workspace you want to work. Then choose File / Import / --> General / Preferences --> choose to folder which you had picked the file *.epf and OK

Have fun!

Key existence check in HashMap

if(map.get(key) != null || (map.get(key) == null && map.containsKey(key)))

How to correctly catch change/focusOut event on text input in React.js?

Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.

What is the hamburger menu icon called and the three vertical dots icon called?

Cannot say about the "official nomenclature" - infact I wonder whose word will be "official" anyway - but here's how they can be called:

Variable declaration in a header file

You can (should) declare it as extern in a header file, and define it in exactly 1 .c file.

Note that that .c file should also use the header and that the standard pattern looks like:

// file.h
extern int x;  // declaration

// file.c
#include "file.h"
int x = 1;    // definition and re-declaration

How to open/run .jar file (double-click not working)?

In cmd you can use the following:

c:\your directory\your folder\build>java -jar yourFile.jar 

However, you need to create you .jar file on your project if you use Netbeans. How just go to Run ->Clean and Build Project(your project name)

Also make sure you project properties Build->Packing has a yourFile.jar and check Build JAR after Compiling check Copy Depentent Libraries

Warning: Make sure your Environmental variables for Java are properly set.

Old way to compile and run a Java File from the command prompt (cmd)

Compiling: c:\>javac Myclass.java
Running: c:\>java com.myPackage.Myclass

I hope this info help.

Get the current language in device

Answers above don't distinguish between simple chinese and traditinal chinese. Locale.getDefault().toString() works which returns "zh_CN", "zh_TW", "en_US" and etc.

References to : https://developer.android.com/reference/java/util/Locale.html, ISO 639-1 is OLD.

The cast to value type 'Int32' failed because the materialized value is null

Had this error message when I was trying to select from a view.

The problem was the view recently had gained some new null rows (in SubscriberId column), and it had not been updated in EDMX (EF database first).

The column had to be Nullable type for it to work.

var dealer = Context.Dealers.Where(x => x.dealerCode == dealerCode).FirstOrDefault();

Before view refresh:

public int SubscriberId { get; set; }

After view refresh:

public Nullable<int> SubscriberId { get; set; }

Deleting and adding the view back in EDMX worked.

Hope it helps someone.

Click toggle with jQuery

In JQuery I don't think that click() accepts two functions for toggling. You should use the toggle() function for that: http://docs.jquery.com/Events/toggle

Remove x-axis label/text in chart.js

The simplest solution is:

scaleFontSize: 0

see the chart.js Document

smilar question

How do I wait until Task is finished in C#?

async Task<int> AccessTheWebAsync()  
{   
    // You need to add a reference to System.Net.Http to declare client.  
    HttpClient client = new HttpClient();  

    // GetStringAsync returns a Task<string>. That means that when you await the  
    // task you'll get a string (urlContents).  
    Task<string> getStringTask = 

    client.GetStringAsync("http://msdn.microsoft.com");  

    // You can do work here that doesn't rely on the string from GetStringAsync.  
    DoIndependentWork();  

    // The await operator suspends AccessTheWebAsync.  
    //  - AccessTheWebAsync can't continue until getStringTask is complete.  
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.  
    //  - Control resumes here when getStringTask is complete.   
    //  - The await operator then retrieves the string result from 
    getStringTask.  
    string urlContents = await getStringTask;  

    // The return statement specifies an integer result.  
    // Any methods that are awaiting AccessTheWebenter code hereAsync retrieve the length 
    value.  
    return urlContents.Length;  
}  

How to Identify port number of SQL server

PowerShell solution that shows all of the instances on the host as well as their incoming traffic addresses. The second bit might be helpful if all you know is the DNS:

ForEach ($SQL_Proc in Get-Process | Select-Object -Property ProcessName, Id | Where-Object {$_.ProcessName -like "*SQL*"})
{
    Get-NetTCPConnection | `
     Where-Object {$_.OwningProcess -eq $SQL_Proc.id} | `
      Select-Object -Property `
                                @{Label ="Process_Name";e={$SQL_Proc.ProcessName}}, `
                                @{Label ="Local_Address";e={$_.LocalAddress + ":" + $_.LocalPort }},  `
                                @{Label ="Remote_Address";e={$_.RemoteAddress + ":" + $_.RemotePort}}, State | `
      Format-Table
} 

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

Create ul and li elements in javascript.

Great then. Let's create a simple function that takes an array and prints our an ordered listview/list inside a div tag.

Step 1: Let's say you have an div with "contentSectionID" id.<div id="contentSectionID"></div>

Step 2: We then create our javascript function that returns a list component and takes in an array:

function createList(spacecrafts){

var listView=document.createElement('ol');

for(var i=0;i<spacecrafts.length;i++)
{
    var listViewItem=document.createElement('li');
    listViewItem.appendChild(document.createTextNode(spacecrafts[i]));
    listView.appendChild(listViewItem);
}

return listView;
}

Step 3: Finally we select our div and create a listview in it:

document.getElementById("contentSectionID").appendChild(createList(myArr));

running multiple bash commands with subprocess

I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with Popen, but it wasn't possible in my situation.

What I ended up doing is something like:

commands = '''
echo "a"
echo "b"
echo "c"
echo "d"
'''

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out

So I first create the child bash process and after I tell it what to execute. This approach removes the limitations of passing the command directly to the Popen constructor.

How to call multiple JavaScript functions in onclick event?

A link with 1 function defined

<a href="#" onclick="someFunc()">Click me To fire some functions</a>

Firing multiple functions from someFunc()

function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

Make sure you Double-Check that the version you refer to in the child-pom is the same as that in the parent-pom. For me, I'd bumped version in the parent and had it as 3.1.0.0-RELEASE, but in the child-pom, I was still referring to the previous version via relativePath, and had it defined as 2.0.0.0-SNAPSHOT. It did not make any difference if I included just the parent directory, or had the "pom.xml" appended to the directory:

    <parent>        
    <artifactId>eric-project-parent</artifactId>
    <groupId>com.eric.common</groupId>
     <!-- Should be 3.1.0.0-RELEASE -->
    <version>2.0.0.0-SNAPSHOT</version>     
    <relativePath>
                ../../EricParentAsset/projects/eric-project-parent</relativePath>           
</parent>

Finding the average of a list

I tried using the options above but didn't work. Try this:

from statistics import mean

n = [11, 13, 15, 17, 19]

print(n)
print(mean(n))

worked on python 3.5

C default arguments

Another trick using macros:

#include <stdio.h>

#define func(...) FUNC(__VA_ARGS__, 15, 0)
#define FUNC(a, b, ...) func(a, b)

int (func)(int a, int b)
{
    return a + b;
}

int main(void)
{
    printf("%d\n", func(1));
    printf("%d\n", func(1, 2));
    return 0;
}

If only one argument is passed, b receives the default value (in this case 15)

ASP.net page without a code behind

There are two very different types of pages in SharePoint: Application Pages and Site Pages.

If you are going to use your page as an Application Page, you can safely use inline code or code behind in your page, as Application pages live on the file system.

If it's going to be a Site page, you can safely write inline code as long as you have it like that in the initial deployment. However if your site page is going to be customized at some point in the future, the inline code will no longer work because customized site pages live in the database and are executed in asp.net's "no compile" mode.

Bottom line is - you can write aspx pages with inline code. The only problem is with customized Site pages... which will no longer care for your inline code.

Set ANDROID_HOME environment variable in mac

Open Terminal

nano ~/.bash_profile


export ANDROID_HOME=/Users/qss/Library/Android/sdk
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH

Control+S to save
Control+X to exit
Y to save changes
Update changes in terminal
source ~/.bash_profile

Validate Path:
echo $PATH

Confirm if all okay:
adb devices

symfony 2 twig limit the length of the text and put three dots

why not use twig's truncate or wordwrap filter? It belongs to twig extensions and lib is part of Symfony2.0 as i see.

{{ text|truncate(50) }}

How to get the selected index of a RadioGroup in Android

You can either use OnCheckedChangeListener or can use getCheckedRadioButtonId()

What does the fpermissive flag do?

The -fpermissive flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Moment JS start and end of given month

When you use .endOf() you are mutating the object it's called on, so startDate becomes Sep 30

You should use .clone() to make a copy of it instead of changing it

var startDate = moment(year + '-' + month + '-' + 01 + ' 00:00:00');
            var endDate = startDate.clone().endOf('month');
            console.log(startDate.toDate());
            console.log(endDate.toDate());

Mon Sep 01 2014 00:00:00 GMT+0700 (ICT) 
Tue Sep 30 2014 23:59:59 GMT+0700 (ICT) 

Get original URL referer with PHP?

Store it in a cookie that only lasts for the current browsing session

Are list-comprehensions and functional functions faster than "for loops"?

Adding a twist to Alphii answer, actually the for loop would be second best and about 6 times slower than map

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        a += i**2
    return a

def square_sum3(numbers):
    a = 0
    map(lambda x: a+x**2, numbers)
    return a

def square_sum4(numbers):
    a = 0
    return [a+i**2 for i in numbers]

time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])

Main changes have been to eliminate the slow sum calls, as well as the probably unnecessary int() in the last case. Putting the for loop and map in the same terms makes it quite fact, actually. Remember that lambdas are functional concepts and theoretically shouldn't have side effects, but, well, they can have side effects like adding to a. Results in this case with Python 3.6.1, Ubuntu 14.04, Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz

0:00:00.257703 #Reduce
0:00:00.184898 #For loop
0:00:00.031718 #Map
0:00:00.212699 #List comprehension

node.js, socket.io with SSL

This is how I managed to set it up with express:

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
    key: fs.readFileSync('./test_key.key'),
    cert: fs.readFileSync('./test_cert.crt'),
    ca: fs.readFileSync('./test_ca.crt'),
    requestCert: false,
    rejectUnauthorized: false
},app);
server.listen(8080);

var io = require('socket.io').listen(server);

io.sockets.on('connection',function (socket) {
    ...
});

app.get("/", function(request, response){
    ...
})


I hope that this will save someone's time.

Update : for those using lets encrypt use this

var server = https.createServer({ 
                key: fs.readFileSync('privkey.pem'),
                cert: fs.readFileSync('fullchain.pem') 
             },app);

Django - Reverse for '' not found. '' is not a valid view function or pattern name

If you dont define name in the path field, usually the error will come. e.g.: path('crud/',ABC.as_view(),name="crud")

Maximum value of maxRequestLength?

These two settings worked for me to upload 1GB mp4 videos.

<system.web>
    <httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="2147483648" />
        </requestFiltering>
    </security>
</system.webServer>

update to python 3.7 using anaconda

To see just the Python releases, do conda search --full-name python.

DropDownList's SelectedIndexChanged event not firing

Add property ViewStateMode="Enabled" and EnableViewState="true" And AutoPostBack="true" in drop DropDownList

NSAttributedString add text alignment

 NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
 paragraphStyle.alignment                = NSTextAlignmentCenter;

 NSAttributedString *attributedString   = 
[NSAttributedString.alloc initWithString:@"someText" 
                              attributes:
         @{NSParagraphStyleAttributeName:paragraphStyle}];

Swift 4.2

let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center

    let attributedString = NSAttributedString(string: "someText", attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle])

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Changing the text on a label

Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar

If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.

There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.

text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
                                                                    ^^^^^^^^^^^^^^^^^
  def depositCallBack(self,event):
      text.set('change the value')

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

I had the same problem. It turned out that I didn't specify a default page and I didn't have any page that is named after the default page convention (default.html, defult.aspx etc). As a result, ASP.NET doesn't allow the user to browse the directory (not a problem in Visual Studio built-in web server that allows you to view the directory) and shows the error message. To fix it, I added one default page in Web.Config and it worked.

<system.webServer>
    <defaultDocument>
        <files>
            <add value="myDefault.aspx"/>
        </files>
    </defaultDocument>
</system.webServer>

JSON Array iteration in Android/Java

Unfortunately , JSONArray doesn't support foreach statements, like:

_x000D_
_x000D_
for(JSONObject someObj : someJsonArray) {_x000D_
    // do something about someObj_x000D_
    ...._x000D_
    ...._x000D_
}
_x000D_
_x000D_
_x000D_

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

Python: OSError: [Errno 2] No such file or directory: ''

Have you noticed that you don't get the error if you run

python ./script.py

instead of

python script.py

This is because sys.argv[0] will read ./script.py in the former case, which gives os.path.dirname something to work with. When you don't specify a path, sys.argv[0] reads simply script.py, and os.path.dirname cannot determine a path.

Renaming Column Names in Pandas Groupby function

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

Deprecated Answer as of pandas version 0.20

This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg method.

These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.

Before we get there, let's create a four column DataFrame.

df = pd.DataFrame({'A' : list('wwwwxxxx'), 
                   'B':list('yyzzyyzz'), 
                   'C':np.random.rand(8), 
                   'D':np.random.rand(8)})

   A  B         C         D
0  w  y  0.643784  0.828486
1  w  y  0.308682  0.994078
2  w  z  0.518000  0.725663
3  w  z  0.486656  0.259547
4  x  y  0.089913  0.238452
5  x  y  0.688177  0.753107
6  x  z  0.955035  0.462677
7  x  z  0.892066  0.368850

Let's say we want to group by columns A, B and aggregate column C with mean and median and aggregate column D with max. The following code would do this.

df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})

            D         C          
          max      mean    median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:

df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'}, 
                            'D':{'D_max': 'max'}})

            D         C          
        D_max    C_mean  C_median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0).

Adding asterisk to required fields in Bootstrap 3

The other two answers are correct. When you include spaces in your CSS selectors you're targeting child elements so:

.form-group .required {
    styles
}

Is targeting an element with the class of "required" that is inside an element with the class of "form-group".

Without the space it's targeting an element that has both classes. 'required' and 'form-group'

How do I perform a Perl substitution on a string while keeping the original?

If you write Perl with use strict;, then you'll find that the one line syntax isn't valid, even when declared.

With:

my ($newstring = $oldstring) =~ s/foo/bar/;

You get:

Can't declare scalar assignment in "my" at script.pl line 7, near ") =~"
Execution of script.pl aborted due to compilation errors.

Instead, the syntax that you have been using, while a line longer, is the syntactically correct way to do it with use strict;. For me, using use strict; is just a habit now. I do it automatically. Everyone should.

#!/usr/bin/env perl -wT

use strict;

my $oldstring = "foo one foo two foo three";
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

print "$oldstring","\n";
print "$newstring","\n";

How can we draw a vertical line in the webpage?

There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.

Try this:

CSS

.vr {
    width:10px;
    background-color:#000;
    position:absolute;
    top:0;
    bottom:0;
    left:150px;
}

HTML

<div class="vr">&nbsp;</div>

Demo

How can I change the color of a Google Maps marker?

With version 3 of the Google Maps API, the easiest way to do this may be by grabbing a custom icon set, like the one that Benjamin Keen has created here:

http://www.benjaminkeen.com/?p=105

If you put all of those icons at the same place as your map page, you can colorize a Marker simply by using the appropriate icon option when creating it:

var beachMarker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: 'brown_markerA.png'
});

This is super-easy, and is the approach I'm using for the project I'm working on currently.

Convert timestamp in milliseconds to string formatted time in Java

Try this:

    String sMillis = "10997195233";
    double dMillis = 0;

    int days = 0;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;
    int millis = 0;

    String sTime;

    try {
        dMillis = Double.parseDouble(sMillis);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }


    seconds = (int)(dMillis / 1000) % 60;
    millis = (int)(dMillis % 1000);

    if (seconds > 0) {
        minutes = (int)(dMillis / 1000 / 60) % 60;
        if (minutes > 0) {
            hours = (int)(dMillis / 1000 / 60 / 60) % 24;
            if (hours > 0) {
                days = (int)(dMillis / 1000 / 60 / 60 / 24);
                if (days > 0) {
                    sTime = days + " days " + hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
                } else {
                    sTime = hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
                }
            } else {
                sTime = minutes + " min " + seconds + " sec " + millis + " millisec";
            }
        } else {
            sTime = seconds + " sec " + millis + " millisec";
        }
    } else {
        sTime = dMillis + " millisec";
    }

    System.out.println("time: " + sTime);

How to get the IP address of the docker host from inside a docker container

If you enabled the docker remote API (via -Htcp://0.0.0.0:4243 for instance) and know the host machine's hostname or IP address this can be done with a lot of bash.

Within my container's user's bashrc:

export hostIP=$(ip r | awk '/default/{print $3}')
export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
export proxyPort=$(
  curl -s http://$hostIP:4243/containers/$containerID/json |
  node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
)

The second line grabs the container ID from your local /proc/self/cgroup file.

Third line curls out to the host machine (assuming you're using 4243 as docker's port) then uses node to parse the returned JSON for the DESIRED_PORT.

Your password does not satisfy the current policy requirements

If you don't care what the password policy is. You can set it to LOW by issuing below mysql command:

mysql> SET GLOBAL validate_password_policy=LOW;

Check if a string has white space

This function checks for other types of whitespace, not just space (tab, carriage return, etc.)

import some from 'lodash/fp/some'
const whitespaceCharacters = [' ', '  ',
  '\b', '\t', '\n', '\v', '\f', '\r', `\"`, `\'`, `\\`,
  '\u0008', '\u0009', '\u000A', '\u000B', '\u000C',
'\u000D', '\u0020','\u0022', '\u0027', '\u005C',
'\u00A0', '\u2028', '\u2029', '\uFEFF']
const hasWhitespace = char => some(
  w => char.indexOf(w) > -1,
  whitespaceCharacters
)

console.log(hasWhitespace('a')); // a, false
console.log(hasWhitespace(' ')); // space, true
console.log(hasWhitespace(' ')); // tab, true
console.log(hasWhitespace('\r')); // carriage return, true

If you don't want to use Lodash, then here is a simple some implementation with 2 s:

const ssome = (predicate, list) =>
{
  const len = list.length;
  for(const i = 0; i<len; i++)
  {
    if(predicate(list[i]) === true) {
      return true;
    }
  }
  return false;
};

Then just replace some with ssome.

const hasWhitespace = char => some(
  w => char.indexOf(w) > -1,
  whitespaceCharacters
)

For those in Node, use:

const { some } = require('lodash/fp');

Get time of specific timezone

short answer from client-side: NO, you have to get it from the server side.

Change directory in Node.js command prompt

If you mean to change default directory for "Node.js command prompt", when you launch it, then (Windows case)

  1. go the directory where NodeJS was installed
  2. find file nodevars.bat
  3. open it with editor as administrator
  4. change the default path in the row which looks like

    if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%"
    

with your path. It could be for example

    if "%CD%\"=="%~dp0" cd /d "c://MyDirectory/"

if you mean to change directory once when you launched "Node.js command prompt", then execute the following command in the Node.js command prompt:

     cd c:/MyDirectory/

connecting to phpMyAdmin database with PHP/MySQL

Connect to MySQL

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'username';

/*** mysql password ***/
$password = 'password';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

Also mysqli_connect() function to open a new connection to the MySQL server.

<?php
// Create connection
$con=mysqli_connect(host,username,password,dbname); 

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?> 

Delete cookie by name?

In my case I used blow code for different environment.

  document.cookie = name +`=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;Domain=.${document.domain.split('.').splice(1).join('.')}`;

Tool to generate JSON schema from JSON data

GenSON (PyPI | Github) is a JSON Schema generator that can generate a single schema from multiple objects. You can also merge schemas with it. It is written in Python and comes with a CLI tool.

(Full disclosure: I'm the author.)

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

How to use LDFLAGS in makefile

Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:

CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm

.PHONY: all
all: client

.PHONY: clean
clean:
    $(RM) *~ *.o client

OBJECTS=client.o
client: $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)

In the line defining the client target change the order of $(LDFLAGS) as needed.

Rownum in postgresql

Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.

Null vs. False vs. 0 in PHP

Below is an example:

            Comparisons of $x with PHP functions

Expression          gettype()   empty()     is_null()   isset() boolean : if($x)
$x = "";            string      TRUE        FALSE       TRUE    FALSE
$x = null;          NULL        TRUE        TRUE        FALSE   FALSE
var $x;             NULL        TRUE        TRUE        FALSE   FALSE
$x is undefined     NULL        TRUE        TRUE        FALSE   FALSE
$x = array();       array       TRUE        FALSE       TRUE    FALSE
$x = false;         boolean     TRUE        FALSE       TRUE    FALSE
$x = true;          boolean     FALSE       FALSE       TRUE    TRUE
$x = 1;             integer     FALSE       FALSE       TRUE    TRUE
$x = 42;            integer     FALSE       FALSE       TRUE    TRUE
$x = 0;             integer     TRUE        FALSE       TRUE    FALSE
$x = -1;            integer     FALSE       FALSE       TRUE    TRUE
$x = "1";           string      FALSE       FALSE       TRUE    TRUE
$x = "0";           string      TRUE        FALSE       TRUE    FALSE
$x = "-1";          string      FALSE       FALSE       TRUE    TRUE
$x = "php";         string      FALSE       FALSE       TRUE    TRUE
$x = "true";        string      FALSE       FALSE       TRUE    TRUE
$x = "false";       string      FALSE       FALSE       TRUE    TRUE

Please see this for more reference of type comparisons in PHP. It should give you a clear understanding.

pip installing in global site-packages instead of virtualenv

I had the same problem, I solved it by removing venv directory and recreating it!

deactivate (if venv is activated first deactivate it)
rm -rf venv
virtualenv -p python3 venv
. ENV/bin/activate
pip3 install -r requirements.txt

Now everything works like a charm.

Find and kill a process in one line using bash and regex

If pkill -f csp_build.py doesn't kill the process you can add -9 to send a kill signall which will not be ignored. i.e. pkill -9 -f csp_build.py

Allow anything through CORS Policy

Simply you can add rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0

1st Step: add gem to your Gemfile:

gem 'rack-cors', :require => 'rack/cors'

and then save and run bundle install

2nd Step: update your config/application.rb file by adding this:

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

for more details you can go to https://github.com/cyu/rack-cors Specailly if you don't use rails 5.

C++ equivalent of Java's toString?

As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:

#include <sstream>    
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace

std::stringstream is located in the <sstream> header.

How do I execute a bash script in Terminal?

cd to the directory that contains the script, or put it in a bin folder that is in your $PATH

then type

./scriptname.sh

if in the same directory or

scriptname.sh

if it's in the bin folder.

Python SQLite: database is locked

I also had this problem. I was trying to enter data into the database without saving changes I had made in it. after i saved the changes worked

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

Best way to extract a subvector from a vector?

You could just use insert

vector<type> myVec { n_elements };

vector<type> newVec;

newVec.insert(newVec.begin(), myVec.begin() + X, myVec.begin() + Y);

Invalid Host Header when ngrok tries to connect to React dev server

I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:

module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
},   }

Require the file in the server.

const configstrp      = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;

and connect as such

if (ngrok) {
console.log('If nGronk')
ngrok.connect(
    {
    addr: configstrp.ngrok.port,
    subdomain: configstrp.ngrok.subdomain,
    authtoken: configstrp.ngrok.authtoken,
    host_header:3000
  },
  (err, url) => {
    if (err) {

    } else {

    }
   }
  );
 }

Do not pass a subdomain if you do not have a custom domain

scp with port number specified

You know what's cooler than -P? nothing

If you use this server more than a few times, setup/create a ~/.ssh/config file with an entry like:

Host www.myserver.com
    Port 80

or

Host myserver myserver80 short any.name.u.want yes_anything well-within-reason
    HostName www.myserver.com
    Port 80
    User username

Then you can use:

scp [email protected]:/root/file.txt .

or

scp short:/root/file.txt .

You can use anything on the "Host" line with ssh, scp, rsync, git & more

There are MANY configuration option that you can use in config files, see:

man ssh_config

FileNotFoundError: [Errno 2] No such file or directory

Lets say we have a script in "c:\script.py" that contain :

result = open("index.html","r")
print(result.read())

Lets say that the index.html file is also in the same directory "c:\index.html" when i execute the script from cmd (or shell)

C:\Users\Amine>python c:\script.py

You will get error:

FileNotFoundError: [Errno 2] No such file or directory: 'index.html'

And that because "index.html" is not in working directory which is "C:\Users\Amine>". so in order to make it work you have to change the working directory

C:\python script.py

'<html><head></head><body></body></html>'

This is why is it preferable to use absolute path.

Outline effect to text

This mixin for SASS will give smooth results, using 8-axis:

@mixin stroke($size: 1px, $color: #000) {
  text-shadow:
    -#{$size} -#{$size} 0 $color,
     0        -#{$size} 0 $color,
     #{$size} -#{$size} 0 $color,
     #{$size}  0        0 $color,
     #{$size}  #{$size} 0 $color,
     0         #{$size} 0 $color,
    -#{$size}  #{$size} 0 $color,
    -#{$size}  0        0 $color;
}

And normal CSS:

text-shadow:
  -1px -1px 0 #000,
   0   -1px 0 #000,
   1px -1px 0 #000,
   1px  0   0 #000,
   1px  1px 0 #000,
   0    1px 0 #000,
  -1px  1px 0 #000,
  -1px  0   0 #000;

How do I edit SSIS package files?

Current for 2016 link is https://msdn.microsoft.com/en-us/library/mt204009.aspx

SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.

Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.

This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016

Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer http://sqlmag.com/sql-server-2014/q-where-business-intelligence-development-studio-bids-sql-server-2014

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

If you want to generate a file in the Windows, then, please follow the below steps:

  1. Go to a directory where you want to save the generated file
  2. Open the command prompt on that directory
  3. Run this fsutil file createnew [filename].[extension] [# of bytes] command. For example fsutil file createnew test.pdf 999999999
  4. 95.3 MB File will be generated

Update: The generated file will not be a valid pdf file. It just holds the given size.

What does DIM stand for in Visual Basic and BASIC?

Dimension a variable, basically you are telling the compiler that you are going to need a variable of this type at some point.

SQL Server FOR EACH Loop

[CREATE PROCEDURE [rat].[GetYear]

AS
BEGIN

-- variable for storing start date
Declare @StartYear as int
-- Variable for the End date 
Declare @EndYear as int 

-- Setting the value in strat Date
select @StartYear = Value from   rat.Configuration where Name = 'REPORT_START_YEAR'; 

-- Setting the End date 
select @EndYear = Value from   rat.Configuration where Name = 'REPORT_END_YEAR'; 


-- Creating Tem table 
    with [Years] as
    (
        --Selecting the Year
        select @StartYear [Year] 
        --doing Union 
        union all
         -- doing the loop in Years table 
         select Year+1 Year from [Years] where Year < @EndYear
     )
    --Selecting the Year table 
selec]

Check difference in seconds between two times

Assuming dateTime1 and dateTime2 are DateTime values:

var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;

In your case, you 'd use DateTime.Now as one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1 is earlier than dateTime2.

What is the Swift equivalent of respondsToSelector?

The equivalent is the ? operator:

var value: NSNumber? = myQuestionableObject?.importantMethod()

importantMethod will only be called if myQuestionableObject exists and implements it.

Android: Vertical alignment for multi line EditText (Text area)

Use this:

android:gravity="top"

or

android:gravity="top|left"

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

Graphviz: How to go from .dot to a graph?

dot file.dot -Tpng -o image.png

This works on Windows and Linux. Graphviz must be installed.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

npm install -g npm-install-peers

it will add all the missing peers and remove all the error

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

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

You can use simple form:

@using(Html.BeginForm("Update", "Shopping"))
{
    <input type="text" id="ss" name="qty" value="@item.Quantity"/>
    ...
    <input type="submit" value="Update" />
}

And add here attribute:

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)

How to dynamically create a class?

You want to look at CodeDOM. It allows defining code elements and compiling them. Quoting MSDN:

...This object graph can be rendered as source code using a CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.

How can I start PostgreSQL server on Mac OS X?

If you didn't install it with Homebrew and directly from the Mac package, this worked for me for PostgreSQL 12 when using all the default locations, variables, etc.

$ sudo su postgres
bash-3.2$ /Library/PostgreSQL/12/bin/pg_ctl -D /Library/PostgreSQL/12/data/ stop

iOS 8 UITableView separator inset 0 not working

Lukasz answer in Swift:

    // iOS 7:
    UITableView.appearance().separatorStyle = .SingleLine
    UITableView.appearance().separatorInset = UIEdgeInsetsZero
    UITableViewCell.appearance().separatorInset = UIEdgeInsetsZero

    // iOS 8:
    if UITableView.instancesRespondToSelector("setLayoutMargins:") {
        UITableView.appearance().layoutMargins = UIEdgeInsetsZero
        UITableViewCell.appearance().layoutMargins = UIEdgeInsetsZero
        UITableViewCell.appearance().preservesSuperviewLayoutMargins = false
    }

Stop form from submitting , Using Jquery

Try the code below. e.preventDefault() was added. This removes the default event action for the form.

 $(document).ready(function () {
    $("form").submit(function (e) {
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
        });
        e.preventDefault();
    });
});

Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?

Here is an example of some added validation

 $(document).ready(function () {
    $("form").submit(function (e) {
      /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
    if(!$('#inputID').val()){ 
       e.preventDefault(); // This will prevent the form submission
     } else{
        // In the event all validations pass. THEN process AJAX request.
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
       });
     }


    });
 });

Using find to locate files that match one of multiple patterns

I had a similar need. This worked for me:

find ../../ \( -iname 'tmp' -o -iname 'vendor' \) -prune -o \( -iname '*.*rb' -o -iname '*.rjs' \) -print

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

Get a list of dates between two dates

You can use MySQL's user variables like this:

SET @num = -1;
SELECT DATE_ADD( '2009-01-01', interval @num := @num+1 day) AS date_sequence, 
your_table.* FROM your_table
WHERE your_table.other_column IS NOT NULL
HAVING DATE_ADD('2009-01-01', interval @num day) <= '2009-01-13'

@num is -1 because you add to it the first time you use it. Also, you can't use "HAVING date_sequence" because that makes the user variable increment twice for each row.

Recursive search and replace in text files on Mac and Linux

https://bitbucket.org/masonicboom/serp is a go utility (i.e. cross-platform), tested on OSX, that does recursive search-and-replace for text in files within a given directory, and confirms each replacement. It's new, so might be buggy.

Usage looks like:

$ ls test
a  d  d2 z
$ cat test/z
hi
$ ./serp --root test --search hi --replace bye --pattern "*"                         
test/z: replace hi with bye? (y/[n]) y
$ cat test/z
bye

.Net System.Mail.Message adding multiple "To" addresses

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;

namespace HMS.HtmlHelper
{
    public class SendmailHelper
    {
        //Created SendEMail method for sendiing mails to users 
        public bool SendEMail(string FromName, string ToAddress, string Subject, string Message)
        {
            bool valid =false;
            try
            {
                string smtpUserName = System.Configuration.ConfigurationManager.AppSettings["smtpusername"].ToString();
                string smtpPassword = System.Configuration.ConfigurationManager.AppSettings["smtppassword"].ToString();
                MailMessage mail = new MailMessage();``
                mail.From = new MailAddress(smtpUserName, FromName);
                mail.Subject = Subject;
                mail.To.Add(FormatMultipleEmailAddresses(ToAddress));
                //mail.To.Add(ToAddress);
                mail.Body = Message.ToString();
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["smtpserverport"]);
                smtp.Host = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]; /
                smtp.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
                smtp.EnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ssl"]); ;
                smtp.Send(mail);
                valid = true;

            }
            catch (Exception ex)
            {
                valid =false ;
            }

            return valid;
        }



        public string FormatMultipleEmailAddresses(string emailAddresses)
        {
            var delimiters = new[] { ',', ';' };

            var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

            return string.Join(",", addresses);
        }

    }
}``

Create Log File in Powershell

Gist with log rotation: https://gist.github.com/barsv/85c93b599a763206f47aec150fb41ca0

Usage:

. .\logger.ps1
Write-Log "debug message"
Write-Log "info message" "INFO"

How to check if a String contains only ASCII?

This will return true if String only contains ASCII characters and false when it does not

Charset.forName("US-ASCII").newEncoder().canEncode(str)

If You want to remove non ASCII , here is the snippet:

if(!Charset.forName("US-ASCII").newEncoder().canEncode(str)) {
                        str = str.replaceAll("[^\\p{ASCII}]", "");
                    }

Can I run multiple programs in a Docker container?

I agree with the other answers that using two containers is preferable, but if you have your heart set on bunding multiple services in a single container you can use something like supervisord.

in Hipache for instance, the included Dockerfile runs supervisord, and the file supervisord.conf specifies for both hipache and redis-server to be run.

Check if string is in a pandas dataframe

You should use any()

In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True

In [99]: if a['Names'].str.contains('Mel').any():
   ....:     print "Mel is there"
   ....:
Mel is there

a['Names'].str.contains('Mel') gives you a series of bool values

In [100]: a['Names'].str.contains('Mel')
Out[100]:
0    False
1    False
2    False
3    False
4     True
Name: Names, dtype: bool

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

PHP class: Global variable as property in class

What I've experienced is that you can't assign your global variable to a class variable directly.

class myClass() {

    public $var = $GLOBALS['variable'];

    public function func() {
         var_dump($this->var);
    }
}

With the code right above, you get an error saying "Parse error: syntax error, unexpected '$GLOBALS'"

But if we do something like this,

class myClass() {

    public $var = array();

    public function __construct() {
        $this->var = $GLOBALS['variable'];
    }

    public function func() {
         var_dump($this->var);
    }

}

Our code will work fine.

Where we assign a global variable to a class variable must be inside a function. And I've used constructor function for this.

So, you can access your global variable inside the every function of a class just using $this->var;

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

How to use Comparator in Java to sort

Here's an example of a Comparator that will work for any zero arg method that returns a Comparable. Does something like this exist in a jdk or library?

import java.lang.reflect.Method;
import java.util.Comparator;

public class NamedMethodComparator implements Comparator<Object> {

    //
    // instance variables
    //

    private String methodName;

    private boolean isAsc;

    //
    // constructor
    //

    public NamedMethodComparator(String methodName, boolean isAsc) {
        this.methodName = methodName;
        this.isAsc = isAsc;
    }

    /**
     * Method to compare two objects using the method named in the constructor.
     */
    @Override
    public int compare(Object obj1, Object obj2) {
        Comparable comp1 = getValue(obj1, methodName);
        Comparable comp2 = getValue(obj2, methodName);
        if (isAsc) {
            return comp1.compareTo(comp2);
        } else {
            return comp2.compareTo(comp1);
        }
    }

    //
    // implementation
    //

    private Comparable getValue(Object obj, String methodName) {
        Method method = getMethod(obj, methodName);
        Comparable comp = getValue(obj, method);
        return comp;
    }

    private Method getMethod(Object obj, String methodName) {
        try {
            Class[] signature = {};
            Method method = obj.getClass().getMethod(methodName, signature);
            return method;
        } catch (Exception exp) {
            throw new RuntimeException(exp);
        }
    }

    private Comparable getValue(Object obj, Method method) {
        Object[] args = {};
        try {
            Object rtn = method.invoke(obj, args);
            Comparable comp = (Comparable) rtn;
            return comp;
        } catch (Exception exp) {
            throw new RuntimeException(exp);
        }
    }

}

How can I force a hard reload in Chrome for Android

Viewing the page in incognito mode will disable the cache. It was the only way I could force a refresh on a stylesheet without manually clearing the cache through the settings.

A simple command line to download a remote maven2 artifact to the local repository?

As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used

mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
    -DremoteRepositories=http://download.java.net/maven/2 \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
    -Ddest=c:\temp\robo-guice.jar

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

In Python, how do I determine if an object is iterable?

It's always eluded me as to why python has callable(obj) -> bool but not iterable(obj) -> bool...
surely it's easier to do hasattr(obj,'__call__') even if it is slower.

Since just about every other answer recommends using try/except TypeError, where testing for exceptions is generally considered bad practice among any language, here's an implementation of iterable(obj) -> bool I've grown more fond of and use often:

For python 2's sake, I'll use a lambda just for that extra performance boost...
(in python 3 it doesn't matter what you use for defining the function, def has roughly the same speed as lambda)

iterable = lambda obj: hasattr(obj,'__iter__') or hasattr(obj,'__getitem__')

Note that this function executes faster for objects with __iter__ since it doesn't test for __getitem__.

Most iterable objects should rely on __iter__ where special-case objects fall back to __getitem__, though either is required for an object to be iterable.
(and since this is standard, it affects C objects as well)

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

  • The @@identity function returns the last identity created in the same session.
  • The scope_identity() function returns the last identity created in the same session and the same scope.
  • The ident_current(name) returns the last identity created for a specific table or view in any session.
  • The identity() function is not used to get an identity, it's used to create an identity in a select...into query.

The session is the database connection. The scope is the current query or the current stored procedure.

A situation where the scope_identity() and the @@identity functions differ, is if you have a trigger on the table. If you have a query that inserts a record, causing the trigger to insert another record somewhere, the scope_identity() function will return the identity created by the query, while the @@identity function will return the identity created by the trigger.

So, normally you would use the scope_identity() function.

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

Visual Studio window which shows list of methods

Since Visual Studio 2012, you can view the outline ( fields and methods) in the solution explorer by expanding the node corresponding to your file .

accepting HTTPS connections with self-signed certificates

I wrote small library ssl-utils-android to trust particular certificate on Android.

You can simply load any certificate by giving the filename from assets directory.

Usage:

OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());

Fully change package name including company domain

@Luch Filip's solution works well if you just want to rename the App package. In my case, I also want to rename the source package too, so as not to confuse things.

Only 2 steps are needed:

  1. Click on your source folder e.g. com.company.example > Shift + F6 (Refactor->Rename...) > Rename Package > enter your desired name.

  2. Go to your AndroidManifest.xml, click on your package name > Shift + F6 (Refactor->Rename...) > enter same name as above.

Step 1 will automatically rename your R.java folder, and you can build straight away.

Sorting a list with stream.sorted() in Java

It seems to be working fine:

List<BigDecimal> list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
System.out.println("Unsorted list: " + list);
final List<BigDecimal> sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);

Example Input/Output

Unsorted list: [24.455, 23.455, 28.455, 20.455]
Sorted list: [20.455, 23.455, 24.455, 28.455]

Are you sure you are not verifying list instead of sortedList [in above example] i.e. you are storing the result of stream() in a new List object and verifying that object?

How to print out a variable in makefile

As per the GNU Make manual and also pointed by 'bobbogo' in the below answer, you can use info / warning / error to display text.

$(error   text…)
$(warning text…)
$(info    text…)

To print variables,

$(error   VAR is $(VAR))
$(warning VAR is $(VAR))
$(info    VAR is $(VAR))

'error' would stop the make execution, after showing the error string

How to modify existing, unpushed commit messages?

git commit --amend -m "your new message"

How to format a Java string with leading zero?

public static String lpad(String str, int requiredLength, char padChar) {
    if (str.length() > requiredLength) {
        return str;
    } else {
        return new String(new char[requiredLength - str.length()]).replace('\0', padChar) + str;
    }
}

What are queues in jQuery?

The uses of jQuery .queue() and .dequeue()

Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data(). They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue(), and you remove (by calling) the functions using .dequeue().

To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay():

$.fn.delay = function( time, type ) {
  time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
  type = type || "fx";

  return this.queue( type, function() {
    var elem = this;
    setTimeout(function() {
      jQuery.dequeue( elem, type );
    }, time );
  });
};

The default queue - fx

The default queue in jQuery is fx. The default queue has some special properties that are not shared with other queues.

  1. Auto Start: When calling $(elem).queue(function(){}); the fx queue will automatically dequeue the next function and run it if the queue hasn't started.
  2. 'inprogress' sentinel: Whenever you dequeue() a function from the fx queue, it will unshift() (push into the first location of the array) the string "inprogress" - which flags that the queue is currently being run.
  3. It's the default! The fx queue is used by .animate() and all functions that call it by default.

NOTE: If you are using a custom queue, you must manually .dequeue() the functions, they will not auto start!

Retrieving/Setting the queue

You can retrieve a reference to a jQuery queue by calling .queue() without a function argument. You can use the method if you want to see how many items are in the queue. You can use push, pop, unshift, shift to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue() function.

Quick Examples:

// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop(); 
// insert it at the beginning:    
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3)); 

An animation (fx) queue example:

Run example on jsFiddle

$(function() {
    // lets do something with google maps:
    var $map = $("#map_canvas");
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map($map[0], myOptions);
    var resized = function() {
        // simple animation callback - let maps know we resized
        google.maps.event.trigger(map, 'resize');
    };

    // wait 2 seconds
    $map.delay(2000);
    // resize the div:
    $map.animate({
        width: 250,
        height: 250,
        marginLeft: 250,
        marginTop:250
    }, resized);
    // geocode something
    $map.queue(function(next) {
        // find stackoverflow's whois address:
      geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);

      function handleResponse(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var location = results[0].geometry.location;
              map.setZoom(13);
              map.setCenter(location);
              new google.maps.Marker({ map: map, position: location });
          }
          // geocoder result returned, continue with animations:
          next();
      }
    });
    // after we find stack overflow, wait 3 more seconds
    $map.delay(3000);
    // and resize the map again
    $map.animate({
        width: 500,
        height: 500,
        marginLeft:0,
        marginTop: 0
    }, resized);
});

Another custom queue example

Run example on jsFiddle

var theQueue = $({}); // jQuery on an empty object - a perfect queue holder

$.each([1,2,3],function(i, num) {
  // lets add some really simple functions to a queue:
  theQueue.queue('alerts', function(next) { 
    // show something, and if they hit "yes", run the next function.
    if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
      next();
    }
  }); 
});

// create a button to run the queue:
$("<button>", {
  text: 'Run Queue', 
  click: function() { 
    theQueue.dequeue('alerts'); 
  }
}).appendTo('body');

// create a button to show the length:
$("<button>", {
  text: 'Show Length', 
  click: function() { 
    alert(theQueue.queue('alerts').length); 
  }
}).appendTo('body');

Queueing Ajax Calls:

I developed an $.ajaxQueue() plugin that uses the $.Deferred, .queue(), and $.ajax() to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue that still works in 1.4 is posted on my answer to Sequencing Ajax Requests

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

        // and then reject the deferred
        dfd.rejectWith( ajaxOpts.context || ajaxOpts,
            [ promise, statusText, "" ] );

        return promise;
    };

    // run the actual query
    function doRequest( next ) {
        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, next );
    }

    return promise;
};

})(jQuery);

I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.

Case vs If Else If: Which is more efficient?

It seems that the compiler is better in optimizing a switch-statement than an if-statement.

The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.

Here's a small comparison:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

AlertDialog styling - how to change style (color) of title, message, etc

Here's my Code to theme the alert dialog box:

<style name="alertDialog" parent="Theme.AppCompat.Dialog.Alert">
    <item name="android:background">@color/light_button_text_color</item>
    <item name="android:textColor">@android:color/black</item>
    <item name="android:textColorPrimary">@android:color/black</item>
    <item name="android:textColorSecondary">@android:color/black</item>
    <item name="android:titleTextColor" tools:targetApi="m">@android:color/black</item>
</style>

Place this code in styles.xml. In your java apply this theme as:

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.alertDialog);

Output of the code

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

This sounds like a bad clone. You could try the following to get (possibly?) more information:

git fsck --full

CodeIgniter - return only one row?

To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:

if ($query->num_rows() > 0) {
    return $query->first_row();
}

To retrieve the first row.

Does Visual Studio Code have box select/multi-line edit?

On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.

How to use a filter in a controller?

Here's another example of using filter in an Angular controller:

$scope.ListOfPeople = [
    { PersonID: 10, FirstName: "John", LastName: "Smith", Sex: "Male" },
    { PersonID: 11, FirstName: "James", LastName: "Last", Sex: "Male" },
    { PersonID: 12, FirstName: "Mary", LastName: "Heart", Sex: "Female" },
    { PersonID: 13, FirstName: "Sandra", LastName: "Goldsmith", Sex: "Female" },
    { PersonID: 14, FirstName: "Shaun", LastName: "Sheep", Sex: "Male" },
    { PersonID: 15, FirstName: "Nicola", LastName: "Smith", Sex: "Male" }
];

$scope.ListOfWomen = $scope.ListOfPeople.filter(function (person) {
    return (person.Sex == "Female");
});

//  This will display "There are 2 women in our list."
prompt("", "There are " + $scope.ListOfWomen.length + " women in our list.");

Simple, hey ?

Passing command line arguments in Visual Studio 2010?

Visual Studio 2015:

Project => Your Application Properties. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.

enter image description here

        static void Main(string[] args)
        {
            if(args == null || args.Length == 0)
            {
                Console.WriteLine("Please specify arguments!");
            }
            else
            {
                Console.WriteLine(args[0]);     // First
                Console.WriteLine(args[1]);     // Second Argument
            }
        }

Curl not recognized as an internal or external command, operable program or batch file

Here you can find the direct download link for Curl.exe

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

link to download curl generic

Div show/hide media query

 Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { 
  #my-content{
   width:100%;
 }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { 
  #my-content{
   width:100%;
 }
 }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { 
display: none;
 }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) {
// Havent code only get for more informations 
 } 

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

Using a PHP variable in a text input value = statement

Solution

You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.

<input type="text" name="idtest" value="<?php echo $idtest; ?>" >

Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

The key parameter is: innodb_page_size

Support for 32k and 64k page sizes was added in MySQL 5.7. For both 32k and 64k page sizes, the maximum row length is approximately 16000 bytes.

The trick is that this parameter can be only changed during the INITIALIZATION of the mysql service instance, so it does not have any affect if you change this parameter after the instance is already initialized (the very first run of the instance).

innodb_page_size can only be configured prior to initializing the MySQL instance and cannot be changed afterward. If no value is specified, the instance is initialized using the default page size. See Section 14.6.1, “InnoDB Startup Configuration”.

So if you do not change this value in my.ini before initialization, the default value will be 16K, which will have row size limit of ~8K. Thats why the error comes up.

If you increase the innodb_page_size, the innodb_log_buffer_size must be also increased. Set it at least to 16M. Also if the ROW_FORMAT is set to COMPRESSED you cannot increase innodb_page_size to 32k, or 64K. It should be DYNAMIC (default in 5.7).

ROW_FORMAT=COMPRESSED is not supported when innodb_page_size is set to 32KB or 64KB. For innodb_page_size=32k, extent size is 2MB. For innodb_page_size=64k, extent size is 4MB. innodb_log_buffer_size should be set to at least 16M (the default) when using 32k or 64k page sizes.

Furthermore the innodb_buffer_pool_size should be increased from 128M to 512M at least, otherwise you will get an error on initialization of the instance (I do not have the exact error).

After this, the row size error gone.

The problem with this is that you have to create a new MySql instance, and migrate data to your new DataBase instance, from old one.

Parameters that I changed and works (after creating a new instance and initialized with the my.ini that is first modified with these settings):

innodb_page_size=64k
innodb_log_buffer_size=32M
innodb_buffer_pool_size=512M

All the settings and descriptions in which I found the solution can be found here:

https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html

Hope this helps!

Regards!