Programs & Examples On #Xmlroot

MessageBodyWriter not found for media type=application/json

To overcome this issue try the following. Worked for me.

Add following dependency in the pom.xml

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <version>2.25</version>
</dependency>

And make sure Model class contains no arg constructor

 public Student()
    {
    }

no suitable HttpMessageConverter found for response type

From a Spring point of view, none of the HttpMessageConverter instances registered with the RestTemplate can convert text/html content to a ProductList object. The method of interest is HttpMessageConverter#canRead(Class, MediaType). The implementation for all of the above returns false, including Jaxb2RootElementHttpMessageConverter.

Since no HttpMessageConverter can read your HTTP response, processing fails with an exception.

If you can control the server response, modify it to set the Content-type to application/xml, text/xml, or something matching application/*+xml.

If you don't control the server response, you'll need to write and register your own HttpMessageConverter (which can extend the Spring classes, see AbstractXmlHttpMessageConverter and its sub classes) that can read and convert text/html.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

I ran into this same problem these days and maybe some more detail might be helpful to somebody else.

I was looking some security guidelines for REST APIs and crossed a very intriguing issue with json arrays. Check the link for details, but basically, you should wrap them within an Object as we already saw in this post question.

So, instead of:

  [
    {
      "name": "order1"
    },
    {
      "name": "order2"
    }
  ]

It's advisable that we always do:

  {
    "data": [
      {
        "name": "order1"
      },
      {
        "name": "order2"
      }
    ]
  }

This is pretty straight-forward when you doing a GET, but might give you some trouble if, instead, your trying to POST/PUT the very same json.

In my case, I had more than one GET that was a List and more than one POST/PUT that would receive the very same json.

So what I end up doing was to use a very simple Wrapper object for a List:

public class Wrapper<T> {
  private List<T> data;

  public Wrapper() {}

  public Wrapper(List<T> data) {
    this.data = data;
  }
  public List<T> getData() {
    return data;
  }
  public void setData(List<T> data) {
    this.data = data;
  }
}

Serialization of my lists were made with a @ControllerAdvice:

@ControllerAdvice
public class JSONResponseWrapper implements ResponseBodyAdvice<Object> {

  @Override
  public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
  }

  @Override
  @SuppressWarnings("unchecked")
  public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    if (body instanceof List) {
      return new Wrapper<>((List<Object>) body);
    }
    else if (body instanceof Map) {
      return Collections.singletonMap("data", body);
    }  
    return body;
  }
}

So, all the Lists and Maps where wrapped over a data object as below:

  {
    "data": [
      {...}
    ]
  }

Deserialization was still default, just using de Wrapper Object:

@PostMapping("/resource")
public ResponseEntity<Void> setResources(@RequestBody Wrapper<ResourceDTO> wrappedResources) {
  List<ResourceDTO> resources = wrappedResources.getData();
  // your code here
  return ResponseEntity
           .ok()
           .build();
}

That was it! Hope it helps someone.

Note: tested with SpringBoot 1.5.5.RELEASE.

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

from Jackson 2.7.x+ there is a way to annotate the member variable itself:

 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
 private List<String> newsletters;

More info here: Jackson @JsonFormat

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

This exception can be solved by specifying a full class path.

Example:

If you are using a class named ExceptionDetails


Wrong Way of passing arguments

JAXBContext jaxbContext = JAXBContext.newInstance(ExceptionDetails.class);

Right Way of passing arguments

JAXBContext jaxbContext = JAXBContext.newInstance(com.tibco.schemas.exception.ExceptionDetails.class);

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had this issue and found that the problem was that I had not registered the JacksonFeature class:

// Create JAX-RS application.
final Application application = new ResourceConfig()
    ...
    .register(JacksonFeature.class);

Without doing this your application does not know how to convert the JSON to a java object.

https://jersey.java.net/documentation/latest/media.html#json.jackson

I can't understand why this JAXB IllegalAnnotationException is thrown

I had this same issue, I was passing a spring bean back as a ResponseBody object. When I handed back an object created by new, all was good.

Jersey Exception : SEVERE: A message body reader for Java class

just put this

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This solved my issue.

http://www.markhneedham.com/blog/2012/11/28/jersey-com-sun-jersey-api-client-clienthandlerexception-a-message-body-reader-for-java-class-and-mime-media-type-applicationjson-was-not-found/

Including following dependencies in your POM.xml and run Maven -> Update also fixed my issue.

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.19.1</version>
</dependency>
<dependency>
   <groupId>com.owlike</groupId>
   <artifactId>genson</artifactId>
   <version>0.99</version>
</dependency>

JAXB :Need Namespace Prefix to all the elements

Another way is to tell the marshaller to always use a certain prefix

marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
             @Override
            public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
                return "ns1";
            }
        });'

Jaxb, Class has two properties of the same name

just declare the member variables to private in the class you want to convert to XML. Happy coding

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

Serialize an object to XML

Extension class:

using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace MyProj.Extensions
{
    public static class XmlExtension
    {
        public static string Serialize<T>(this T value)
        {
            if (value == null) return string.Empty;

            var xmlSerializer = new XmlSerializer(typeof(T));

            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter,new XmlWriterSettings{Indent = true}))
                {
                    xmlSerializer.Serialize(xmlWriter, value);
                    return stringWriter.ToString();
                }    
            }
        }
    }
}

Usage:

Foo foo = new Foo{MyProperty="I have been serialized"};

string xml = foo.Serialize();

Just reference the namespace holding your extension method in the file you would like to use it in and it'll work (in my example it would be: using MyProj.Extensions;)

Note that if you want to make the extension method specific to only a particular class(eg., Foo), you can replace the T argument in the extension method, eg.

public static string Serialize(this Foo value){...}

JAXB Exception: Class not known to this context

Fixed it by setting the class name to the property "classesToBeBound" of the JAXB marshaller:

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
          <list>
                <value>myclass</value>
          </list>
        </property>
</bean>

Best way to store data locally in .NET (C#)

A lot of the answers in this thread attempt to overengineer the solution. If I'm correct, you just want to store user settings.

Use an .ini file or App.Config file for this.

If I'm wrong, and you are storing data that is more than just settings, use a flat text file in csv format. These are fast and easy without the overhead of XML. Folks like to poo poo these since they aren't as elegant, don't scale nicely and don't look as good on a resume, but it might be the best solution for you depending on what you need.

XML Serialize generic list of serializable objects

Below is a Util class in my project:

namespace Utils
{
    public static class SerializeUtil
    {
        public static void SerializeToFormatter<F>(object obj, string path) where F : IFormatter, new()
        {
            if (obj == null)
            {
                throw new NullReferenceException("obj Cannot be Null.");
            }

            if (obj.GetType().IsSerializable == false)
            {
                //  throw new 
            }
            IFormatter f = new F();
            SerializeToFormatter(obj, path, f);
        }

        public static T DeserializeFromFormatter<T, F>(string path) where F : IFormatter, new()
        {
            T t;
            IFormatter f = new F();
            using (FileStream fs = File.OpenRead(path))
            {
                t = (T)f.Deserialize(fs);
            }
            return t;
        }

        public static void SerializeToXML<T>(string path, object obj)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.Create(path))
            {
                xs.Serialize(fs, obj);
            }
        }

        public static T DeserializeFromXML<T>(string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.OpenRead(path))
            {
                return (T)xs.Deserialize(fs);
            }
        }

        public static T DeserializeFromXml<T>(string xml)
        {
            T result;

            var ser = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }


        private static void SerializeToFormatter(object obj, string path, IFormatter formatter)
        {
            using (FileStream fs = File.Create(path))
            {
                formatter.Serialize(fs, obj);
            }
        }
    }
}

No @XmlRootElement generated by JAXB

You can fix this issue using the binding from How to generate @XmlRootElement Classes for Base Types in XSD?.

Here is an example with Maven

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>1.3.1</version>
            <executions>
                <execution>
                    <id>xjc</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <schemaDirectory>src/main/resources/xsd</schemaDirectory>
                <packageName>com.mycompany.schemas</packageName>
                <bindingFiles>bindings.xjb</bindingFiles>
                <extension>true</extension>
            </configuration>
        </plugin>

Here is the binding.xjb file content

<?xml version="1.0"?>
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
              xmlns:xjc= "http://java.sun.com/xml/ns/jaxb/xjc"
              jxb:extensionBindingPrefixes="xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <jxb:bindings schemaLocation="path/to/myschema.xsd" node="/xs:schema">
        <jxb:globalBindings>
            <xjc:simple/>
        </jxb:globalBindings>
    </jxb:bindings>
</jxb:bindings>

Serialize Class containing Dictionary member

the Dictionary class implements ISerializable. The definition of Class Dictionary given below.

[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback  

I don't think that is the problem. refer to the below link, which says that if you are having any other data type which is not serializable then Dictionary will not be serialized. http://forums.asp.net/t/1734187.aspx?Is+Dictionary+serializable+

How to Deserialize XML document

One liner:

var object = (Cars)new XmlSerializer(typeof(Cars)).Deserialize(new StringReader(xmlString));

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

How to refresh Android listview?

If you are using SimpleCursorAdapter try calling requery() on the Cursor object.

What is the bower (and npm) version syntax?

You can also use the latest keyword to install the most recent version available:

  "dependencies": {
    "fontawesome": "latest"
  }

How do I set environment variables from Java?

// this is a dirty hack - but should be ok for a unittest.
private void setNewEnvironmentHack(Map<String, String> newenv) throws Exception
{
  Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
  Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
  theEnvironmentField.setAccessible(true);
  Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
  env.clear();
  env.putAll(newenv);
  Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
  theCaseInsensitiveEnvironmentField.setAccessible(true);
  Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
  cienv.clear();
  cienv.putAll(newenv);
}

Understanding generators in Python

It helps to make a clear distinction between the function foo, and the generator foo(n):

def foo(n):
    yield n
    yield n+1

foo is a function. foo(6) is a generator object.

The typical way to use a generator object is in a loop:

for n in foo(6):
    print(n)

The loop prints

# 6
# 7

Think of a generator as a resumable function.

yield behaves like return in the sense that values that are yielded get "returned" by the generator. Unlike return, however, the next time the generator gets asked for a value, the generator's function, foo, resumes where it left off -- after the last yield statement -- and continues to run until it hits another yield statement.

Behind the scenes, when you call bar=foo(6) the generator object bar is defined for you to have a next attribute.

You can call it yourself to retrieve values yielded from foo:

next(bar)    # Works in Python 2.6 or Python 3.x
bar.next()   # Works in Python 2.5+, but is deprecated. Use next() if possible.

When foo ends (and there are no more yielded values), calling next(bar) throws a StopInteration error.

Difference between onLoad and ng-init in angular

From angular's documentation,

ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit

onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude

The major difference between them is when used with ng-include.

<div ng-include="partialViewUrl" onload="myFunction()"></div>

In this case, myFunction is called everytime the partial view is loaded.

<div ng-include="partialViewUrl" ng-init="myFunction()"></div>

Whereas, in this case, myFunction is called only once when the parent view is loaded.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.

Here's how I'm doing it for a long time, very successfully:

  1. Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).

  2. Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that (see FileStorm link at the bottom for a good tool). The background image is usually an image we put into a hidden folder (".something") on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).

  3. Unmount the DMG again, all settings should be stored by now.

  4. Write a create DMG script, that works as follows:

    • It copies the DMG, so the original one is never touched again.
    • It mounts the copy.
    • It replaces all files with the most up to date ones (e.g. latest app after build). You can simply use mv or ditto for that on command line. Note, when you replace a file like that, the icon will stay the same, the position will stay the same, everything but the file (or directory) content stays the same (at least with ditto, which we usually use for that task). You can of course also replace the background image with another one (just make sure it has the same dimensions).
    • After replacing the files, make the script unmount the DMG copy again.
    • Finally call hdiutil to convert the writable, to a compressed (and such not writable) DMG.

This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named "Create DMG") and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).

Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a relase DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).

Regarding the initial layout of the template, FileStorm is a good tool for doing it. It is commercial, but very powerful and easy to use. The normal version is less than $20, so it is really affordable. Maybe one can automate FileStorm to create a DMG (e.g. via AppleScript), never tried that, but once you have found the perfect template DMG, it's really easy to update it for every release.

mongodb: insert if not exists

In general, using update is better in MongoDB as it will just create the document if it doesn't exist yet, though I'm not sure how to work that with your python adapter.

Second, if you only need to know whether or not that document exists, count() which returns only a number will be a better option than find_one which supposedly transfer the whole document from your MongoDB causing unnecessary traffic.

MVC4 HTTP Error 403.14 - Forbidden

If you're running IIS 8.5 on Windows 8, or Server 2012, you might find that running mvc 4/5 (.net 4.5) doesn't work in a virtual directory. If you create a local host entry in the host file to point back to your local machine and then point a new local IIS website to that folder (with the matching host header entry) you'll find it works then.

How to set environment variable for everyone under my linux system?

Amazingly, Unix and Linux do not actually have a place to set global environment variables. The best you can do is arrange for any specific shell to have a site-specific initialization.

If you put it in /etc/profile, that will take care of things for most posix-compatible shell users. This is probably "good enough" for non-critical purposes.

But anyone with a csh or tcsh shell won't see it, and I don't believe csh has a global initialization file.

What is a NoReverseMatch error, and how do I fix it?

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for 'my_url_name'

    This is the name of the url that it cannot find

  • with arguments '()' and

    These are the non-keyword arguments its providing to the url

  • keyword arguments '{}' not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.

Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.

Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you're trying to access the given name?
  • If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren't correct:

  • The value is missing or an empty string

    This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you're constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you're matching is included within the patterns tried

    If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

Add Favicon with React and Webpack

For future googlers: You can also use copy-webpack-plugin and add this to webpack's production config:

plugins: [
  new CopyWebpackPlugin({ 
    patterns: [ 
     // relative path is from src
     { from: './static/favicon.ico' }, // <- your path to favicon
    ]
 })
]

Path to Powershell.exe (v 2.0)

It is always C:\Windows\System32\WindowsPowershell\v1.0. It was left like that for backward compability is what I heard or read somewhere.

Minimum Hardware requirements for Android development

I use an i5 processor with 4Gb RAM. It works very well. I feel this is the minimum configuration required to run both eclipse and android avd simultaneously. Just an old processor with high RAM is not sufficient.

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

I may be quite late to the party, but we can create custom foldr using simple lambda calculus and curried function. Here is my implementation of foldr in python.

def foldr(func):
    def accumulator(acc):
        def listFunc(l):
            if l:
                x = l[0]
                xs = l[1:]
                return func(x)(foldr(func)(acc)(xs))
            else:
                return acc
        return listFunc
    return accumulator  


def curried_add(x):
    def inner(y):
        return x + y
    return inner

def curried_mult(x):
    def inner(y):
        return x * y
    return inner

print foldr(curried_add)(0)(range(1, 6))
print foldr(curried_mult)(1)(range(1, 6))

Even though the implementation is recursive (might be slow), it will print the values 15 and 120 respectively

Where do I find the bashrc file on Mac?

I would think you should add it to ~/.bash_profile instead of .bashrc, (creating .bash_profile if it doesn't exist.) Then you don't have to add the extra step of checking for ~/.bashrc in your .bash_profile

Are you comfortable working and editing in a terminal? Just in case, ~/ means your home directory, so if you open a new terminal window that is where you will be "located". And the dot at the front makes the file invisible to normal ls command, unless you put -a or specify the file name.

Check this answer for more detail.

Java equivalent to Explode and Implode(PHP)

I'm not familiar with PHP, but I think String.split is Java equivalent to PHP explode. As for implode, standart library does not provide such functionality. You just iterate over your array and build string using StringBuilder/StringBuffer. Or you can try excellent Google Guava Splitter and Joiner or split/join methods from Apache Commons StringUtils.

What is the difference between null=True and blank=True in Django?

You may have your answer however till this day it's difficult to judge whether to put null=True or blank=True or both to a field. I personally think it's pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.

I follow this table, from Two Scoops of Django: enter image description here

Table showing when to use null or blank for each field type

Setting the zoom level for a MKMapView

Here, I put my answer and its working for swift 4.2.

MKMapView center and zoom in

Permission denied on CopyFile in VBS

for me adding / worked at the end of location of folder. Hence, if you are copying into folder, don't forget to put /

How to install python-dateutil on Windows?

I followed several suggestions in this list without success. Finally got it installed on Windows using this method: I extracted the zip file and placed the folders under my python27 folder. In a DOS window, I navigated to the installed root folder from extracting the zip file (python-dateutil-2.6.0), then issued this command:

.\python setup.py install

Whammo-bammo it all worked.

How to get a MemoryStream from a Stream in .NET?

You will have to read in all the data from the Stream object into a byte[] buffer and then pass that into the MemoryStream via its constructor. It may be better to be more specific about the type of stream object you are using. Stream is very generic and may not implement the Length attribute, which is rather useful when reading in data.

Here's some code for you:

public MyClass(Stream inputStream) {
    byte[] inputBuffer = new byte[inputStream.Length];
    inputStream.Read(inputBuffer, 0, inputBuffer.Length);

    _ms = new MemoryStream(inputBuffer);
}

If the Stream object doesn't implement the Length attribute, you will have to implement something like this:

public MyClass(Stream inputStream) {
    MemoryStream outputStream = new MemoryStream();

    byte[] inputBuffer = new byte[65535];
    int readAmount;
    while((readAmount = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
        outputStream.Write(inputBuffer, 0, readAmount);

    _ms = outputStream;
}

ASP.NET email validator regex

Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator

How-to turn off all SSL checks for postman for a specific site

enter image description here

This steps are used in spring boot with self signed ssl certificate implementation

if SSL turns off then HTTPS call will be worked as expected.

https://localhost:8443/test/hello

These are the steps we have to follow,

  1. Generate self signed ssl certificate
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

after key generation has done then copy that file in to the resource foder in your project

  1. add key store properties in applicaiton.properties
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
  1. change your postman ssl verification settings to turn OFF

now verify the url: https://localhost:8443/test/hello

Check orientation on Android phone

Check screen orientation in runtime.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();

    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();        
    }
}

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

Convert string with comma to integer

How about this?

 "1,112".delete(',').to_i

How can I hide select options with JavaScript? (Cross browser)

Here's an option that:

  • Works in all browsers
  • Preserves current selection when filtering
  • Preserves order of items when removing / restoring
  • No dirty hacks / invalid HTML

`

$('select').each(function(){
    var $select = $(this);
    $select.data('options', $select.find('option'));
});

function filter($select, search) {
    var $prev = null;
    var $options = $select.data('options');
    search = search.trim().toLowerCase();
    $options.each(function(){
        var $option = $(this);
        var optionText = $option.text();
        if(search == "" || optionText.indexOf(search) >= 0) {
            if ($option.parent().length) {
                    $prev = $option;
                return;
            }
            if (!$prev) $select.prepend($option);
            else $prev.after($option);
            $prev = $option;
        }
        else {
              $option.remove();
        }
    });
}

`

JSFiddle: https://jsfiddle.net/derrh5tr/

Python decorators in classes

import functools


class Example:

    def wrapper(func):
        @functools.wraps(func)
        def wrap(self, *args, **kwargs):
            print("inside wrap")
            return func(self, *args, **kwargs)
        return wrap

    @wrapper
    def method(self):
        print("METHOD")

    wrapper = staticmethod(wrapper)


e = Example()
e.method()

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

Nesting CSS classes

Try this...

Give the element an ID, and also a class Name. Then you can nest the #IDName.className in your CSS.

Here's a better explanation https://css-tricks.com/multiple-class-id-selectors/

MongoDB: How to update multiple documents with a single command?

For Mongo version > 2.2, add a field multi and set it to true

db.Collection.update({query}, 
                 {$set: {field1: "f1", field2: "f2"}},
                 {multi: true })

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

iterating and filtering two lists using java 8

If you stream the first list and use a filter based on contains within the second...

list1.stream()
    .filter(item -> !list2.contains(item))

The next question is what code you'll add to the end of this streaming operation to further process the results... over to you.

Also, list.contains is quite slow, so you would be better with sets.

But then if you're using sets, you might find some easier operations to handle this, like removeAll

Set list1 = ...;
Set list2 = ...;
Set target = new Set();
target.addAll(list1);
target.removeAll(list2);

Given we don't know how you're going to use this, it's not really possible to advise which approach to take.

How do I request and receive user input in a .bat and use it to run a certain program?

Add quotation marks (" ") around the %INPUT% so it looks like this:

If "%INPUT%" == "y" goto yes
If "%INPUT%" == "n" goto no
If "%INPUT%" == "Y" goto yes
If "%INPUT%" == "N" goto no

The developers of this app have not set up this app properly for Facebook Login?

I had the same problem but now here is how I solved it
Go to https://developers.facebook.com/
• Click on the Apps menu on the top bar.
• Select the respective app from the drop down.
• Click Settings from the table in the left side of the page
• Then under the Contact Email type in your email you would like to use
• Then click save settings button
• Go to 'Status & Review' from the table in the left side of the page.
• Do you want to make this app and all its live features available to the general public? - Select switch to set YES/NO value.

How to have jQuery restrict file types on upload?

No plugin necessary for just this task. Cobbled this together from a couple other scripts:

$('INPUT[type="file"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
            $('#uploadButton').attr('disabled', false);
            break;
        default:
            alert('This is not an allowed file type.');
            this.value = '';
    }
});

The trick here is to set the upload button to disabled unless and until a valid file type is selected.

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

You don't mention if it has to be batch only, but if you can use ROBOCOPY, try this:

ROBOCOPY C:\Source C:\Destination data.zip info.txt /E

EDIT: Changed the /S parameter to /E to include empty folders.

How to change DataTable columns order

If you have more than 2-3 columns, SetOrdinal is not the way to go. A DataView's ToTable method accepts a parameter array of column names. Order your columns there:

DataView dataView = dataTable.DefaultView;
dataTable = dataView.ToTable(true, "Qty", "Unit", "Id");

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Project Links do not work on Wamp Server

You can follow all steps by @RiggsFolly thats is really good answer, If you do not want to create virtual host and want to use like previous localhost/example/ or something like that you can use answer by @Arunu

But if you still face problem please use this method,

  1. Locate your wamp folder (Eg. c:/Wamp/) where you have installed
  2. Goto Wamp/www/
  3. Open index.php file
  4. find this code $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://' : '').$file.'">'.$file.'</a></li>';
  5. modify it add localhost after http:// $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://localhost' : '').$file.'">'.$file.'</a></li>';
  6. Restart wamp server
  7. open localhost see the updated links

Hope you got your url like previous version of wamp server.

Change limit for "Mysql Row size too large"

I am using MySQL 5.6 on AWS RDS. I updated following in parameter group.

innodb_file_per_table=1
innodb_file_format = Barracuda

I had to reboot DB instance for parameter group changes to be in effect.

Also, ROW_FORMAT=COMPRESSED was not supported. I used DYNAMIC as below and it worked fine.

ALTER TABLE nombre_tabla ENGINE=InnoDB ROW_FORMAT=DYNAMIC KEY_BLOCK_SIZE=8

curl error 18 - transfer closed with outstanding read data remaining

Seeing this error during the use of Guzzle as well. The following header fixed it for me:

'headers' => [
    'accept-encoding' => 'gzip, deflate',
],

I issued the request with Postman which gave me a complete response and no error. Then I started adding the headers that Postman sends to the Guzzle request and this was the one that fixed it.

Where does Chrome store cookies?

For Google chrome Version 56.0.2924.87 (Latest Release) cookies are found inside profile1 folder.

If you browse that you can find variety of information.

There is a separate file called "Cookies". Also the Cache folder is inside this folder.

Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Profile 1

Remember to replace user_name.

For Version 61.0.3163.100
Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Default

Inside this folder there is Cookies file and Cache folder.

How do I make XAML DataGridColumns fill the entire DataGrid?

set ONE column's width to any value, i.e. width="*"

typecast string to integer - Postgres

Common issue

Naively type casting any string into an integer like so

SELECT ''::integer

Often results to the famous error:

Query failed: ERROR: invalid input syntax for integer: ""

Problem

PostgreSQL has no pre-defined function for safely type casting any string into an integer.

Solution

Create a user-defined function inspired by PHP's intval() function.

CREATE FUNCTION intval(character varying) RETURNS integer AS $$

SELECT
CASE
    WHEN length(btrim(regexp_replace($1, '[^0-9]', '','g')))>0 THEN btrim(regexp_replace($1, '[^0-9]', '','g'))::integer
    ELSE 0
END AS intval;

$$
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;

Usage

/* Example 1 */
SELECT intval('9000');
-- output: 9000

/* Example 2 */
SELECT intval('9gag');
-- output: 9

/* Example 3 */
SELECT intval('the quick brown fox jumps over the lazy dog');
-- output: 0

External resource not being loaded by AngularJs

If anybody is looking for a TypeScript solution:

.ts file (change variables where applicable):

module App.Filters {

    export class trustedResource {

        static $inject:string[] = ['$sce'];

        static filter($sce:ng.ISCEService) {
            return (value) => {
                return $sce.trustAsResourceUrl(value)
            };
        }
    }
}
filters.filter('trustedResource', App.Filters.trusted.filter);

Html:

<video controls ng-if="HeaderVideoUrl != null">
  <source ng-src="{{HeaderVideoUrl | trustedResource}}" type="video/mp4"/>
</video>

how to append a css class to an element by javascript?

Adding class using element's classList property:

element.classList.add('my-class-name');

Removing:

element.classList.remove('my-class-name');

How can I wait for a thread to finish with .NET?

I took a little different approach. There is a counter option in previous answers, and I just applied it a bit differently. I was spinning off numerous threads and incremented a counter and decremented a counter as a thread started and stopped. Then in the main method I wanted to pause and wait for threads to complete I did.

while (threadCounter > 0)
{
    Thread.Sleep(500); // Make it pause for half second so that we don’t spin the CPU out of control.
}

This is documented in my blog post: http://www.adamthings.com/post/2012/07/11/ensure-threads-have-finished-before-method-continues-in-c/

Java: Rotating Images

This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);

Send raw ZPL to Zebra printer via USB

I spent 8 hours to do that. It is simple...

You shoud have a code like that:

private const int GENERIC_WRITE = 0x40000000;

//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;

Change that variable content from 3 (open file already exist) to 1 (create a new file). It'll work at Windows 7 and XP.

TypeError: Image data can not convert to float

This question comes up first in the Google search for this type error, but does not have a general answer about the cause of the error. The poster's unique problem was the use of an inappropriate object type as the main argument for plt.imshow(). A more general answer is that plt.imshow() wants an array of floats and if you don't specify a float, numpy, pandas, or whatever else, might infer a different data type somewhere along the line. You can avoid this by specifying a float for the dtype argument is the constructor of the object.

See the Numpy documentation here.

See the Pandas documentation here

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Generate random password string with requirements in javascript

My Crypto based take on the problem. Using ES6 and omitting any browser feature checks. Any comments on security or performance?

const generatePassword = (
  passwordLength = 12,
  passwordChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
) =>
  [...window.crypto.getRandomValues(new Uint32Array(passwordLength))]
    .map(x => passwordChars[x % passwordChars.length])
    .join('');

How do multiple clients connect simultaneously to one port, say 80, on a server?

Normally, for every connecting client the server forks a child process that communicates with the client (TCP). The parent server hands off to the child process an established socket that communicates back to the client.

When you send the data to a socket from your child server, the TCP stack in the OS creates a packet going back to the client and sets the "from port" to 80.

How do I add FTP support to Eclipse?

Eclipse natively supports FTP and SSH. Aptana is not necessary.

Native FTP and SSH support in Eclipse is in the "Remote System Explorer End-User Runtime" Plugin.

Install it through Eclipse itself. These instructions may vary slightly with your version of Eclipse:

  1. Go to 'Help' -> 'Install New Software' (in older Eclipses, this is called something a bit different)
  2. In the 'Work with:' drop-down, select your version's plugin release site. Example: for Kepler, this is
    Kepler - http://download.eclipse.org/releases/kepler
  3. In the filter field, type 'remote'.
  4. Check the box next to 'Remote System Explorer End-User Runtime'
  5. Click 'Next', and accept the terms. It should now download and install.
  6. After install, Eclipse may want to restart.

Using it, in Eclipse:

  1. Window -> Open Perspective -> (perhaps select 'Other') -> Remote System Explorer
  2. File -> New -> Other -> Remote System Explorer (folder) -> Connection (or type Connection into the filter field)
  3. Choose FTP from the 'Select Remote System Type' panel.
  4. Fill in your FTP host info in the next panel (username and password come later).
  5. In the Remote Systems panel, right-click the hostname and click 'connect'.
  6. Enter username + password and you're good!
  7. Well, not exactly 'good'. The RSE system is fairly unusual, but you're connected.
  8. And you're one smart cookie! You'll figure out the rest.

Edit: To change the default port, follow the instructions on this page: http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/

Why does the JFrame setSize() method not set the size correctly?

I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.

Using this

setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));

But this always work in any size:

setSize(width + 14, height + 7);

If you don't want the border to border, and only want the white area, here:

setSize(width + 16, height + 39);

Also this only works on Windows 10, for MacOS users, use @ben's answer.

Execute a terminal command from a Cocoa app

If the Terminal command requires Administrator Privilege (aka sudo), use AuthorizationExecuteWithPrivileges instead. The following will create a file named "com.stackoverflow.test" is the root directory "/System/Library/Caches".

AuthorizationRef authorizationRef;
FILE *pipe = NULL;
OSStatus err = AuthorizationCreate(nil,
                                   kAuthorizationEmptyEnvironment,
                                   kAuthorizationFlagDefaults,
                                   &authorizationRef);

char *command= "/usr/bin/touch";
char *args[] = {"/System/Library/Caches/com.stackoverflow.test", nil};

err = AuthorizationExecuteWithPrivileges(authorizationRef,
                                         command,
                                         kAuthorizationFlagDefaults,
                                         args,
                                         &pipe); 

How to implement history.back() in angular.js

Angular routes watch the browser's location, so simply using window.history.back() on clicking something would work.

HTML:

<div class="nav-header" ng-click="doTheBack()">Reverse!</div>

JS:

$scope.doTheBack = function() {
  window.history.back();
};

I usually create a global function called '$back' on my app controller, which I usually put on the body tag.

angular.module('myApp').controller('AppCtrl', ['$scope', function($scope) {
  $scope.$back = function() { 
    window.history.back();
  };
}]);

Then anywhere in my app I can just do <a ng-click="$back()">Back</a>

(If you want it to be more testable, inject the $window service into your controller and use $window.history.back()).

How to kill a child process after a given timeout in Bash?

Here's the third answer I've submitted here. This one handles signal interrupts and cleans up background processes when SIGINT is received. It uses the $BASHPID and exec trick used in the top answer to get the PID of a process (in this case $$ in a sh invocation). It uses a FIFO to communicate with a subshell that is responsible for killing and cleanup. (This is like the pipe in my second answer, but having a named pipe means that the signal handler can write into it too.)

run_with_timeout ()
{
  t=$1 ; shift

  trap cleanup 2

  F=$$.fifo ; rm -f $F ; mkfifo $F

  # first, run main process in background
  "$@" & pid=$!

  # sleeper process to time out
  ( sh -c "echo \$\$ >$F ; exec sleep $t" ; echo timeout >$F ) &
  read sleeper <$F

  # control shell. read from fifo.
  # final input is "finished".  after that
  # we clean up.  we can get a timeout or a
  # signal first.
  ( exec 0<$F
    while : ; do
      read input
      case $input in
        finished)
          test $sleeper != 0 && kill $sleeper
          rm -f $F
          exit 0
          ;;
        timeout)
          test $pid != 0 && kill $pid
          sleeper=0
          ;;
        signal)
          test $pid != 0 && kill $pid
          ;;
      esac
    done
  ) &

  # wait for process to end
  wait $pid
  status=$?
  echo finished >$F
  return $status
}

cleanup ()
{
  echo signal >$$.fifo
}

I've tried to avoid race conditions as far as I can. However, one source of error I couldn't remove is when the process ends near the same time as the timeout. For example, run_with_timeout 2 sleep 2 or run_with_timeout 0 sleep 0. For me, the latter gives an error:

timeout.sh: line 250: kill: (23248) - No such process

as it is trying to kill a process that has already exited by itself.

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

typesafe select onChange event using reactjs and typescript

JSX:

<select value={ this.state.foo } onChange={this.handleFooChange}>
    <option value="A">A</option>
    <option value="B">B</option>
</select>

TypeScript:

private handleFooChange = (event: React.FormEvent<HTMLSelectElement>) => {
    const element = event.target as HTMLSelectElement;
    this.setState({ foo: element.value });
}

How do I use WPF bindings with RelativeSource?

Don't forget TemplatedParent:

<Binding RelativeSource="{RelativeSource TemplatedParent}"/>

or

{Binding RelativeSource={RelativeSource TemplatedParent}}

how to get the last character of a string?

If you have or are already using lodash, use last instead:

_.last(str);

Not only is it more concise and obvious than the vanilla JS, it also safer since it avoids Uncaught TypeError: Cannot read property X of undefined when the input is null or undefined so you don't need to check this beforehand:

// Will throws Uncaught TypeError if str is null or undefined
str.slice(-1); // 
str.charAt(str.length -1);

// Returns undefined when str is null or undefined
_.last(str);

node.js - request - How to "emitter.setMaxListeners()"?

Try to use:

require('events').EventEmitter.defaultMaxListeners = Infinity; 

MySQL: How to add one day to datetime field in query

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");

Or, simplier:

date("Y-m-d H:i:s", time()+((60*60)*24));

C# 30 Days From Todays Date

@Ed courtenay, @James, I have one stupid question. How to keep user away from this file?(File containing expiry date). If the user has installation rights, then obviously user has access to view files also. Changing the extension of file wont help. So, how to keep this file safe and away from users hands?

How to disable keypad popup when on edittext?

Use This to enable and disable EditText....

InputMethodManager imm;

imm = (InputMethodManager)
getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);

if (isETEnable == true) {

    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    ivWalllet.setImageResource(R.drawable.checkbox_yes);
    etWalletAmount.setEnabled(true);
    etWalletAmount.requestFocus();
    isETEnable = false;
    } 
else {

    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
    ivWalllet.setImageResource(R.drawable.checkbox_unchecked);
    etWalletAmount.setEnabled(false);
    isETEnable = true;
    }

Convert True/False value read from file to boolean

you can use distutils.util.strtobool

>>> from distutils.util import strtobool

>>> strtobool('True')
1
>>> strtobool('False')
0

True values are y, yes, t, true, on and 1; False values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

How do I check if a property exists on a dynamic anonymous type in c#?

This is working for me-:

  public static bool IsPropertyExist(dynamic dynamicObj, string property)
       {
           try
           {
               var value=dynamicObj[property].Value;
               return true;
           }
           catch (RuntimeBinderException)
           {

               return false;
           }

       }

Bulk create model objects in django

Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.

I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.

http://djangosnippets.org/snippets/446/

How to make CSS3 rounded corners hide overflow in Chrome/Opera

Add a z-index to your border-radius'd item, and it will mask the things inside of it.

Centering Bootstrap input fields

For bootstrap 4 use offset-4, see below.

<div class="mx-auto">        
        <form class="mx-auto" action="/campgrounds" method="POST">
            <div class="form-group row">                
                <div class="col-sm-4 offset-4">
                    <input class="form-control" type="text" name="name" placeholder="name">
                </div>
            </div>
            <div class="form-group row">               
                <div class="col-sm-4 offset-4">
                    <input class="form-control" type="text" name="picture" placeholder="image url">
                </div>
            </div>
            <div class="form-group row">
                    <div class="col-sm-4 offset-4">
                        <input class="form-control" type="text" name="description" placeholder="description">
                    </div>
                </div>
            <button class="btn btn-primary" type="submit">Submit!</button>
            <a class="btn btn-secondary"  href="/campgrounds">Go Back</a>
        </form>      
    </div>

What is a "cache-friendly" code?

Be aware that caches do not just cache continuous memory. They have multiple lines (at least 4) so discontinous and overlapping memory can often be stored just as efficiently.

What is missing from all the above examples is measured benchmarks. There are many myths about performance. Unless you measure it you do not know. Do not complicate your code unless you have a measured improvement.

Cannot find java. Please use the --jdkhome switch

In my case, I had installed *ahem* OpenJDK, but the bin folder was full of symlinks to the bundled JRE and the actual JDK was nowhere to be found.

When I see a directory structure with bin and jre subdirectories I expect this to be the JDK installation, because JRE installations on Windows looked different. But in this case it was the JRE installation as found out by apt search. After installing openjdk-8-jre the simlinks were replaced and the directory structure otherwise stayed the same.

Error: macro names must be identifiers using #ifdef 0

The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit:

identifier:
    identifier-nondigit
    identifier identifier-nondigit
    identifier digit
identifier-nondigit:
    nondigit
    universal-character-name
    other implementation-defined characters>
nondigit: one of
    _ a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
digit: one of
    0 1 2 3 4 5 6 7 8 9

The correct form for using the pre-processor to block out code is:

#if 0
: : :
#endif

You can also use:

#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif

but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED or DONOTCOMPILE which others may also use. To be safe, the #if option should be preferred.

Convert a python UTC datetime to a local datetime using only python standard library?

This is a terrible way to do it but it avoids creating a definition. It fulfills the requirement to stick with the basic Python3 library.

# Adjust from UST to Eastern Standard Time (dynamic)
# df.my_localtime should already be in datetime format, so just in case
df['my_localtime'] = pd.to_datetime.df['my_localtime']

df['my_localtime'] = df['my_localtime'].dt.tz_localize('UTC').dt.tz_convert('America/New_York').astype(str)
df['my_localtime'] = pd.to_datetime(df.my_localtime.str[:-6])

How can I select an element by name with jQuery?

You can get the name value from an input field using name element in jQuery by:

_x000D_
_x000D_
var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD_x000D_
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ _x000D_
console.log(firstname);_x000D_
console.log(lastname);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name="form1" id="form1">_x000D_
  <input type="text" name="firstname" value="ABCD"/>_x000D_
  <input type="text" name="lastname" value="XYZ"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Change tab bar item selected color in a storyboard

Add this code in your app delegate -did_finish_launching_with_options function

UITabBar.appearance().tintColor = UIColor( red: CGFloat(255/255.0), green: CGFloat(99/255.0), blue: CGFloat(95/255.0), alpha: CGFloat(1.0) )

put the RGB of the required color

How to validate a file upload field using Javascript/jquery

My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.

Try this:

<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">

function validate_fileupload(fileName)
{
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}

How to get to Model or Viewbag Variables in a Script Tag

Use single quotation marks ('):

var val = '@ViewBag.ForSection';
alert(val);

The provider is not compatible with the version of Oracle client

i have the same problem but in my case i can't just copy the dlls into the bin folder, then i only 'rebind' the assembly version.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>    
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89B483F429C47342" culture="neutral"/>
        <bindingRedirect oldVersion="2.112.2.0" newVersion="2.112.1.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Return content with IHttpActionResult for non-OK response

In ASP.NET Web API 2, you can wrap any ResponseMessage in a ResponseMessageResult:

public IHttpActionResult Get()
{
   HttpResponseMessage responseMessage = ...
   return new ResponseMessageResult(responseMessage);
}

In some cases this may be the simplest way to get the desired result, although generally it might be preferable to use the various results in System.Web.Http.Results.

How do you change the server header returned by nginx?

Like Apache, this is a quick edit to the source and recompile. From Calomel.org:

The Server: string is the header which is sent back to the client to tell them what type of http server you are running and possibly what version. This string is used by places like Alexia and Netcraft to collect statistics about how many and of what type of web server are live on the Internet. To support the author and statistics for Nginx we recommend keeping this string as is. But, for security you may not want people to know what you are running and you can change this in the source code. Edit the source file src/http/ngx_http_header_filter_module.c at look at lines 48 and 49. You can change the String to anything you want.

## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)
static char ngx_http_server_string[] = "Server: MyDomain.com" CRLF;
static char ngx_http_server_full_string[] = "Server: MyDomain.com" CRLF;

March 2011 edit: Props to Flavius below for pointing out a new option, replacing Nginx's standard HttpHeadersModule with the forked HttpHeadersMoreModule. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.

Upload folder with subfolders using S3 and the AWS console

I ended up here when trying to figure this out. With the version that's up there right now you can drag and drop a folder into it and it works, even though it doesn't allow you to select a folder when you open the upload dialogue.

What is the scope of variables in JavaScript?

Here's an example:

<script>

var globalVariable = 7; //==window.globalVariable

function aGlobal( param ) { //==window.aGlobal(); 
                            //param is only accessible in this function
  var scopedToFunction = {
    //can't be accessed outside of this function

    nested : 3 //accessible by: scopedToFunction.nested
  };

  anotherGlobal = {
    //global because there's no `var`
  }; 

}

</script>

You'll want to investigate closures, and how to use them to make private members.

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

The DLL you're looking for that contains that namespace is

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

Note that unit testing cannot be used in Visual Studio Express.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

A simple one liner:

$("#text").val( $("#text").val().replace(".", ":") );

How to keep the spaces at the end and/or at the beginning of a String?

If you need the space for the purpose of later concatenating it with other strings, then you can use the string formatting approach of adding arguments to your string definition:

<string name="error_">Error: %s</string>

Then for format the string (eg if you have an error returned by the server, otherwise use getString(R.string.string_resource_example)):

String message = context.getString(R.string.error_, "Server error message here")

Which results in:

Error: Server error message here

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

How do I change tab size in Vim?

UPDATE

If you are working in a particular project I highly recommend using editorconfig.

It lets you define an .editorconfig file at the root of your repository defining the indentation you want to use for each file type across your repository.

For example:

root = true

[*.css]
charset = utf-8
indent_style = space
indent_size = 4

[*.js]
charset = utf-8
indent_style = space
indent_size = 2

There is a vim plugin that automatically configures vim according to the config file for file you open.

On top of that the .editorconfig file is automatically supported on many other IDEs and editors so it is the best option for collaborating between users with different environments.

ORIGINAL ANSWER

If you need to change sizes often and you don't want to bind this to a specific file type you can have predefined commands on your .vimrc file to quickly switch preferences:

nmap <leader>t :set expandtab tabstop=4 shiftwidth=4 softtabstop=4<CR>
nmap <leader>m :set expandtab tabstop=2 shiftwidth=2 softtabstop=2<CR>

This maps two different sets of sizes to keys \t and \m. You can rebind this to whatever keys you want.

How to stop/shut down an elasticsearch node?

The Head plugin for Elasticsearch provides a great web based front end for Elasticsearch administration, including shutting down nodes. It can run any Elasticsearch commands as well.

Mac SQLite editor

Take a look on a free tool - Valentina Studio. Amazing product! IMO this is the best manager for SQLite for all platforms:

Also it works on Mac OS X, you can install Valentina Studio (FREE) directly from Mac App Store:

Soft keyboard open and close listener in an activity in Android

private boolean isKeyboardShown = false;
private int prevContentHeight = 0;
private ViewGroup contentLayout;

private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener =
        new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        int contentHeight = contentLayout.getHeight();
        int rootViewHeight = contentLayout.getRootView().getHeight();

        if (contentHeight > 0) {

            if (!isKeyboardShown) {
                if (contentHeight < prevContentHeight) {
                    isKeyboardShown = true;
                    onShowKeyboard(rootViewHeight - contentHeight);
                }
            } else {
                if (contentHeight > prevContentHeight) {
                    isKeyboardShown = false;
                    onHideKeyboard();
                }
            }

            prevContentHeight = contentHeight;
        }
    }
};

I've modified the Jaap's accepted answer a bit. But in my case, there are few assumptions such as android:windowSoftInputMode=adjustResize and the keyboard does not show up at the beginning when the app starts. And also, I assume that the screen in regard matches the parent's height.

contentHeight > 0 this check provides me to know if the regarding screen is hidden or shown to apply keyboard event listening for this specific screen. Also I pass the layout view of the regarding screen in attachKeyboardListeners(<your layout view here>) in my main activity's onCreate() method. Every time when the height of the regarding screen changes, I save it to prevContentHeight variable to check later whether the keyboard is shown or hidden.

For me, so far it's been worked pretty well. I hope that it works for others too.

Execute a shell script in current shell with sudo permission

What you are trying to do is impossible; your current shell is running under your regular user ID (i.e. without root the access sudo would give you), and there is no way to grant it root access. What sudo does is create a new *sub*process that runs as root. The subprocess could be just a regular program (e.g. sudo cp ... runs the cp program in a root process) or it could be a root subshell, but it cannot be the current shell.

(It's actually even more impossible than that, because the sudo command itself is executed as a subprocess of the current shell -- meaning that in a sense it's already too late for it to do anything in the "current shell", because that's not where it executes.)

How to use boolean 'and' in Python

Try this:

i = 5
ii = 10
if i == 5 and ii == 10:
      print "i is 5 and ii is 10"

Edit: Oh, and you dont need that semicolon on the last line (edit to remove it from my code).

failed to find target with hash string android-23

Following these reccomended directions seemed to work:

Hint: Open the SDK manager by running: /path/to/android/tools/android

You will require: 1. "SDK Platform" for android-23 2. "Android SDK Platform-tools (latest) 3. "Android SDK Build-tools" (latest)

Is there a CSS selector by class prefix?

CSS Attribute selectors will allow you to check attributes for a string. (in this case - a class-name)

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

(looks like it's actually at 'recommendation' status for 2.1 and 3)


Here's an outline of how I *think it works:

  • [ ] : is the container for complex selectors if you will...
  • class : 'class' is the attribute you are looking at in this case.
  • * : modifier(if any): in this case - "wildcard" indicates you're looking for ANY match.
  • test- : the value (assuming there is one) of the attribute - that contains the string "test-" (which could be anything)

So, for example:

[class*='test-'] {
  color: red;
}

You could be more specific if you have good reason, with the element too

ul[class*='test-'] > li { ... }

I've tried to find edge cases, but I see no need to use a combination of ^ and * - as * gets everything...

example: http://codepen.io/sheriffderek/pen/MaaBwp

http://caniuse.com/#feat=css-sel2

Everything above IE6 will happily obey. : )

note that:

[class] { ... }

Will select anything with a class...

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

The next solution helped me. Add to build.gradle

 compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Font-awesome, input type 'submit'

use button type="submit" instead of input

<button type="submit" class="btn btn-success">
    <i class="fa fa-arrow-circle-right fa-lg"></i> Next
</button>

for Font Awesome 3.2.0 use

<button type="submit" class="btn btn-success">
    <i class="icon-circle-arrow-right icon-large"></i> Next
</button>

Cache busting via params

Two questions: Will this effectively break the cache?

Yes. Even Stack Overflow use this method, although I remember that they (with their millions of visitors per day and zillions of different client and proxy versions and configurations) have had some freak edge cases where even this was not enough to break the cache. But the general assumption is that this will work, and is a suitable method to break caching on clients.

Will the param cause the browser to then never cache the response from that url since the param indicates that this is dynamic content?

No. The parameter will not change the caching policy; the caching headers sent by the server still apply, and if it doesn't send any, the browser's defaults.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

You can create a setTimeout loop using recursion:

function timeout() {
    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        timeout();
    }, 1000);
}

The problem with setInterval() and setTimeout() is that there is no guarantee your code will run in the specified time. By using setTimeout() and calling it recursively, you're ensuring that all previous operations inside the timeout are complete before the next iteration of the code begins.

How to test if list element exists?

The best way to check for named elements is to use exist(), however the above answers are not using the function properly. You need to use the where argument to check for the variable within the list.

foo <- list(a=42, b=NULL)

exists('a', where=foo) #TRUE
exists('b', where=foo) #TRUE
exists('c', where=foo) #FALSE

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

Reference : https://support.microsoft.com/en-in/help/2028526/building-an-asp-net-project-in-visual-studio-results-in-compiler-error

When building an ASP.NET project using Visual Studio, you may randomly see an error message similar to the following:

Compiler Error Message: CS0433: The type 'ASP.summary_common_controls_notes_ascx' exists in both 'c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\Book_Details\abc12345\def8910\App_Web_msftx123.dll' and 'c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\Book_Details\abc12345\def8910\App_Web_msfty456.dll'

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Source Error: Line 100: Line 101:
New Notes Line 102:
Line 103:
1450 Line 104:

Summary.

Source File: d:\http\post\publisher\default.aspx Line: 102

Common scenarios where this error can occur are discussed below

Scenario 1

Description: A common cause is when there are two assemblies in the same web application bin folder containing two class definitions but that have the same class name. This can happen if more than one Default.aspx was compiled into a single assembly. Commonly, this occurs when the Master page (Default.master) and the Default ASPX page (Default.aspx) both declare a _Default class. Solution: Change the class name of the master page (from _Default in most cases) and rebuild the project. It is important to resolve any naming conflict between classes.

Scenario 2

Description: The Reference Paths in Visual Studio is used to specify the folder path for assembly references used by the project. It is possible that the path contains an assembly that contains the same class name. It may be that there are multiple References added to the same assembly (possibly different version or name) causing a naming conflict.
Solution: Remove the old version reference. To do so, in Visual Studio right-click your web site and check the "References" in the properties.

Scenario 3

Description: By default, when an ASP.NET Web application is compiled the compiled code is placed in the Temporary ASP.NET Files folder. By default the access permissions are given to the ASP.NET local user account, which has the high-trust permissions needed to access compiled code. It is possible that there were some changes in the default permissions causing versioning conflicts. Another possibility would be that anti-virus software could be locking an assembly inadvertently. Solution: Clear the Temporary ASP.NET Files Folder of all contents.

Scenario 4

Description: When the batch attribute in the web.config is set to True it eliminates the delay caused by the compilation required when you access a file for the first time. ASP.NET precompiles all the un-compiled files in a batch mode, which causes delays the first time the files are compiled. Turning off batch compilation may expose masked compilation errors that may exist in the application but are not reported. However more importantly for this issue it tells ASP.NET to dynamically compile individual .aspx/.ascx files into separate assemblies instead of into a single assembly. Solution: Set batch=false in the section in web.config. This should be considered a temporary solution as setting batch=false in the compilation section has a significant performance impact on build times for the application in Visual Studio.

Scenario 5

Description: Modifying the web.config file for an ASP.NET application or changing a file in the bin folder (such as adding, deleting, or renaming) causes the AppDomain to restart. When this occurs all session state is lost and cached items are removed from the cache as the website restarts. It is possible that the problem is caused by an inconsistent state in the web application. Solution: Trigger an AppDomain restart by touching (editing) the web.config file.

Scenario 6

Description: You can store source code in the App_Code folder, and it will be automatically compiled at run time. The resulting assembly is accessible to any other code in the Web application. The App_Code folder therefore works much like the Bin folder, except that you can store source code in it instead of compiled code. The class will be recompiled when there is a change in the source file. If there is conflict due to an outdated assembly then forcing a recompile may resolve the problem. Solution: Touch a file in the Bin or App_Code folders to trigger a full recompilation.

Converting ISO 8601-compliant String to java.util.Date

Starting from Java 8, there is a completely new officially supported way to do this:

    String s = "2020-02-13T18:51:09.840Z";
    TemporalAccessor ta = DateTimeFormatter.ISO_INSTANT.parse(s);
    Instant i = Instant.from(ta);
    Date d = Date.from(i);

setTimeout / clearTimeout problems

That's because timer is a local variable to your function.

Try creating it outside of the function.

How to vertically align <li> elements in <ul>?

You can use flexbox for this.

ul {
    display: flex;
    align-items: center;
}

A detailed explanation of how to use flexbox can be found here.

What is the difference between function and procedure in PL/SQL?

In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.

Excel formula to remove space between words in a cell

Suppose the data is in the B column, write in the C column the formula:

=SUBSTITUTE(B1," ","")

Copy&Paste the formula in the whole C column.

edit: using commas or semicolons as parameters separator depends on your regional settings (I have to use the semicolons). This is weird I think. Thanks to @tocallaghan and @pablete for pointing this out.

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.github.com")
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")
                .build();

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
        httpHeaders.stream().forEach(System.out::println);

        // close client and response
    }
}

how to set background image in submit button?

i do it like this cover button and the middle image that

<button><img src="foldername/imagename" width="30px" height= "30px"></button>

Batch file include external file for variables

While trying to use the method with excutable configuration I noticed that it may work or may NOT work depending on where in the script is located the call:

call config.cmd

I know it doesn't make any sens, but for me it's a fact. When "call config.cmd" is located at the top of the script, it works, but if further in the script it doesn't.

By doesn't work, I mean the variable are not set un the calling script.

Very very strange !!!!

.gitignore all the .DS_Store files in every folder and subfolder

If .DS_Store was never added to your git repository, simply add it to your .gitignore file.

If you don't have one, create a file called

.gitignore

In the root directory of your app and simply write

**/.DS_Store

In it. This will never allow the .DS_Store file to sneak in your git.

But, if it's already there, write in your terminal:

find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

then commit and push the changes to remove the .DS_Store from your remote repo:

git commit -m "Remove .DS_Store from everywhere"

git push origin master

And now add .DS_Store to your .gitignore file, and then again commit and push with the 2 last pieces of code (git commit..., git push...)

text-overflow: ellipsis not working

I was having an issue with ellipsis under chrome. Turning on white-space: nowrap seemed to fix it.

max-width: 95px;
max-height: 20px;
overflow: hidden;
display: inline-block;
text-overflow: ellipsis;
border: solid 1px black;
font-size: 12pt;
text-align: right;
white-space: nowrap;

How to generate random colors in matplotlib?

When less than 9 datasets:

colors = "bgrcmykw"
color_index = 0

for X,Y in data:
    scatter(X,Y, c=colors[color_index])
    color_index += 1

Mathematical functions in Swift

As other noted you have several options. If you want only mathematical functions. You can import only Darwin.

import Darwin

If you want mathematical functions and other standard classes and functions. You can import Foundation.

import Foundation

If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.

For OS X, you need import Cocoa.

import Cocoa

For iOS, you need import UIKit.

import UIKit

You can easily discover your playground platform by opening File Inspector (??1).

Playground Settings - Platform

Toolbar overlapping below status bar

Use android:fitsSystemWindows="true" in the root view of your layout (LinearLayout in your case). And android:fitsSystemWindows is an

internal attribute to adjust view layout based on system windows such as the status bar. If true, adjusts the padding of this view to leave space for the system windows. Will only take effect if this view is in a non-embedded activity.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol fitsSystemWindows.

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

You can explicitly tell Eclipse where to find it. Open eclipse.ini and add the following lines to the top of the file:

-vm
/absolute/path/to/jre6/bin

Update: I just nailed down the root cause on my own Windows machine. The GlassFish installer complained with exactly the same error message and after digging in GlassFish forums, the cause was clear: a corrupt JRE install on a Windows machine. My JRE came along with the JDK and the Java 6 JDK installer didn't install the JRE properly somehow. A DLL file was missing in JDK's JRE installation. After I reinstalled the standalone JRE from http://java.com, overwriting the old one, the GlassFish installer continued and also Eclipse was able to start flawlessly without those two lines in eclipse.ini.

How to generate Javadoc from command line

D:\>javadoc *.java

If you want to create dock file of lang package then path should be same where your lang package is currently. For example, I created a folder name javaapi and unzipped the src zip file, then used the command below.

C:\Users\Techsupport1\Desktop\javaapi\java\lang> javadoc *.java

How to use google maps without api key

source

In June 2016 Google announced that they would stop supporting keyless usage, meaning any request that doesn’t include an API key or Client ID. This will go into effect on June 11 2018, and keyless access will no longer be supported

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

Receive JSON POST with PHP

Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:

"http://yourdomain.com/read_result.php"

should be

"https://yourdomain.com/read_result.php"

or either way.
add or remove the "s" to match your URL.

Visual Studio : short cut Key : Duplicate Line

Why so many long drawn out methods to accomplish something so simple? It takes less than a minute to download and install the extension from Microsoft. The page says that it will bind it to ALT+D by default, but for me it bound it to CTRL+D automatically in Visual Studio Community 2015 without any changes.

Here's the link to download the extension from Microsoft.com.

How to change the color of text in javafx TextField?

If you are designing your Javafx application using SceneBuilder then use -fx-text-fill(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield.

I came here for the same problem and solved it in this way.

Test iOS app on device without apple developer program or jailbreak

Follow these Steps:

1.Open the Xcode->Select the project->select targets->Tick an automatically manage signing->then add your apple developer account->clean the project->build the project->run,everything works fine.

What's default HTML/CSS link color?

The best way to get a browser's default styling on something is to not style the element at all in the first place.

how to initialize a char array?

Absent a really good reason to do otherwise, I'd probably use:

std::vector<char> msg(65546, '\0');

Side-by-side list items as icons within a div (css)

I would recommend that you use display: inline;. float is screwed up in IE. Here is an example of how I would approach it:

<ul class="side-by-side">
  <li>item 1<li>
  <li>item 2<li>
  <li>item 3<li>
</ul>

and here's the css:

.side-by-side {
  width: 100%;
  border: 1px solid black;

}
.side-by-side li {
  display: inline;
}

Also, if you use floats the ul will not wrap around the li's and will instead have a hight of 0 in this example:

.side-by-side li {
  float: left;
}

Replace text in HTML page with jQuery

You could use the following to replace the first occurrence of a word within the body of the page:

var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);

If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g:

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

If you wanted a one liner:

$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));

You are basically taking all of the HTML within the <body> tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.

See a demo here - look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.

How to slice a Pandas Data Frame by position?

dataframe[:n] - Will return first n-1 rows

php var_dump() vs print_r()

If you're asking when you should use what, I generally use print_r() for displaying values and var_dump() for when having issues with variable types.

Changing iframe src with Javascript

Here is my updated code. It works fine and it can help you.

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Untitled 1</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script type="text/javascript">
  function go(loc) {
    document.getElementById('calendar').src = loc;
  }
  </script>
</head>

<body>
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>

  <form method="post">
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
  </form>

</body>

</html>

Definitive way to trigger keypress events with jQuery

I made it work with keyup.

$("#id input").trigger('keyup');

Adding Table rows Dynamically in Android

Activity
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableLayout
            android:id="@+id/mytable"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </TableLayout>
    </HorizontalScrollView>

Your Class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testtable);
    table = (TableLayout)findViewById(R.id.mytable);
    showTableLayout();
}


public  void showTableLayout(){
    Date date = new Date();
    int rows = 80;
    int colums  = 10;
    table.setStretchAllColumns(true);
    table.bringToFront();

    for(int i = 0; i < rows; i++){

        TableRow tr =  new TableRow(this);
        for(int j = 0; j < colums; j++)
        {
            TextView txtGeneric = new TextView(this);
            txtGeneric.setTextSize(18);
            txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
            tr.addView(txtGeneric);
            /*txtGeneric.setHeight(30); txtGeneric.setWidth(50);   txtGeneric.setTextColor(Color.BLUE);*/
        }
        table.addView(tr);
    }
}

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

How to pass dictionary items as function arguments in python?

You can just pass it

def my_function(my_data):
    my_data["schoolname"] = "something"
    print my_data

or if you really want to

def my_function(**kwargs):
    kwargs["schoolname"] = "something"
    print kwargs

Identify duplicates in a List

Similar to some answers here, but if you want to find duplicates based on some property:

  public static <T, R> Set<R> findDuplicates(Collection<? extends T> collection, Function<? super T, ? extends R> mapper) {
    Set<R> uniques = new HashSet<>();
    return collection.stream()
        .map(mapper)
        .filter(e -> !uniques.add(e))
        .collect(toSet());
  }

How to link an input button to a file select window?

You could use JavaScript and trigger the hidden file input when the button input has been clicked.

http://jsfiddle.net/gregorypratt/dhyzV/ - simple

http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery

Or, you could style a div directly over the file input and set pointer-events in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

How to disable mouse right click on a web page?

window.oncontextmenu = function () {
return false;
}

might help you.

How to get POST data in WebAPI?

Is there a way to handle form post data in a Web Api controller?

The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection:

public void Post(NameValueCollection formData)
{
  var value = formData["key"];
}

Is it possible to change the radio button icon in an android radio button group

In case you want to do it programmatically,

checkBoxOrRadioButton.setButtonDrawable(null);
checkBoxOrRadioButton.setBackgroundResource(R.drawable.resource_name);

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

Plot 3D data in R

If you're working with "real" data for which the grid intervals and sequence cannot be guaranteed to be increasing or unique (hopefully the (x,y,z) combinations are unique at least, even if these triples are duplicated), I would recommend the akima package for interpolating from an irregular grid to a regular one.

Using your definition of data:

library(akima)
im <- with(data,interp(x,y,z))
with(im,image(x,y,z))

enter image description here

And this should work not only with image but similar functions as well.

Note that the default grid to which your data is mapped to by akima::interp is defined by 40 equal intervals spanning the range of x and y values:

> formals(akima::interp)[c("xo","yo")]
$xo
seq(min(x), max(x), length = 40)

$yo
seq(min(y), max(y), length = 40)

But of course, this can be overridden by passing arguments xo and yo to akima::interp.

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Just installed Android Studio v 0.8.1 beta and ran into the same problem targeting SDK 19.

Copied 19 from the adt-bundle to android-studio, changed build.gradle to:

compileSdkVersion 19 targetSdkVersion 19

then project -> app -> open module settings (aka project structure): change compile sdk version to 19.

Now works fine.

Facebook how to check if user has liked page and show content?

There is an article here that describes your problem

http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

    <fb:visible-to-connection>
       Fans will see this content.
       <fb:else>
           Non-fans will see this content.
       </fb:else>
    </fb:visible-to-connection>

git push says "everything up-to-date" even though I have local changes

Another situation that is important to be aware of: The sort of default state for git is that you are working in the "master" branch. And for a lot of situations, you'll just hang out in that as your main working branch (although some people get fancy and do other things).

Anyway, that's just one branch. So a situation I might get into is:

My active branch is actually NOT the master branch. ... But I habitually do the command: git push (and I had previously done git push origin master, so it's a shortcut for THAT).

So I'm habitually pushing the master branch to the shared repo ... which is probably a good clean thing, in my case ...

But I have forgotten that the changes I have been working on are not yet IN the master branch !!!

So therefore everytime I try git push, and I see "Everything up to date", I want to scream, but of course, it is not git's fault! It's mine.

So instead, I merge my branch into master, and then do push, and everything is happy again.

Java: Detect duplicates in ArrayList?

If you are looking to avoid having duplicates at all, then you should just cut out the middle process of detecting duplicates and use a Set.

Python csv string to array

The official doc for csv.reader() https://docs.python.org/2/library/csv.html is very helpful, which says

file objects and list objects are both suitable

import csv

text = """1,2,3
a,b,c
d,e,f"""

lines = text.splitlines()
reader = csv.reader(lines, delimiter=',')
for row in reader:
    print('\t'.join(row))

Hash string in c#

The shortest and fastest way ever. Only 1 line!

    public static string StringSha256Hash(string text) =>
        string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

you can do update the User path as inside _JAVA_OPTIONS : -Xmx512M Path : C:\Program Files (x86)\Java\jdk1.8.0_231\bin;C:\Program Files(x86)\Java\jdk1.8.0_231\jre\bin for now it is working / /

Twitter Bootstrap: div in container with 100% height

It is very simple. You can use

.fill .map 
{
  min-height: 100vh;
}

You can change height according to your requirement.

Is it valid to have a html form inside another html form?

As workaround you could use formaction attribute on submit button. And just use different names on your inputs.

<form action="a">
<input.../>
    <!-- Form 2 inputs -->
    <input.../>
    <input.../>
    <input.../>
    <input type="submit" formaction="b">

</form>
<input.../>

Description for event id from source cannot be found

Restart your system!

A friend of mine had exactly the same problem. He tried all the described options but nothing seemed to work. After many studies, also of Microsoft's description, he concluded to restart the system. It worked!!

It seems that the operating system does not in all cases refresh the list of registered event sources. Only after a restart you can be sure the event sources are registered properly.

show more/Less text with just HTML and JavaScript

 <script type="text/javascript">
     function showml(divId,inhtmText) 
     {  
        var x = document.getElementById(divId).style.display; 

        if(x=="block")
        {
          document.getElementById(divId).style.display = "none";
          document.getElementById(inhtmText).innerHTML="Show More...";
        }
       if(x=="none")
       {
          document.getElementById(divId).style.display = "block";
          document.getElementById(inhtmText).innerHTML="Show Less";
        }
     }
</script>

 <p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

if more div use like this change only 1 to 2

<p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

demo jsfiddle

How to make the python interpreter correctly handle non-ASCII characters in string operations?

def removeNonAscii(s): return "".join(filter(lambda x: ord(x)<128, s))

edit: my first impulse is always to use a filter, but the generator expression is more memory efficient (and shorter)...

def removeNonAscii(s): return "".join(i for i in s if ord(i)<128)

Keep in mind that this is guaranteed to work with UTF-8 encoding (because all bytes in multi-byte characters have the highest bit set to 1).

How to send a "multipart/form-data" with requests in python?

I'm trying to send a request to URL_server with request module in python 3. This works for me:

# -*- coding: utf-8 *-*
import json, requests

URL_SERVER_TO_POST_DATA = "URL_to_send_POST_request"
HEADERS = {"Content-Type" : "multipart/form-data;"}

def getPointsCC_Function():
  file_data = {
      'var1': (None, "valueOfYourVariable_1"),
      'var2': (None, "valueOfYourVariable_2")
  }

  try:
    resElastic = requests.post(URL_GET_BALANCE, files=file_data)
    res = resElastic.json()
  except Exception as e:
    print(e)

  print (json.dumps(res, indent=4, sort_keys=True))

getPointsCC_Function()

Where:

  • URL_SERVER_TO_POST_DATA = Server where we going to send data
  • HEADERS = Headers sended
  • file_data = Params sended

'ls' is not recognized as an internal or external command, operable program or batch file

I'm fairly certain that the ls command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd, which is the command line for the Windows OS).

You should use dir instead, which is the Windows equivalent of ls.

Edit (since this post seems to be getting so many views :) ):

You can't use ls on cmd as it's not shipped with Windows, but you can use it on other terminal programs (such as GitBash). Note, ls might work on some FTP servers if the servers are linux based and the FTP is being used from cmd.

dir on Windows is similar to ls. To find out the various options available, just do dir/?.

If you really want to use ls, you could install 3rd party tools to allow you to run unix commands on Windows. Such a program is Microsoft Windows Subsystem for Linux (link to docs).

onKeyDown event not working on divs in React

You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key instead of event.keyCode (because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).

onKeyPressed(e) {
  console.log(e.key);
}

render() {
  let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
  return (
    <div 
      className="player"
      style={{ position: "absolute" }}
      onKeyDown={this.onKeyPressed}
    >
      <div className="light-circle">
        <div className="image-wrapper">
          <img src={IMG_URL+player.img} />
        </div>
      </div>
    </div>
  )
}

Splitting a C++ std::string using tokens, e.g. ";"

I find std::getline() is often the simplest. The optional delimiter parameter means it's not just for reading "lines":

#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> strings;
    istringstream f("denmark;sweden;india;us");
    string s;    
    while (getline(f, s, ';')) {
        cout << s << endl;
        strings.push_back(s);
    }
}

Centering brand logo in Bootstrap Navbar

Updated 2018

Bootstrap 3

See if this example helps: http://bootply.com/mQh8DyRfWY

The brand is centered using..

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    text-align: center;
    margin: auto;
}

Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner.

EDIT - Another approach is using transform: translateX(-50%);

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

http://www.bootply.com/V7vKDfk46G

Bootstrap 4

In Bootstrap 4, mx-auto or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.

Also see:

Bootstrap NavBar with left, center or right aligned items

Casting an int to a string in Python

x = 1
y = "foo" + str(x)

Please see the Python documentation: https://docs.python.org/2/library/functions.html#str

Performing a query on a result from another query?

Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
  SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
  FROM availables
  INNER JOIN rooms
  ON availables.room_id=rooms.id
  WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
  GROUP BY availables.bookdate
) AS SUBQUERY

CakePHP select default value in SELECT input

Assuming you are using form helper to generate the form:

select(string $fieldName, array $options, mixed $selected, array $attributes, boolean $showEmpty)

Set the third parameter to set the selected option.

When should I write the keyword 'inline' for a function/method?

You want to put it in the very beginning, before return type. But most Compilers ignore it. If it's defined, and it has a smaller block of code, most compilers consider it inline anyway.

How can I set the background color of <option> in a <select> element?

I assume you mean the <select> input element?

Support for that is pretty new, but FF 3.6, Chrome and IE 8 render this all right:

_x000D_
_x000D_
<select name="select">
  <option value="1" style="background-color: blue">Test</option>
  <option value="2" style="background-color: green">Test</option>
</select>
_x000D_
_x000D_
_x000D_

Changing the image source using jQuery

This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

selecting rows with id from another table

You can use a subquery:

SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');

and if you need to show all columns from both tables:

SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'

Floating point comparison functions for C#

Further to Andrew Wang's answer: if the BitConverter method is too slow but you cannot use unsafe code in your project, this struct is ~6x quicker than BitConverter:

[StructLayout(LayoutKind.Explicit)]
public struct FloatToIntSafeBitConverter
{
    public static int Convert(float value)
    {
        return new FloatToIntSafeBitConverter(value).IntValue;
    }

    public FloatToIntSafeBitConverter(float floatValue): this()
    {
        FloatValue = floatValue;
    }

    [FieldOffset(0)]
    public readonly int IntValue;

    [FieldOffset(0)]
    public readonly float FloatValue;
}

(Incidentally, I tried using the accepted solution but it (well my conversion at least) failed some of the unit tests also mentioned in the answer. e.g. assertTrue(nearlyEqual(Float.MIN_VALUE, -Float.MIN_VALUE)); )

Quick easy way to migrate SQLite3 to MySQL?

echo ".dump" | sqlite3 /tmp/db.sqlite > db.sql

watch out for CREATE statements

How do I count a JavaScript object's attributes?

 var miobj = [
  {"padreid":"0", "sw":"0", "dtip":"UNO", "datos":[]},
  {"padreid":"1", "sw":"0", "dtip":"DOS", "datos":[]}
 ];
 alert(miobj.length) //=== 2

but

 alert(miobj[0].length) //=== undefined

this function is very good

Object.prototype.count = function () {
    var count = 0;
    for(var prop in this) {
        if(this.hasOwnProperty(prop))
            count = count + 1;
    }
    return count;
}

alert(miobj.count()) // === 2
alert(miobj[0].count()) // === 4

Get the Highlighted/Selected text

Get highlighted text this way:

window.getSelection().toString()

and of course a special treatment for ie:

document.selection.createRange().htmlText

How do I compile C++ with Clang?

Also, for posterity -- Clang (like GCC) accepts the -x switch to set the language of the input files, for example,

$ clang -x c++ some_random_file.txt

This mailing list thread explains the difference between clang and clang++ well: Difference between clang and clang++

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In your entity definition, you're not specifying the @JoinColumn for the Account joined to a Transaction. You'll want something like this:

@Entity
public class Transaction {
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    @JoinColumn(name = "accountId", referencedColumnName = "id")
    private Account fromAccount;
}

EDIT: Well, I guess that would be useful if you were using the @Table annotation on your class. Heh. :)

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

For me Fake Sendmail works.

What to do:

1) Edit C:\wamp\sendmail\sendmail.ini:

smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password

2) Edit php.ini and set sendmail_path

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

That's it. Now you can test a mail.

How to return values in javascript

I would prefer a callback solution: Working fiddle here: http://jsfiddle.net/canCu/

function myFunction(value1,value2,value3, callback) {

    value2 = 'somevalue2'; //to return
    value3 = 'somevalue3'; //to return

    callback( value2, value3 );

}

var value1 = 1;
var value2 = 2;
var value3 = 3;

myFunction(value1,value2,value3, function(value2, value3){
    if (value2 && value3) {
        //Do some stuff
        alert( value2 + '-' + value3 );
    }    
});

is there a tool to create SVG paths from an SVG file?

Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.

  1. First download Gimp: https://www.gimp.org/downloads/
  2. Export your SVG as a .svg file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it up
  3. Import the SVG file into Gimp with File -> Open, and the following (or similar) dialog should show up:

Gimp SVG Open Dialog

Check both the Import Paths and Merge imported paths options

  1. Then go to Windows->Dockable Dialogues->Paths
  2. Right-click on the single path which says Imported Path and you should see the following dialog:

enter image description here

  1. Click Export Path... and save this text file to a location of your choice
  2. Locate and open up this file with a text editor of your choice e.g Notepad, TextEdit
  3. Copy the text within the <path d="copy this text here" />
  4. Since Gimp formats the text with lots of spaces, you may need to re-format it, by removing some of the spaces to paste it into your HTML in a single line

Run cron job only if it isn't already running

Consider using pgrep (if available) rather than ps piped through grep if you're going to go that route. Though, personally, I've got a lot of mileage out of scripts of the form

while(1){
  call script_that_must_run
  sleep 5
}

Though this can fail and cron jobs are often the best way for essential stuff. Just another alternative.

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

MVVM Passing EventArgs As Command Parameter

Prism's InvokeCommandAction will pass the event args by default if CommandParameter is not set.

https://docs.microsoft.com/en-us/previous-versions/msp-n-p/gg405494(v=pandp.40)#passing-eventargs-parameters-to-the-command

Here is an example. Note the use of prism:InvokeCommandAction instead of i:InvokeCommandAction.

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Sorting">
        <prism:InvokeCommandAction Command="{Binding SortingCommand}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

The ViewModel

    private DelegateCommand<EventArgs> _sortingCommand;

    public DelegateCommand<EventArgs> SortingCommand => _sortingCommand ?? (_sortingCommand = new DelegateCommand<EventArgs>(OnSortingCommand));

    private void OnSortingCommand(EventArgs obj)
    {
        //do stuff
    }

There is a new version of the Prismlibrary documentation.

How do I record audio on iPhone with AVAudioRecorder?

As per the above answers, I made some changes and I got the correct output.

Step 1: Under "inf.plist" add the Microphone usage permissions ==>

  <key>NSMicrophoneUsageDescription</key>
  <string>${PRODUCT_NAME} Microphone Usage</string>

Step 2:

  1. Save record audio file into Local Document Directory

  2. Play/Stop recording

  3. Get the Duration of Saved audio file

Here is the source code. Please have a look at once and use it.

ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController{
AVAudioPlayer *audioPlayer;
AVAudioRecorder *audioRecorder;
}

-(IBAction) startRecording;
-(IBAction) stopRecording;
-(IBAction) playRecording;
-(IBAction) stopPlaying;

@end

ViewController.m

#import "ViewController.h"
@interface ViewController () <AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

-(IBAction) startRecording{
// Setup audio session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err)
{
    NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
    return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err)
{
    NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
    return;
}
AVAudioSessionRecordPermission permissionStatus = [audioSession recordPermission];
switch (permissionStatus) {
    case AVAudioSessionRecordPermissionUndetermined:{
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
            if (granted) {
                // Microphone enabled code
                NSLog(@"Mic permission granted.  Call method for granted stuff.");
                [self startRecordingAudioSound];
            }
            else {
                // Microphone disabled code
                NSLog(@"Mic permission indeterminate. Call method for indeterminate stuff.");
                //        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
            }
        }];
        break;
    }
    case AVAudioSessionRecordPermissionDenied:
        // direct to settings...
        NSLog(@"Mic permission denied. Call method for denied stuff.");

        break;
    case AVAudioSessionRecordPermissionGranted:
        // mic access ok...
        NSLog(@"Mic permission granted.  Call method for granted stuff.");
        [self startRecordingAudioSound];
        break;
    default:
        // this should not happen.. maybe throw an exception.
        break;
}
}

#pragma mark - Audio Recording
- (BOOL)startRecordingAudioSound{
NSError *error = nil;
NSMutableDictionary *recorderSettings = [[NSMutableDictionary alloc] init];
[recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

// Create a new audio file
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath_ = [searchPaths objectAtIndex: 0];
NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:[self dateString]];
NSLog(@"the path is %@",pathToSave);

// File URL
NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];

//Save recording path to preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setURL:url forKey:@"Test1"];
[prefs synchronize];

audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&error];
if (!audioRecorder)
{
    NSLog(@"Error establishing recorder: %@", error.localizedFailureReason);
    return NO;
}

// Initialize degate, metering, etc.
audioRecorder.delegate = self;
audioRecorder.meteringEnabled = YES;
//self.title = @"0:00";

if (![audioRecorder prepareToRecord])
{
    NSLog(@"Error: Prepare to record failed");
    //[self say:@"Error while preparing recording"];
    return NO;
}

if (![audioRecorder record])
{
    NSLog(@"Error: Record failed");
    //  [self say:@"Error while attempting to record audio"];
    return NO;
}
NSLog(@"Recroding Started");
return YES;
}

#pragma mark - AVAudioRecorderDelegate
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
NSLog (@"audioRecorderDidFinishRecording:successfully:");
}

#pragma mark - AVAudioPlayerDelegate
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog (@"audioPlayerDidFinishPlaying:successfully:");
}

- (NSString *) dateString {
// return a formatted string for a file name
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"ddMMMYY_hhmmssa";
return [[formatter stringFromDate:[NSDate date]]stringByAppendingString:@".aif"];
}

-(IBAction) stopRecording{
NSLog(@"stopRecording");
[audioRecorder stop];
NSLog(@"stopped");
}

-(IBAction) playRecording{
//Load recording path from preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSURL *temporaryRecFile = [prefs URLForKey:@"Test1"];

//Get Duration of Audio File
AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:temporaryRecFile options:nil];
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
NSLog(@"Duration Of Audio: %f", audioDurationSeconds);

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
audioPlayer.volume = 1;
[audioPlayer prepareToPlay];
[audioPlayer play];
NSLog(@"playing");
}

-(IBAction) stopPlaying{
NSLog(@"stopPlaying");
[audioPlayer stop];
NSLog(@"stopped");
 }

 @end

Check if one list contains element from the other

org.springframework.util.CollectionUtils

boolean containsAny(java.util.Collection<?> source, java.util.Collection<?> candidates)

Return true if any element in 'candidates' is contained in 'source'; otherwise returns false

IIS: Where can I find the IIS logs?

I'm adding this answer because after researching the web, I ended up at this answer but still didn't know which subfolder of the IIS logs folder to look in.

If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.

Once you know the ID, let's call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:

%SystemDrive%\inetpub\logs\LogFiles\W3SVC4

Acknowlegements:

  • Answer by @jishi tells where the logs are by default.
  • Answer by @Rafid explains how to find actual location (maybe not default).
  • Answer by @Bergius gives a programmatic way to find the log folder location for a specific website, taking ID into account, without using IIS.

Bootstrap 3 - 100% height of custom div inside column

I was just looking for a smiliar issue and I found this:

.div{
  height : 100vh;
}

more info

vw: 1/100th viewport width
vh: 1/100th viewport height
vmin: 1/100th of the smallest side
vmax: 1/100th of the largest side

How to reset AUTO_INCREMENT in MySQL?

Adding an update because the functionality changed in MySQL 5.6. As of MySQL 5.6 you CAN use the simple ALTER TABLE with InnoDB:

ALTER TABLE tablename AUTO_INCREMENT = 1;

The docs are updated to reflect this:

http://dev.mysql.com/doc/refman/5.6/en/alter-table.html

My testing also shows that the table is NOT copied, the value is simply changed.

Change the "No file chosen":

_x000D_
_x000D_
$(function () {_x000D_
     $('input[type="file"]').change(function () {_x000D_
          if ($(this).val() != "") {_x000D_
                 $(this).css('color', '#333');_x000D_
          }else{_x000D_
                 $(this).css('color', 'transparent');_x000D_
          }_x000D_
     });_x000D_
})
_x000D_
input[type="file"]{_x000D_
    color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" name="app_cvupload" class="fullwidth input rqd">
_x000D_
_x000D_
_x000D_

How to create a hidden <img> in JavaScript?

This question is vague, but if you want to make the image with Javascript. It is simple.

function loadImages(src) {
  if (document.images) {
    img1 = new Image();
    img1.src = src;
}
loadImages("image.jpg");

The image will be requested but until you show it it will never be displayed. great for pre loading images you expect to be requests but delaying it until the document is loaded.

Example

How to do multiline shell script in Ansible

Adding a space before the EOF delimiter allows to avoid cmd:

- shell: |
    cat <<' EOF'
    This is a test.
    EOF

How to deselect a selected UITableView cell?

It might be useful to make an extension in Swift for this.

Swift 4 and Swift 5:

Swift extension (e.g. in a UITableViewExtension.swift file):

import UIKit

extension UITableView {

    func deselectSelectedRow(animated: Bool)
    {
        if let indexPathForSelectedRow = self.indexPathForSelectedRow {
            self.deselectRow(at: indexPathForSelectedRow, animated: animated)
        }
    }

}

Use e.g.:

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)

    self.tableView.deselectSelectedRow(animated: true)
}

What is the (best) way to manage permissions for Docker shared volumes?

My approach is to detect current UID/GID, then create such user/group inside the container and execute the script under him. As a result all files he will create will match the user on the host (which is the script):

# get location of this script no matter what your current folder is, this might break between shells so make sure you run bash
LOCAL_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# get current IDs
USER_ID=$(id -u)
GROUP_ID=$(id -g)

echo "Mount $LOCAL_DIR into docker, and match the host IDs ($USER_ID:$GROUP_ID) inside the container."

docker run -v $LOCAL_DIR:/host_mount -i debian:9.4-slim bash -c "set -euo pipefail && groupadd -r -g $GROUP_ID lowprivgroup && useradd -u $USER_ID lowprivuser -g $GROUP_ID && cd /host_mount && su -c ./runMyScriptAsRegularUser.sh lowprivuser"

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

{{ myentity.text|length > 50 ? myentity.text|slice(0, 50) ~ '...' : myentity.text  }}

You need Twig 1.6

What is the difference between signed and unsigned variables?

unsigned is used when ur value must be positive, no negative value here, if signed for int range -32768 to +32767 if unsigned for int range 0 to 65535