Programs & Examples On #Serialization

Serialization is the process by which data-structures are converted into a format that can be easily stored or transmitted and subsequently reconstructed.

Convert an object to an XML string

 public static class XMLHelper
    {
        /// <summary>
        /// Usage: var xmlString = XMLHelper.Serialize<MyObject>(value);
        /// </summary>
        /// <typeparam name="T">Ki?u d? li?u</typeparam>
        /// <param name="value">giá tr?</param>
        /// <param name="omitXmlDeclaration">b? qua declare</param>
        /// <param name="removeEncodingDeclaration">xóa encode declare</param>
        /// <returns>xml string</returns>
        public static string Serialize<T>(T value, bool omitXmlDeclaration = false, bool omitEncodingDeclaration = true)
        {
            if (value == null)
            {
                return string.Empty;
            }
            try
            {
                var xmlWriterSettings = new XmlWriterSettings
                {
                    Indent = true,
                    OmitXmlDeclaration = omitXmlDeclaration, //true: remove <?xml version="1.0" encoding="utf-8"?>
                    Encoding = Encoding.UTF8,
                    NewLineChars = "", // remove \r\n
                };

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

                using (var memoryStream = new MemoryStream())
                {
                    using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
                    {
                        xmlserializer.Serialize(xmlWriter, value);
                        //return stringWriter.ToString();
                    }

                    memoryStream.Position = 0;
                    using (var sr = new StreamReader(memoryStream))
                    {
                        var pureResult = sr.ReadToEnd();
                        var resultAfterOmitEncoding = ReplaceFirst(pureResult, " encoding=\"utf-8\"", "");
                        if (omitEncodingDeclaration)
                            return resultAfterOmitEncoding;
                        return pureResult;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XMLSerialize error: ", ex);
            }
        }

        private static string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);

            if (pos < 0)
            {
                return text;
            }

            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
    }

java.io.InvalidClassException: local class incompatible:

Serialisation in java is not meant as long term persistence or transport format - it is too fragile for this. With the slightest difference in class bytecode and JVM, your data is not readable anymore. Use XML or JSON data-binding for your task (XStream is fast and easy to use, and there are a ton of alternatives)

How can I display a JavaScript object?

var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);

Preferred method to store PHP arrays (json_encode vs serialize)

I've written a blogpost about this subject: "Cache a large array: JSON, serialize or var_export?". In this post it is shown that serialize is the best choice for small to large sized arrays. For very large arrays (> 70MB) JSON is the better choice.

How to generate serial version UID in Intellij

Easiest method: Alt+Enter on

private static final long serialVersionUID = ;

IntelliJ will underline the space after the =. put your cursor on it and hit alt+Enter (Option+Enter on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

You don't need to use JsonConverterAttribute, keep your model clean, also use CustomCreationConverter, the code is simpler:

public class SampleConverter : CustomCreationConverter<ISample>
{
    public override ISample Create(Type objectType)
    {
        return new Sample();
    }
}

Then:

var sz = JsonConvert.SerializeObject( sampleGroupInstance );
JsonConvert.DeserializeObject<SampleGroup>( sz, new SampleConverter());

Documentation: Deserialize with CustomCreationConverter

jQuery to serialize only elements within a div

serialize all the form-elements within a div.

You could do that by targeting the div #target-div-id inside your form using :

$('#target-div-id').find('select, textarea, input').serialize();

Serializing list to JSON

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

<Django object > is not JSON serializable

First I added a to_dict method to my model ;

def to_dict(self):
    return {"name": self.woo, "title": self.foo}

Then I have this;

class DjangoJSONEncoder(JSONEncoder):

    def default(self, obj):
        if isinstance(obj, models.Model):
            return obj.to_dict()
        return JSONEncoder.default(self, obj)


dumps = curry(dumps, cls=DjangoJSONEncoder)

and at last use this class to serialize my queryset.

def render_to_response(self, context, **response_kwargs):
    return HttpResponse(dumps(self.get_queryset()))

This works quite well

Checking if an object is a number in C#

Rather than rolling your own, the most reliable way to tell if an in-built type is numeric is probably to reference Microsoft.VisualBasic and call Information.IsNumeric(object value). The implementation handles a number of subtle cases such as char[] and HEX and OCT strings.

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

Submit form using AJAX and jQuery

There is a nice form plugin that allows you to send an HTML form asynchroniously.

$(document).ready(function() { 
    $('#myForm1').ajaxForm(); 
});

or

$("select").change(function(){
    $('#myForm1').ajaxSubmit();
});

to submit the form immediately

Deserialize JSON into C# dynamic object?

JsonFx can deserialize JSON content into dynamic objects.

Serialize to/from dynamic types (default for .NET 4.0):

var reader = new JsonReader(); var writer = new JsonWriter();

string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}

@JsonProperty annotation on field as well as getter/setter

In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.

In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.

With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.

jQuery: serialize() form and other parameters

Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:

var data = form.serialize() + '&' + $.param(object)

See http://api.jquery.com/jQuery.param for further reference.

$(this).serialize() -- How to add a value?

While matt b's answer will work, you can also use .serializeArray() to get an array from the form data, modify it, and use jQuery.param() to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.

var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
    type: 'POST',
    url: this.action,
    data: $.param(data),
});

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can use ObjectMapper

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectClass object = objectMapper.readValue(data, ObjectClass.class);

What is deserialize and serialize in JSON?

Explanation of Serialize and Deserialize using Python

In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.

Serialization using pickle

import pickle

#the object to serialize
example_dic={1:"6",2:"2",3:"f"}

#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()

The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):

€}q (KX 6qKX 2qKX fqu.

Deserialization using pickle

import pickle

pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)

print(get_deserialized_data_back)

Output:

{1: '6', 2: '2', 3: 'f'}

Simple working Example of json.net in VB.net

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

Java ByteBuffer to String

the root of this question is how to decode bytes to string?

this can be done with the JAVA NIO CharSet:

public final CharBuffer decode(ByteBuffer bb)

FileChannel channel = FileChannel.open(
  Paths.get("files/text-latin1.txt", StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);

CharSet latin1 = StandardCharsets.ISO_8859_1;
CharBuffer latin1Buffer = latin1.decode(buffer);

String result = new String(latin1Buffer.array());
  • First we create a channel and read it in a buffer
  • Then decode method decodes a Latin1 buffer to a char buffer
  • We can then put the result, for instance, in a String

How do I PHP-unserialize a jQuery-serialized form?

Use:

$( '#form' ).serializeArray();

Php get array, dont need unserialize ;)

Jackson - How to process (deserialize) nested JSON?

Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.

Given this JSON:

{
    "list": [
        {
            "wrapper": {
                "name": "Jack"
            }
        },
        {
            "wrapper": {
                "name": "Jane"
            }
        }
    ]
}

And these model objects:

public class RootObject {
    @JsonProperty("list")
    @JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
    @SkipWrapperObject("wrapper")
    public InnerObject[] innerObjects;
}

and

public class InnerObject {
    @JsonProperty("name")
    public String name;
}

Where the Jackson voodoo is implemented like:

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
    String value();
}

and

public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
        ContextualDeserializer {
    private Class<?> wrappedType;
    private String wrapperKey;

    public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
            BeanProperty property) throws JsonMappingException {
        SkipWrapperObject skipWrapperObject = property
                .getAnnotation(SkipWrapperObject.class);
        wrapperKey = skipWrapperObject.value();
        JavaType collectionType = property.getType();
        JavaType collectedType = collectionType.containedType(0);
        wrappedType = collectedType.getRawClass();
        return this;
    }

    @Override
    public Object deserialize(JsonParser parser, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode objectNode = mapper.readTree(parser);
        JsonNode wrapped = objectNode.get(wrapperKey);
        Object mapped = mapIntoObject(wrapped);
        return mapped;
    }

    private Object mapIntoObject(JsonNode node) throws IOException,
            JsonProcessingException {
        JsonParser parser = node.traverse();
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(parser, wrappedType);
    }
}

Hope this is useful to someone!

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

Print array to a file

Either var_export or set print_r to return the output instead of printing it.

Example from PHP manual

$b = array (
    'm' => 'monkey', 
    'foo' => 'bar', 
    'x' => array ('x', 'y', 'z'));

$results = print_r($b, true); // $results now contains output from print_r

You can then save $results with file_put_contents. Or return it directly when writing to file:

file_put_contents('filename.txt', print_r($b, true));

IntelliJ IDEA generating serialVersionUID

Install the GenerateSerialVersionUID plugin by Olivier Descout.

Go to: menu File ? Settings ? Plugins ? Browse repositories ? GenerateSerialVersionUID

Install the plugin and restart.

Now you can generate the id from menu Code ? Generate ? serialVersionUID` or the shortcut.

Java Serializable Object to Byte Array

code example with java 8+:

public class Person implements Serializable {

private String lastName;
private String firstName;

public Person() {
}

public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

@Override
public String toString() {
    return "firstName: " + firstName + ", lastName: " + lastName;
}
}


public interface PersonMarshaller {
default Person fromStream(InputStream inputStream) {
    try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
        Person person= (Person) objectInputStream.readObject();
        return person;
    } catch (IOException | ClassNotFoundException e) {
        System.err.println(e.getMessage());
        return null;
    }
}

default OutputStream toStream(Person person) {
    try (OutputStream outputStream = new ByteArrayOutputStream()) {
        ObjectOutput objectOutput = new ObjectOutputStream(outputStream);
        objectOutput.writeObject(person);
        objectOutput.flush();
        return outputStream;
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return null;
    }

}

}

How to save/restore serializable object to/from file?

You can use the following:

    /// <summary>
    /// Serializes an object.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="serializableObject"></param>
    /// <param name="fileName"></param>
    public void SerializeObject<T>(T serializableObject, string fileName)
    {
        if (serializableObject == null) { return; }

        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, serializableObject);
                stream.Position = 0;
                xmlDocument.Load(stream);
                xmlDocument.Save(fileName);
            }
        }
        catch (Exception ex)
        {
            //Log exception here
        }
    }


    /// <summary>
    /// Deserializes an xml file into an object list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public T DeSerializeObject<T>(string fileName)
    {
        if (string.IsNullOrEmpty(fileName)) { return default(T); }

        T objectOut = default(T);

        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(fileName);
            string xmlString = xmlDocument.OuterXml;

            using (StringReader read = new StringReader(xmlString))
            {
                Type outType = typeof(T);

                XmlSerializer serializer = new XmlSerializer(outType);
                using (XmlReader reader = new XmlTextReader(read))
                {
                    objectOut = (T)serializer.Deserialize(reader);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
        }

        return objectOut;
    }

How to serialize a JObject without the formatting?

you can use JsonConvert.SerializeObject()

JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method

JsonConvert.SerializeObject()

JObject.Parse()

JSONResult to String

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

How do you serialize a model instance in Django?

There is a good answer for this and I'm surprised it hasn't been mentioned. With a few lines you can handle dates, models, and everything else.

Make a custom encoder that can handle models:

from django.forms import model_to_dict
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Model

class ExtendedEncoder(DjangoJSONEncoder):

    def default(self, o):

        if isinstance(o, Model):
            return model_to_dict(o)

        return super().default(o)

Now use it when you use json.dumps

json.dumps(data, cls=ExtendedEncoder)

Now models, dates and everything can be serialized and it doesn't have to be in an array or serialized and unserialized. Anything you have that is custom can just be added to the default method.

You can even use Django's native JsonResponse this way:

from django.http import JsonResponse

JsonResponse(data, encoder=ExtendedEncoder)

Serialize an object to string

Use a StringWriter instead of a StreamWriter:

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

    using(StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

Note, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible subclasses of T (which are valid for the method), while using the latter one will fail when passing a type derived from T.    Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject that is defined in the derived type's base class: http://ideone.com/1Z5J1.

Also, Ideone uses Mono to execute code; the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

What is the difference between Serialization and Marshaling?

Marshalling is the rule to tell compiler how the data will be represented on another environment/system; For example;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;

as you can see two different string values represented as different value types.

Serialization will only convert object content, not representation (will stay same) and obey rules of serialization, (what to export or no). For example, private values will not be serialized, public values yes and object structure will stay same.

Java serialization - java.io.InvalidClassException local class incompatible

@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver program on all your old classes. put these serialVersionUID values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID on all Serializable classes)

if the new versions are not serial compatible, then you need to do some magic with a custom readObject implementation (you would only need a custom writeObject if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.

Of course, even if the new class is serial compatible, you may still want a custom readObject implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

Alternative ASP.NET MVC 5 Fix:

In my case the error was occurring during the request. Best approach in my scenario is modifying the actual JsonValueProviderFactory which applies the fix to the global project and can be done by editing the global.cs file as such.

JsonValueProviderConfig.Config(ValueProviderFactories.Factories);

add a web.config entry:

<add key="aspnet:MaxJsonLength" value="20971520" />

and then create the two following classes

public class JsonValueProviderConfig
{
    public static void Config(ValueProviderFactoryCollection factories)
    {
        var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
        factories.Remove(jsonProviderFactory);
        factories.Add(new CustomJsonValueProviderFactory());
    }
}

This is basically an exact copy of the default implementation found in System.Web.Mvc but with the addition of a configurable web.config appsetting value aspnet:MaxJsonLength.

public class CustomJsonValueProviderFactory : ValueProviderFactory
{

    /// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
    /// <returns>A JSON value-provider object for the specified controller context.</returns>
    /// <param name="controllerContext">The controller context.</param>
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext);
        if (deserializedObject == null)
            return null;

        Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), string.Empty, deserializedObject);

        return new DictionaryValueProvider<object>(strs, CultureInfo.CurrentCulture);
    }

    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return null;

        string fullStreamString = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd();
        if (string.IsNullOrEmpty(fullStreamString))
            return null;

        var serializer = new JavaScriptSerializer()
        {
            MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength()
        };
        return serializer.DeserializeObject(fullStreamString);
    }

    private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
    {
        IDictionary<string, object> strs = value as IDictionary<string, object>;
        if (strs != null)
        {
            foreach (KeyValuePair<string, object> keyValuePair in strs)
                CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);

            return;
        }

        IList lists = value as IList;
        if (lists == null)
        {
            backingStore.Add(prefix, value);
            return;
        }

        for (int i = 0; i < lists.Count; i++)
        {
            CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakeArrayKey(prefix, i), lists[i]);
        }
    }

    private class EntryLimitedDictionary
    {
        private static int _maximumDepth;

        private readonly IDictionary<string, object> _innerDictionary;

        private int _itemCount;

        static EntryLimitedDictionary()
        {
            _maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth();
        }

        public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
        {
            this._innerDictionary = innerDictionary;
        }

        public void Add(string key, object value)
        {
            int num = this._itemCount + 1;
            this._itemCount = num;
            if (num > _maximumDepth)
            {
                throw new InvalidOperationException("The length of the string exceeds the value set on the maxJsonLength property.");
            }
            this._innerDictionary.Add(key, value);
        }
    }

    private static string MakeArrayKey(string prefix, int index)
    {
        return string.Concat(prefix, "[", index.ToString(CultureInfo.InvariantCulture), "]");
    }

    private static string MakePropertyKey(string prefix, string propertyName)
    {
        if (string.IsNullOrEmpty(prefix))
        {
            return propertyName;
        }
        return string.Concat(prefix, ".", propertyName);
    }

    private static int GetMaximumDepth()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }

    private static int GetMaxJsonLength()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonLength");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }
}

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary)

 var result = new JsonResult()
 {
     Data = new
     {
         partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
     }
 };

I get what's expected:

{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}

Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

You'll see the difference (and can make sure you're using the right one) when serializing a date:

Microsoft way:

 {"wireTime":"\/Date(1355627201572)\/"}

JSON.NET way:

 {"wireTime":"2012-12-15T19:07:03.5247384-08:00"}

Biggest differences of Thrift vs Protocol Buffers?

  • Protobuf serialized objects are about 30% smaller than Thrift.
  • Most actions you may want to do with protobuf objects (create, serialize, deserialize) are much slower than thrift unless you turn on option optimize_for = SPEED.
  • Thrift has richer data structures (Map, Set)
  • Protobuf API looks cleaner, though the generated classes are all packed as inner classes which is not so nice.
  • Thrift enums are not real Java Enums, i.e. they are just ints. Protobuf has real Java enums.

For a closer look at the differences, check out the source code diffs at this open source project.

How to make a class JSON serializable

For more complex classes you could consider the tool jsonpickle:

jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.

The standard Python libraries for encoding Python into JSON, such as the stdlib’s json, simplejson, and demjson, can only handle Python primitives that have a direct JSON equivalent (e.g. dicts, lists, strings, ints, etc.). jsonpickle builds on top of these libraries and allows more complex data structures to be serialized to JSON. jsonpickle is highly configurable and extendable–allowing the user to choose the JSON backend and add additional backends.

(link to jsonpickle on PyPi)

JSON.NET Error Self referencing loop detected for type

Team:

This works with ASP.NET Core; The challenge to the above is how you 'set the setting to ignore'. Depending on how you setup your application it can be quite challenging. Here is what worked for me.

This can be placed in your public void ConfigureServices(IServiceCollection services) section.

services.AddMvc().AddJsonOptions(opt => 
        { 
      opt.SerializerSettings.ReferenceLoopHandling =
      Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object

Parcelable encountered IOException writing serializable object getactivity()

I faced Same issue, the issues was there are some inner classes with the static keyword.After removing the static keyword it started working and also the inner class should implements to Serializable

Issue scenario

class A implements Serializable{ 
  class static B{
  } 
}

Resolved By

class A implements Serializable{ 
      class B implements Serializable{
      } 
    }

how to do file upload using jquery serialization

hmmmm i think there is much efficient way to make it specially for people want to target all browser and not only FormData supported browser

the idea to have hidden IFRAME on page and making normal submit for the From inside IFrame example

<FORM action='save_upload.php' method=post
   enctype='multipart/form-data' target=hidden_upload>
   <DIV><input
      type=file name='upload_scn' class=file_upload></DIV>
   <INPUT
      type=submit name=submit value=Upload /> <IFRAME id=hidden_upload
      name=hidden_upload src='' onLoad='uploadDone("hidden_upload")'
      style='width:0;height:0;border:0px solid #fff'></IFRAME> 
</FORM>

most important to make a target of form the hidden iframe ID or name and enctype multipart/form-data to allow accepting photos

javascript side

function getFrameByName(name) {
    for (var i = 0; i < frames.length; i++)
        if (frames[i].name == name)
            return frames[i];

    return null;
}

function uploadDone(name) {
    var frame = getFrameByName(name);
    if (frame) {
        ret = frame.document.getElementsByTagName("body")[0].innerHTML;

        if (ret.length) {
            var json = JSON.parse(ret);
         // do what ever you want 
        }
    }
}

server Side Example PHP

<?php
  $target_filepath = "/tmp/" . basename($_FILES['upload_scn']['name']);

  if (move_uploaded_file($_FILES['upload_scn']['tmp_name'], $target_filepath)) {
    $result = ....
  }

echo json_encode($result);
?>

Is it possible to deserialize XML into List<T>?

I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.

Take a look (it works for me):

private void SerializeParams<T>(XDocument doc, List<T> paramList)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());

        System.Xml.XmlWriter writer = doc.CreateWriter();

        serializer.Serialize(writer, paramList);

        writer.Close();           
    }

private List<T> DeserializeParams<T>(XDocument doc)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));

        System.Xml.XmlReader reader = doc.CreateReader();

        List<T> result = (List<T>)serializer.Deserialize(reader);
        reader.Close();

        return result;
    }

So you can serialize whatever list you want! You don't need to specify the list type every time.

        List<AssemblyBO> list = new List<AssemblyBO>();
        list.Add(new AssemblyBO());
        list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
        XDocument doc = new XDocument();
        SerializeParams<T>(doc, list);
        List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

How do I turn a C# object into a JSON string in .NET?

Since we all love one-liners

... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})

Documentation: Serializing and Deserializing JSON

How to Serialize a list in java?

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

How can I ignore a property when serializing using the DataContractSerializer?

What you are saying is in conflict with what it says in the MSDN library at this location:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx

I don't see any mention of the SP1 feature you mention.

Serializing and submitting a form with jQuery and PHP

The problem can be PHP configuration:

Please check the setting max_input_vars in the php.ini file.

Try to increase the value of this setting to 5000 as example.

max_input_vars = 5000

Then restart your web-server and try.

How to serialize an object into a string

Today the most obvious approach is to save the object(s) to JSON.

  1. JSON is readable
  2. JSON is more readable and easier to work with than XML.
  3. A lot of Non-SQL databases that allow storing JSON directly.
  4. Your client already communicates with the server using JSON. (If it doesn't, it is very likely a mistake.)

Example using Gson.

Gson gson = new Gson();
Person[] persons = getArrayOfPersons();
String json = gson.toJson(persons);
System.out.println(json);
//output: [{"name":"Tom","age":11},{"name":"Jack","age":12}]
Person[] personsFromJson = gson.fromJson(json, Person[].class);
//...
class Person {
     public String name;
     public int age;
} 

Gson allows converting List directly. Examples can be easily googled. I prefer to convert lists to arrays first.

Convert a python dict to a string and back

Convert dictionary into JSON (string)

import json 

mydict = { "name" : "Don", 
          "surname" : "Mandol", 
          "age" : 43} 

result = json.dumps(mydict)

print(result[0:20])

will get you:

{"name": "Don", "sur

Convert string into dictionary

back_to_mydict = json.loads(result) 

Ruby objects and JSON serialization (without Rails)

Actually, there is a gem called Jsonable, https://github.com/treeder/jsonable. It's pretty sweet.

How to send objects through bundle

You could use the global application state.

Update:

Customize and then add this to your AndroidManifest.xml :

<application android:label="@string/app_name" android:debuggable="true" android:name=".CustomApplication"

And then have a class in your project like this :

package com.example;

import android.app.Application;

public class CustomApplication extends Application {
    public int someVariable = -1;
}

And because "It can be accessed via getApplication() from any Activity or Service", you use it like this:

CustomApplication application = (CustomApplication)getApplication();
application.someVariable = 123; 

Hope that helps.

form serialize javascript (no framework)

I could be crazy but I'm finding these answers seriously bloated. Here's my solution

function serialiseForm(form) {
  var input = form.getElementsByTagName("input");
  var formData = {};
  for (var i = 0; i < input.length; i++) {
    formData[input[i].name] = input[i].value;
  }
  return formData = JSON.stringify(formData);
}

Saving an Object (Data persistence)

Quick example using company1 from your question, with python3.

import pickle

# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))

However, as this answer noted, pickle often fails. So you should really use dill.

import dill

# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))

How do you do a deep copy of an object in .NET?

I wrote a deep object copy extension method, based on recursive "MemberwiseClone". It is fast (three times faster than BinaryFormatter), and it works with any object. You don't need a default constructor or serializable attributes.

Source code:

using System.Collections.Generic;
using System.Reflection;
using System.ArrayExtensions;

namespace System
{
    public static class ObjectExtensions
    {
        private static readonly MethodInfo CloneMethod = typeof(Object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);

        public static bool IsPrimitive(this Type type)
        {
            if (type == typeof(String)) return true;
            return (type.IsValueType & type.IsPrimitive);
        }

        public static Object Copy(this Object originalObject)
        {
            return InternalCopy(originalObject, new Dictionary<Object, Object>(new ReferenceEqualityComparer()));
        }
        private static Object InternalCopy(Object originalObject, IDictionary<Object, Object> visited)
        {
            if (originalObject == null) return null;
            var typeToReflect = originalObject.GetType();
            if (IsPrimitive(typeToReflect)) return originalObject;
            if (visited.ContainsKey(originalObject)) return visited[originalObject];
            if (typeof(Delegate).IsAssignableFrom(typeToReflect)) return null;
            var cloneObject = CloneMethod.Invoke(originalObject, null);
            if (typeToReflect.IsArray)
            {
                var arrayType = typeToReflect.GetElementType();
                if (IsPrimitive(arrayType) == false)
                {
                    Array clonedArray = (Array)cloneObject;
                    clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));
                }

            }
            visited.Add(originalObject, cloneObject);
            CopyFields(originalObject, visited, cloneObject, typeToReflect);
            RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);
            return cloneObject;
        }

        private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect)
        {
            if (typeToReflect.BaseType != null)
            {
                RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);
                CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate);
            }
        }

        private static void CopyFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func<FieldInfo, bool> filter = null)
        {
            foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))
            {
                if (filter != null && filter(fieldInfo) == false) continue;
                if (IsPrimitive(fieldInfo.FieldType)) continue;
                var originalFieldValue = fieldInfo.GetValue(originalObject);
                var clonedFieldValue = InternalCopy(originalFieldValue, visited);
                fieldInfo.SetValue(cloneObject, clonedFieldValue);
            }
        }
        public static T Copy<T>(this T original)
        {
            return (T)Copy((Object)original);
        }
    }

    public class ReferenceEqualityComparer : EqualityComparer<Object>
    {
        public override bool Equals(object x, object y)
        {
            return ReferenceEquals(x, y);
        }
        public override int GetHashCode(object obj)
        {
            if (obj == null) return 0;
            return obj.GetHashCode();
        }
    }

    namespace ArrayExtensions
    {
        public static class ArrayExtensions
        {
            public static void ForEach(this Array array, Action<Array, int[]> action)
            {
                if (array.LongLength == 0) return;
                ArrayTraverse walker = new ArrayTraverse(array);
                do action(array, walker.Position);
                while (walker.Step());
            }
        }

        internal class ArrayTraverse
        {
            public int[] Position;
            private int[] maxLengths;

            public ArrayTraverse(Array array)
            {
                maxLengths = new int[array.Rank];
                for (int i = 0; i < array.Rank; ++i)
                {
                    maxLengths[i] = array.GetLength(i) - 1;
                }
                Position = new int[array.Rank];
            }

            public bool Step()
            {
                for (int i = 0; i < Position.Length; ++i)
                {
                    if (Position[i] < maxLengths[i])
                    {
                        Position[i]++;
                        for (int j = 0; j < i; j++)
                        {
                            Position[j] = 0;
                        }
                        return true;
                    }
                }
                return false;
            }
        }
    }

}

Exception: Serialization of 'Closure' is not allowed

Apparently anonymous functions cannot be serialized.

Example

$function = function () {
    return "ABC";
};
serialize($function); // would throw error

From your code you are using Closure:

$callback = function () // <---------------------- Issue
{
    return 'ZendMail_' . microtime(true) . '.tmp';
};

Solution 1 : Replace with a normal function

Example

function emailCallback() {
    return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;

Solution 2 : Indirect method call by array variable

If you look at http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html

   public function __construct($options = null)
   63     {
   64         if ($options instanceof Zend_Config) {
   65             $options = $options->toArray();
   66         } elseif (!is_array($options)) {
   67             $options = array();
   68         }
   69 
   70         // Making sure we have some defaults to work with
   71         if (!isset($options['path'])) {
   72             $options['path'] = sys_get_temp_dir();
   73         }
   74         if (!isset($options['callback'])) {
   75             $options['callback'] = array($this, 'defaultCallback'); <- here
   76         }
   77 
   78         $this->setOptions($options);
   79     }

You can use the same approach to send the callback

$callback = array($this,"aMethodInYourClass");

.NET NewtonSoft JSON deserialize map to a different property name

Json.NET has a JsonPropertyAttribute which allows you to specify the name of a JSON property, so your code should be:

public class TeamScore
{
    [JsonProperty("eighty_min_score")]
    public string EightyMinScore { get; set; }
    [JsonProperty("home_or_away")]
    public string HomeOrAway { get; set; }
    [JsonProperty("score ")]
    public string Score { get; set; }
    [JsonProperty("team_id")]
    public string TeamId { get; set; }
}

public class Team
{
    public string v1 { get; set; }
    [JsonProperty("attributes")]
    public TeamScore TeamScores { get; set; }
}

public class RootObject
{
    public List<Team> Team { get; set; }
}

Documentation: Serialization Attributes

Serializing to JSON in jQuery

No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.

If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.

EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.

laravel Unable to prepare route ... for serialization. Uses Closure

Check your routes/web.php and routes/api.php

Laravel comes with default route closure in routes/web.php:

Route::get('/', function () {
    return view('welcome');
});

and routes/api.php

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

if you remove that then try again to clear route cache.

Converting any object to a byte array in java

As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.

Serializing class instance to JSON

I just do:

data=json.dumps(myobject.__dict__)

This is not the full answer, and if you have some sort of complicated object class you certainly will not get everything. However I use this for some of my simple objects.

One that it works really well on is the "options" class that you get from the OptionParser module. Here it is along with the JSON request itself.

  def executeJson(self, url, options):
        data=json.dumps(options.__dict__)
        if options.verbose:
            print data
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        return requests.post(url, data, headers=headers)

How do I serialize a Python dictionary into a string, and then back to a dictionary?

If you are trying to only serialize then pprint may also be a good option. It requires the object to be serialized and a file stream.

Here's some code:

from pprint import pprint
my_dict = {1:'a',2:'b'}
with open('test_results.txt','wb') as f:
    pprint(my_dict,f)

I am not sure if we can deserialize easily. I was using json to serialize and deserialze earlier which works correctly in most cases.

f.write(json.dumps(my_dict, sort_keys = True, indent = 2, ensure_ascii=True))

However, in one particular case, there were some errors writing non-unicode data to json.

What are Transient and Volatile Modifiers?

The volatile and transient modifiers can be applied to fields of classes1 irrespective of field type. Apart from that, they are unrelated.

The transient modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null for a reference type, and zero or false for a primitive type. Note that the JLS (see 8.3.1.3) does not say what transient means, but defers to the Java Object Serialization Specification. Other serialization mechanisms may pay attention to a field's transient-ness. Or they may ignore it.

(Note that the JLS permits a static field to be declared as transient. This combination doesn't make sense for Java Object Serialization, since it doesn't serialize statics anyway. However, it could make sense in other contexts, so there is some justification for not forbidding it outright.)

The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. Similarly, reads and writes to volatile fields are atomic. (This does not apply to >>non-volatile<< long or double fields, which may be subject to "word tearing" on some JVMs.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.


1 - But not to local variables or parameters.

Converting Stream to String and back...what are we missing?

When you testing try with UTF8 Encode stream like below

var stream = new MemoryStream();
var streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8);
Serializer.Serialize<SuperExample>(streamWriter, test);

Entity framework self referencing loop detected

I might also look into adding explicit samples for each controller/action, as well covered here:

http://blogs.msdn.com/b/yaohuang1/archive/2012/10/13/asp-net-web-api-help-page-part-2-providing-custom-samples-on-the-help-page.aspx

i.e. config.SetActualResponseType(typeof(SomeType), "Values", "Get");

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

Parsing JSON using Json.net

(This question came up high on a search engine result, but I ended up using a different approach. Adding an answer to this old question in case other people with similar questions read this)

You can solve this with Json.Net and make an extension method to handle the items you want to loop:

public static Tuple<string, int, int> ToTuple(this JToken token)
{
    var type = token["attributes"]["OBJECT_TYPE"].ToString();
    var x = token["position"]["x"].Value<int>();
    var y = token["position"]["y"].Value<int>();
    return new Tuple<string, int, int>(type, x, y);
}

And then access the data like this: (scenario: writing to console):

var tuples = JObject.Parse(myJsonString)["objects"].Select(item => item.ToTuple()).ToList();
tuples.ForEach(t => Console.WriteLine("{0}: ({1},{2})", t.Item1, t.Item2, t.Item3));

How to get string objects instead of Unicode from JSON?

While there are some good answers here, I ended up using PyYAML to parse my JSON files, since it gives the keys and values as str type strings instead of unicode type. Because JSON is a subset of YAML it works nicely:

>>> import json
>>> import yaml
>>> list_org = ['a', 'b']
>>> list_dump = json.dumps(list_org)
>>> list_dump
'["a", "b"]'
>>> json.loads(list_dump)
[u'a', u'b']
>>> yaml.safe_load(list_dump)
['a', 'b']

Notes

Some things to note though:

  • I get string objects because all my entries are ASCII encoded. If I would use unicode encoded entries, I would get them back as unicode objects — there is no conversion!

  • You should (probably always) use PyYAML's safe_load function; if you use it to load JSON files, you don't need the "additional power" of the load function anyway.

  • If you want a YAML parser that has more support for the 1.2 version of the spec (and correctly parses very low numbers) try Ruamel YAML: pip install ruamel.yaml and import ruamel.yaml as yaml was all I needed in my tests.

Conversion

As stated, there is no conversion! If you can't be sure to only deal with ASCII values (and you can't be sure most of the time), better use a conversion function:

I used the one from Mark Amery a couple of times now, it works great and is very easy to use. You can also use a similar function as an object_hook instead, as it might gain you a performance boost on big files. See the slightly more involved answer from Mirec Miskuf for that.

When should we implement Serializable interface?

  1. From What's this "serialization" thing all about?:

    It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).

    Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."

    So, implement the Serializable interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.

  2. Because you want to store or send an object.

  3. It makes storing and sending objects easy. It has nothing to do with security.

Cannot deserialize the current JSON array (e.g. [1,2,3])

This could be You

Before trying to consume your json object with another object just check that the api is returning raw json via the browser api/rootobject, for my case i found out that the underlying data provider mssqlserver was not running and throw an unhanded exception !

as simple as that :)

How do I copy a hash in Ruby?

Since standard cloning method preserves the frozen state, it is not suitable for creating new immutable objects basing on the original object, if you would like the new objects be slightly different than the original (if you like stateless programming).

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

Complete talk fully explaining the problem, which proposes a great paradigm shifting way to avoid these serialization problems: https://github.com/samthebest/dump/blob/master/sams-scala-tutorial/serialization-exceptions-and-memory-leaks-no-ws.md

The top voted answer is basically suggesting throwing away an entire language feature - that is no longer using methods and only using functions. Indeed in functional programming methods in classes should be avoided, but turning them into functions isn't solving the design issue here (see above link).

As a quick fix in this particular situation you could just use the @transient annotation to tell it not to try to serialise the offending value (here, Spark.ctx is a custom class not Spark's one following OP's naming):

@transient
val rddList = Spark.ctx.parallelize(list)

You can also restructure code so that rddList lives somewhere else, but that is also nasty.

The Future is Probably Spores

In future Scala will include these things called "spores" that should allow us to fine grain control what does and does not exactly get pulled in by a closure. Furthermore this should turn all mistakes of accidentally pulling in non-serializable types (or any unwanted values) into compile errors rather than now which is horrible runtime exceptions / memory leaks.

http://docs.scala-lang.org/sips/pending/spores.html

A tip on Kryo serialization

When using kyro, make it so that registration is necessary, this will mean you get errors instead of memory leaks:

"Finally, I know that kryo has kryo.setRegistrationOptional(true) but I am having a very difficult time trying to figure out how to use it. When this option is turned on, kryo still seems to throw exceptions if I haven't registered classes."

Strategy for registering classes with kryo

Of course this only gives you type-level control not value-level control.

... more ideas to come.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

Quick Fix

Recalculating the length of the elements in serialized array - but don't use (preg_replace) it's deprecated - better use preg_replace_callback:

Edit: New Version now not just wrong length but it also fix line-breaks and count correct characters with aczent (thanks to mickmackusa)

// New Version
$data = preg_replace_callback('!s:\d+:"(.*?)";!s', function($m) { return "s:" . strlen($m[1]) . ':"'.$m[1].'";'; }, $data);

How to Deserialize XML document

The following snippet should do the trick (and you can ignore most of the serialization attributes):

public class Car
{
  public string StockNumber { get; set; }
  public string Make { get; set; }
  public string Model { get; set; }
}

[XmlRootAttribute("Cars")]
public class CarCollection
{
  [XmlElement("Car")]
  public Car[] Cars { get; set; }
}

...

using (TextReader reader = new StreamReader(path))
{
  XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
  return (CarCollection) serializer.Deserialize(reader);
}

Jackson JSON custom serialization for certain fields

jackson-annotations provides @JsonFormat which can handle a lot of customizations without the need to write the custom serializer.

For example, requesting a STRING shape for a field with numeric type will output the numeric value as string

public class Person {
    public String name;
    public int age;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public int favoriteNumber;
}

will result in the desired output

{"name":"Joe","age":25,"favoriteNumber":"123"}

Convert a JSON string to object in Java ME?

JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.

If you click the html links there you can find anything you want.

In short:

to create a json object and a json array, the code is:

JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);

o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.

The reverse process is fairly simple, I mean converting a string to json object/array.

String myString;

JSONObject obj = new JSONObject(myString);

JSONArray array = new JSONArray(myString);

In order to be correctly parsed you just have to know if you are parsing an array or an object.

Converting between strings and ArrayBuffers

  stringToArrayBuffer(byteString) {
    var byteArray = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
      byteArray[i] = byteString.codePointAt(i);
    }
    return byteArray;
  }
  arrayBufferToString(buffer) {
    var byteArray = new Uint8Array(buffer);
    var byteString = '';
    for (var i = 0; i < byteArray.byteLength; i++) {
      byteString += String.fromCodePoint(byteArray[i]);
    }
    return byteString;
  }

Converting an object to a string

In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.

For example the following would convert all items in "value" to a string:

$.each(this, function (name, value) {
  alert(String(value));
});

More details here:

http://www.w3schools.com/jsref/jsref_string.asp

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

Just come across it and got an answer somewhere. you can use below annotation since 2.7.0

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Point {
    final private double x;
    final private double y;

    @ConstructorProperties({"x", "y"})
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

Form submit with AJAX passing form data to PHP without page refresh

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {
        $('form').bind('click', function (event) {
        // using this page stop being refreshing 
        event.preventDefault();

          $.ajax({
            type: 'POST',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

PHP

<?php

if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}

echo $time."<br>";
echo $date;
}
?>

JSON.Net Self referencing loop detected

If using ASP.NET Core MVC, add this to the ConfigureServices method of your startup.cs file:

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling =            
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

Deserialize from string instead TextReader

public static string XmlSerializeToString(this object objectInstance)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
    {
        serializer.Serialize(writer, objectInstance);
    }

    return sb.ToString();
}

public static T XmlDeserializeFromString<T>(this string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
    {
        result = serializer.Deserialize(reader);
    }

    return result;
}

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>(); 

Is it possible to serialize and deserialize a class in C++?

The Boost::serialization library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here.

The only native way to do it is to use streams. That's essentially all the Boost::serialization library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format.

For built-in types, or your own types with operator<< and operator>> properly defined, that's fairly simple; see the C++ FAQ for more information.

What is a serialVersionUID and why should I use it?

If you get this warning on a class you don't ever think about serializing, and that you didn't declare yourself implements Serializable, it is often because you inherited from a superclass, which implements Serializable. Often then it would be better to delegate to such a object instead of using inheritance.

So, instead of

public class MyExample extends ArrayList<String> {

    public MyExample() {
        super();
    }
    ...
}

do

public class MyExample {
    private List<String> myList;

    public MyExample() {
         this.myList = new ArrayList<String>();
    }
    ...
}

and in the relevant methods call myList.foo() instead of this.foo() (or super.foo()). (This does not fit in all cases, but still quite often.)

I often see people extending JFrame or such, when they really only need to delegate to this. (This also helps for auto-completing in a IDE, since JFrame has hundreds of methods, which you don't need when you want to call your custom ones on your class.)

One case where the warning (or the serialVersionUID) is unavoidable is when you extend from AbstractAction, normally in a anonymous class, only adding the actionPerformed-method. I think there shouldn't be a warning in this case (since you normally can't reliable serialize and deserialize such anonymous classes anyway accross different versions of your class), but I'm not sure how the compiler could recognize this.

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

How to deserialize a JObject to .NET object

From the documentation I found this

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

The class definition for Person should be compatible to the following:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

Gson: How to exclude specific fields from Serialization without annotations

Kotlin's @Transientannotation also does the trick apparently.

data class Json(
    @field:SerializedName("serialized_field_1") val field1: String,
    @field:SerializedName("serialized_field_2") val field2: String,
    @Transient val field3: String
)

Output:

{"serialized_field_1":"VALUE1","serialized_field_2":"VALUE2"}

Best way to save a trained model in PyTorch?

It depends on what you want to do.

Case # 1: Save the model to use it yourself for inference: You save the model, you restore it, and then you change the model to evaluation mode. This is done because you usually have BatchNorm and Dropout layers that by default are in train mode on construction:

torch.save(model.state_dict(), filepath)

#Later to restore:
model.load_state_dict(torch.load(filepath))
model.eval()

Case # 2: Save model to resume training later: If you need to keep training the model that you are about to save, you need to save more than just the model. You also need to save the state of the optimizer, epochs, score, etc. You would do it like this:

state = {
    'epoch': epoch,
    'state_dict': model.state_dict(),
    'optimizer': optimizer.state_dict(),
    ...
}
torch.save(state, filepath)

To resume training you would do things like: state = torch.load(filepath), and then, to restore the state of each individual object, something like this:

model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])

Since you are resuming training, DO NOT call model.eval() once you restore the states when loading.

Case # 3: Model to be used by someone else with no access to your code: In Tensorflow you can create a .pb file that defines both the architecture and the weights of the model. This is very handy, specially when using Tensorflow serve. The equivalent way to do this in Pytorch would be:

torch.save(model, filepath)

# Then later:
model = torch.load(filepath)

This way is still not bullet proof and since pytorch is still undergoing a lot of changes, I wouldn't recommend it.

What is [Serializable] and when should I use it?

What is it?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.

Uses for Serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Apply SerializableAttribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute even if the class also implements the ISerializable interface to control the serialization process.

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute to that field.

See MSDN for more details.

Edit 1

Any reason to not mark something as serializable

When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.

jQuery serialize does not register checkboxes

The trick is to intercept the form post and change the check boxes to hidden input fields.

Example: Plain Submit

$('form').on("submit", function (e) {
    //find the checkboxes
    var $checkboxes = $(this).find('input[type=checkbox]');

    //loop through the checkboxes and change to hidden fields
    $checkboxes.each(function() {
        if ($(this)[0].checked) {
            $(this).attr('type', 'hidden');
            $(this).val(1);
        } else {
            $(this).attr('type', 'hidden');
            $(this).val(0);
        }
    });
});

Example: AJAX

You need to jump through a few more hoops if you are posting the form via ajax to not update the UI.

$('form').on("submit", function (e) {
    e.preventDefault();

    //clone the form, we don't want this to impact the ui
    var $form = $('form').clone();

    //find the checkboxes
    var $checkboxes = $form.find('input[type=checkbox]');

    //loop through the checkboxes and change to hidden fields
    $checkboxes.each(function() {
        if ($(this)[0].checked) {
            $(this).attr('type', 'hidden');
            $(this).val(1);
        } else {
            $(this).attr('type', 'hidden');
            $(this).val(0);
        }
    });

    $.post("/your/path", $form.serialize());

How do I serialize an object and save it to a file in Android?

Saving (w/o exception handling code):

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

Loading (w/o exception handling code):

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();

How can I change property names when serializing with Json.net?

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

JavaScriptSerializer.Deserialize - how to change field names

There is no standard support for renaming properties in JavaScriptSerializer however you can quite easily add your own:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Reflection;

public class JsonConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        List<MemberInfo> members = new List<MemberInfo>();
        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        object obj = Activator.CreateInstance(type);

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));

            if (jsonProperty != null && dictionary.ContainsKey(jsonProperty.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[jsonProperty.Name]);
            }
            else if (dictionary.ContainsKey(member.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[member.Name]);
            }
            else
            {
                KeyValuePair<string, object> kvp = dictionary.FirstOrDefault(x => string.Equals(x.Key, member.Name, StringComparison.InvariantCultureIgnoreCase));

                if (!kvp.Equals(default(KeyValuePair<string, object>)))
                {
                    SetMemberValue(serializer, member, obj, kvp.Value);
                }
            }
        }

        return obj;
    }


    private void SetMemberValue(JavaScriptSerializer serializer, MemberInfo member, object obj, object value)
    {
        if (member is PropertyInfo)
        {
            PropertyInfo property = (PropertyInfo)member;                
            property.SetValue(obj, serializer.ConvertToType(value, property.PropertyType), null);
        }
        else if (member is FieldInfo)
        {
            FieldInfo field = (FieldInfo)member;
            field.SetValue(obj, serializer.ConvertToType(value, field.FieldType));
        }
    }


    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Type type = obj.GetType();
        List<MemberInfo> members = new List<MemberInfo>();
        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        Dictionary<string, object> values = new Dictionary<string, object>();

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));

            if (jsonProperty != null)
            {
                values[jsonProperty.Name] = GetMemberValue(member, obj);
            }
            else
            {
                values[member.Name] = GetMemberValue(member, obj);
            }
        }

        return values;
    }

    private object GetMemberValue(MemberInfo member, object obj)
    {
        if (member is PropertyInfo)
        {
            PropertyInfo property = (PropertyInfo)member;
            return property.GetValue(obj, null);
        }
        else if (member is FieldInfo)
        {
            FieldInfo field = (FieldInfo)member;
            return field.GetValue(obj);
        }

        return null;
    }


    public override IEnumerable<Type> SupportedTypes
    {
        get 
        {
            return new[] { typeof(DataObject) };
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class JsonPropertyAttribute : Attribute
{
    public JsonPropertyAttribute(string name)
    {
        Name = name;
    }

    public string Name
    {
        get;
        set;
    }
}

The DataObject class then becomes:

public class DataObject
{
    [JsonProperty("user_id")]
    public int UserId { get; set; }

    [JsonProperty("detail_level")]
    public DetailLevel DetailLevel { get; set; }
}

I appreicate this might be a little late but thought other people wanting to use the JavaScriptSerializer rather than the DataContractJsonSerializer might appreciate it.

Convert form data to JavaScript object with jQuery

If you are sending a form with JSON you must remove [] in sending the string. You can do that with the jQuery function serializeObject():

var frm = $(document.myform);
var data = JSON.stringify(frm.serializeObject());

$.fn.serializeObject = function() {
    var o = {};
    //var a = this.serializeArray();
    $(this).find('input[type="hidden"], input[type="text"], input[type="password"], input[type="checkbox"]:checked, input[type="radio"]:checked, select').each(function() {
        if ($(this).attr('type') == 'hidden') { //If checkbox is checked do not take the hidden field
            var $parent = $(this).parent();
            var $chb = $parent.find('input[type="checkbox"][name="' + this.name.replace(/\[/g, '\[').replace(/\]/g, '\]') + '"]');
            if ($chb != null) {
                if ($chb.prop('checked')) return;
            }
        }
        if (this.name === null || this.name === undefined || this.name === '')
            return;
        var elemValue = null;
        if ($(this).is('select'))
            elemValue = $(this).find('option:selected').val();
        else
            elemValue = this.value;
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(elemValue || '');
        }
        else {
            o[this.name] = elemValue || '';
        }
    });
    return o;
}

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

Convert Dictionary to JSON in Swift

Here's an easy extension to do this:

https://gist.github.com/stevenojo/0cb8afcba721838b8dcb115b846727c3

extension Dictionary {
    func jsonString() -> NSString? {
        let jsonData = try? JSONSerialization.data(withJSONObject: self, options: [])
        guard jsonData != nil else {return nil}
        let jsonString = String(data: jsonData!, encoding: .utf8)
        guard jsonString != nil else {return nil}
        return jsonString! as NSString
    }

}

How to JSON serialize sets?

JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.

As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s) then you lose the ability to recover dictionaries).

A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:

from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

Here is a sample session showing that it can handle lists, dicts, and sets:

>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]

>>> j = dumps(data, cls=PythonObjectEncoder)

>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]

Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.

How to write and read java serialized objects into a file

Why not serialize the whole list at once?

FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);

Assuming, of course, that MyClassList is an ArrayList or LinkedList, or another Serializable collection.

In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.

Why should I prefer to use member initialization lists?

Syntax:

  class Sample
  {
     public:
         int Sam_x;
         int Sam_y;

     Sample(): Sam_x(1), Sam_y(2)     /* Classname: Initialization List */
     {
           // Constructor body
     }
  };

Need of Initialization list:

 class Sample
 {
     public:
         int Sam_x;
         int Sam_y;

     Sample()     */* Object and variables are created - i.e.:declaration of variables */*
     { // Constructor body starts 

         Sam_x = 1;      */* Defining a value to the variable */* 
         Sam_y = 2;

     } // Constructor body ends
  };

in the above program, When the class’s constructor is executed, Sam_x and Sam_y are created. Then in constructor body, those member data variables are defined.

Use cases:

  1. Const and Reference variables in a Class

In C, variables must be defined during creation. the same way in C++, we must initialize the Const and Reference variable during object creation by using Initialization list. if we do initialization after object creation (Inside constructor body), we will get compile time error.

  1. Member objects of Sample1 (base) class which do not have default constructor

     class Sample1 
     {
         int i;
         public:
         Sample1 (int temp)
         {
            i = temp;
         }
     };
    
      // Class Sample2 contains object of Sample1 
     class Sample2
     {
      Sample1  a;
      public:
      Sample2 (int x): a(x)      /* Initializer list must be used */
      {
    
      }
     };
    

While creating object for derived class which will internally calls derived class constructor and calls base class constructor (default). if base class does not have default constructor, user will get compile time error. To avoid, we must have either

 1. Default constructor of Sample1 class
 2. Initialization list in Sample2 class which will call the parametric constructor of Sample1 class (as per above program)
  1. Class constructor’s parameter name and Data member of a Class are same:

     class Sample3 {
        int i;         /* Member variable name : i */  
        public:
        Sample3 (int i)    /* Local variable name : i */ 
        {
            i = i;
            print(i);   /* Local variable: Prints the correct value which we passed in constructor */
        }
        int getI() const 
        { 
             print(i);    /*global variable: Garbage value is assigned to i. the expected value should be which we passed in constructor*/
             return i; 
        }
     };
    

As we all know, local variable having highest priority then global variable if both variables are having same name. In this case, the program consider "i" value {both left and right side variable. i.e: i = i} as local variable in Sample3() constructor and Class member variable(i) got override. To avoid, we must use either

  1. Initialization list 
  2. this operator.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

It's an invisible folder. Just hit Command + Shift + G (takes you to the Go to Folder menu item) and type /etc/.

Then it will take you to inside that folder.

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

Internet Access in Ubuntu on VirtualBox

How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.

File content into unix variable with newlines

This is due to IFS (Internal Field Separator) variable which contains newline.

$ cat xx1
1
2

$ A=`cat xx1`
$ echo $A
1 2

$ echo "|$IFS|"
|       
|

A workaround is to reset IFS to not contain the newline, temporarily:

$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK

To REVERT this horrible change for IFS:

IFS=$IFSBAK

How to change the background color on a Java panel?

I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I noticed following line from error.

exact fetch returns more than requested number of rows

That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

So, I truncated dual table and inserted only row which X value. And, everything working fine.

How do I concatenate text in a query in sql server?

The only way would be to convert your text field into an nvarchar field.

Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a

Otherwise, I suggest doing the concatenation in your application.

How do I set the colour of a label (coloured text) in Java?

object.setForeground(Color.green);

*any colour you wish *object being declared earlier

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

How to get tf.exe (TFS command line client)?

Following on from the earlier answers above but based on a VS 2019 install ;
I needed to run "tf git permission" commands, and copied the following files from:

C:\Program Files (x86)\Microsoft Visual Studio\2019\TeamExplorer\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer

Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.Diff.dll
Microsoft.TeamFoundation.Git.Client.dll
Microsoft.TeamFoundation.Git.Contracts.dll
Microsoft.TeamFoundation.Git.Controls.dll
Microsoft.TeamFoundation.Git.CoreServices.dll
Microsoft.TeamFoundation.Git.dll
Microsoft.TeamFoundation.Git.Graph.dll
Microsoft.TeamFoundation.Git.HostingProvider.AzureDevOps.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.imagemanifest
Microsoft.TeamFoundation.Git.Provider.dll
Microsoft.TeamFoundation.SourceControl.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Common.Integration.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll
TF.exe
TF.exe.config

How to display the current time and date in C#

DateTime.Now.Tostring();

. You can supply parameters to To string function in a lot of ways like given in this link http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

This will be a lot useful. If you reside somewhere else than the regular format (MM/dd/yyyy)

use always MM not mm, mm gives minutes and MM gives month.

In Python, how do I split a string and keep the separators?

You can also split a string with an array of strings instead of a regular expression, like this:

def tokenizeString(aString, separators):
    #separators is an array of strings that are being used to split the string.
    #sort separators in order of descending length
    separators.sort(key=len)
    listToReturn = []
    i = 0
    while i < len(aString):
        theSeparator = ""
        for current in separators:
            if current == aString[i:i+len(current)]:
                theSeparator = current
        if theSeparator != "":
            listToReturn += [theSeparator]
            i = i + len(theSeparator)
        else:
            if listToReturn == []:
                listToReturn = [""]
            if(listToReturn[-1] in separators):
                listToReturn += [""]
            listToReturn[-1] += aString[i]
            i += 1
    return listToReturn
    

print(tokenizeString(aString = "\"\"\"hi\"\"\" hello + world += (1*2+3/5) '''hi'''", separators = ["'''", '+=', '+', "/", "*", "\\'", '\\"', "-=", "-", " ", '"""', "(", ")"]))

What's the right way to pass form element state to sibling/parent elements?

  1. The right thing to do is to have the state in the parent component, to avoid ref and what not
  2. An issue is to avoid constantly updating all children when typing into a field
  3. Therefore, each child should be a Component (as in not a PureComponent) and implement shouldComponentUpdate(nextProps, nextState)
  4. This way, when typing into a form field, only that field updates

The code below uses @bound annotations from ES.Next babel-plugin-transform-decorators-legacy of BabelJS 6 and class-properties (the annotation sets this value on member functions similar to bind):

/*
© 2017-present Harald Rudell <[email protected]> (http://www.haraldrudell.com)
All rights reserved.
*/
import React, {Component} from 'react'
import {bound} from 'class-bind'

const m = 'Form'

export default class Parent extends Component {
  state = {one: 'One', two: 'Two'}

  @bound submit(e) {
    e.preventDefault()
    const values = {...this.state}
    console.log(`${m}.submit:`, values)
  }

  @bound fieldUpdate({name, value}) {
    this.setState({[name]: value})
  }

  render() {
    console.log(`${m}.render`)
    const {state, fieldUpdate, submit} = this
    const p = {fieldUpdate}
    return (
      <form onSubmit={submit}> {/* loop removed for clarity */}
        <Child name='one' value={state.one} {...p} />
        <Child name='two' value={state.two} {...p} />
        <input type="submit" />
      </form>
    )
  }
}

class Child extends Component {
  value = this.props.value

  @bound update(e) {
    const {value} = e.target
    const {name, fieldUpdate} = this.props
    fieldUpdate({name, value})
  }

  shouldComponentUpdate(nextProps) {
    const {value} = nextProps
    const doRender = value !== this.value
    if (doRender) this.value = value
    return doRender
  }

  render() {
    console.log(`Child${this.props.name}.render`)
    const {value} = this.props
    const p = {value}
    return <input {...p} onChange={this.update} />
  }
}

Storing SHA1 hash values in MySQL

If you need an index on the sha1 column, I suggest CHAR(40) for performance reasons. In my case the sha1 column is an email confirmation token, so on the landing page the query enters only with the token. In this case CHAR(40) with INDEX, in my opinion, is the best choice :)

If you want to adopt this method, remember to leave $raw_output = false.

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

Access elements of parent window from iframe

I think you can just use window.parent from the iframe. window.parent returns the window object of the parent page, so you could do something like:

window.parent.document.getElementById('yourdiv');

Then do whatever you want with that div.

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

In Git, how do I figure out what my current revision is?

This gives you the first few digits of the hash and they are unique enough to use as say a version number.

git rev-parse --short HEAD

Replace new lines with a comma delimiter with Notepad++?

USE Chrome's Search Bar

1-press CTRL F
2-paste the copied text in search bar
3-press CTRL A followed by CTRL C to copy the text again from search
4-paste in Notepad++
5-replace 'space' with ','

1-click for image
2-click for image

How to install gdb (debugger) in Mac OSX El Capitan?

Please note that this answer was written for Mac OS El Capitan. For newer versions, beware that it may no longer apply. In particular, the legacy option is quite possibly deprecated.

There are two solutions to the problem, and they are both mentioned in other answers to this question and to How to get gdb to work using macports under OSX 10.11 El Capitan?, but to clear up some confusion here is my summary (as an answer since it got a bit long for a comment):

Which alternative is more secure I guess boils down to the choice between 1) trusting self-signed certificates and 2) giving users more privileges.

Alternative 1: signing the binary

If the signature alternative is used, disabling SIP to add the -p option to taskgated is not required.

However, note that with this alternative, debugging is only allowed for users in the _developer group.

Using codesign to sign using a cert named gdb-cert:

codesign -s gdb-cert /opt/local/bin/ggdb

(using the MacPorts standard path, adopt as necessary)

For detailed code-signing recipes (incl cert creation), see : https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html or https://sourceware.org/gdb/wiki/BuildingOnDarwin

Note that you need to restart the keychain application and the taskgated service during and after the process (the easiest way is to reboot).

Alternative 2: use the legacy option for taskgated

As per the answer by @user14241, disabling SIP and adding the -p option to taskgated is an option. Note that if using this option, signing the binary is not needed, and it also bypasses the dialog for authenticating as a member of the Developer Tools group (_developer).

After adding the -p option (allow groups procmod and procview) to taskgated you also need to add the users that should be allowed to use gdb to the procmod group.

The recipe is:

  1. restart in recovery mode, open a terminal and run csrutil disable

  2. restart machine and edit /System/Library/LaunchDaemons/com.apple.taskgated.plist, adding the -p opion:

    <array>
        <string>/usr/libexec/taskgated</string>
        <string>-sp</string>
    </array>
    
  3. restart in recovery mode to reenable SIP (csrutil enable)

  4. restart machine and add user USERNAME to the group procmod:

    sudo dseditgroup -o edit -a USERNAME -t user procmod

    An alternative that does not involve adding users to groups is to make the executable setgid procmod, as that also makes procmod the effective group id of any user executing the setgid binary (suggested in https://apple.stackexchange.com/a/112132)

    sudo chgrp procmod /path/to/gdb
    sudo chmod g+s /path/to/gdb 
    

Is Visual Studio Community a 30 day trial?

I'm using Visual Studio Professional licensed over the MAPS Action Pack subscription. Since the new version of the Microsoft Partner Center one have to add the subscribed user to the partner benefit software.

Partner Center->Benefits->Visual Studio Subscriptions->Add user

After that one have to sign out and reenter the credentials in the account settings of VS.

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case I had to delete the services in my installshield project and start from square one. My original service components were added manually and I couldn't get them working, the only error I was getting was the same "Error 1920 service failed to start. Verify that you have sufficient privileges to start system services." that you were getting. After deleting my components, I re-added them using the component wizard.
enter image description here

Component Wizard looks like this

I actually had to create two new components. One was of type "Install Service".

Service Component type shown here

enter image description here

The other component I had to add was of "Control Service" type.

enter image description here

I had to choose the service that I had setup when I added the Install Service component.enter image description here

After that it worked, even though nothing looked differently from the components I had added manually. Installshield must do something behind the scenes when it wires up the service components with the component wizard.

All of this was with Install Shield 2016.

Using Node.JS, how do I read a JSON file into (server) memory?

In Node 8 you can use the built-in util.promisify() to asynchronously read a file like this

const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)

readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
  .then(contents => {
    const obj = JSON.parse(contents)
    console.log(obj)
  })
  .catch(error => {
    throw error
  })

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In Swift 4.2 and Xcode 10.1:

If you want to get the friends list from Facebook, you need to submit your app for review in Facebook. See some of the Login Permissions:

Login Permissions

Here are the two steps:

1) First your app status is must be in Live

2) Get required permissions form Facebook.

1) Enable our app status live:

  1. Go to the apps page and select your app

    https://developers.facebook.com/apps/

  2. Select status in the top right in Dashboard.

    Enter image description here

  3. Submit privacy policy URL

    Enter image description here

  4. Select category

    Enter image description here

  5. Now our app is in Live status.

    Enter image description here

One step is completed.

2) Submit our app for review:

  1. First send required requests.

    Example: user_friends, user_videos, user_posts, etc.

    Enter image description here

  2. Second, go to the Current Request page

    Enter image description here

    Example: user_events

  3. Submit all details

    Enter image description here

  4. Like this submit for all requests (user_friends , user_events, user_videos, user_posts, etc.).

  5. Finally submit your app for review.

    If your review is accepted from Facebook's side, you are now eligible to read contacts, etc.

Loop through an array in JavaScript

for (const s of myStringArray) {

(Directly answering your question: now you can!)

Most other answers are right, but they do not mention (as of this writing) that ECMAScript  6  2015 is bringing a new mechanism for doing iteration, the for..of loop.

This new syntax is the most elegant way to iterate an array in JavaScript (as long you don't need the iteration index).

It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JavaScript compilers (such as Babel) that allow us to use next-generation features today.

It also works on Node.js (I tested it on version 0.12.0).

Iterating an array

// You could also use "let" or "const" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) {
   console.log(letter);
}

Iterating an array of objects

const band = [
  {firstName : 'John', lastName: 'Lennon'},
  {firstName : 'Paul', lastName: 'McCartney'}
];

for(const member of band){
  console.log(member.firstName + ' ' + member.lastName);
}

Iterating a generator:

(example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)

function* fibonacci() { // A generator function
  let [prev, curr] = [1, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
  }
}

for (const n of fibonacci()) {
  console.log(n);
  // Truncate the sequence at 1000
  if (n >= 1000) {
    break;
  }
}

Compatibility table: http://kangax.github.io/es5-compat-table/es6/#For..of loops

Specification: http://wiki.ecmascript.org/doku.php?id=harmony:iterators

}

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

How can I make a menubar fixed on the top while scrolling

to set a div at position fixed you can use

position:fixed
top:0;
left:0;
width:100%;
height:50px; /* change me */

Trigger change() event when setting <select>'s value with val() function

One thing that I found out (the hard way), is that you should have

$('#selectField').change(function(){
  // some content ...
});

defined BEFORE you are using

$('#selectField').val(10).trigger('change');

or

 $('#selectField').val(10).change();

FAIL - Application at context path /Hello could not be started

I've had the same problem, was missing a slash in servlet url in web.xml

replace

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>jsonservice</url-pattern>
</servlet-mapping>

with

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>/jsonservice</url-pattern>
</servlet-mapping>

SQL RANK() versus ROW_NUMBER()

Simple query without partition clause:

select 
    sal, 
    RANK() over(order by sal desc) as Rank,
    DENSE_RANK() over(order by sal desc) as DenseRank,
    ROW_NUMBER() over(order by sal desc) as RowNumber
from employee 

Output:

    --------|-------|-----------|----------
    sal     |Rank   |DenseRank  |RowNumber
    --------|-------|-----------|----------
    5000    |1      |1          |1
    3000    |2      |2          |2
    3000    |2      |2          |3
    2975    |4      |3          |4
    2850    |5      |4          |5
    --------|-------|-----------|----------

Escaping ampersand character in SQL string

This works as well:

select * from mde_product where cfn = 'A3D"&"R01'

you define & as literal by enclosing is with double qoutes "&" in the string.

Change span text?

document.getElementById("serverTime").innerHTML = ...;

Git: how to reverse-merge a commit?

git reset --hard HEAD^ 

Use the above command to revert merge changes.

How to customise file type to syntax associations in Sublime Text?

for ST3

$language = "language u wish"

if exists,

go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

else

create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

and set

{ "extensions": [ "yourextension" ] }

This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

Merge replication. You can create the subscriber (2008) from the distributor (2008). After the database has fully synchronized, drop the subscription and the publication.

Convert 4 bytes to int

The easiest way is:

RandomAccessFile in = new RandomAccessFile("filename", "r"); 
int i = in.readInt();

-- or --

DataInputStream in = new DataInputStream(new BufferedInputStream(
    new FileInputStream("filename"))); 
int i = in.readInt();

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

One-liner if statements, how to convert this if-else-statement

If expression returns a boolean, you can just return the result of it.

Example

 return (a > b)

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

I recently encountered the same issue however I am using Windows 10 Technical Preview Build 10041 and SQL Server 2014 (Advanced).

Follow the same advice from above:

In particular, my problem was that I did not enable the TCP/IP in Sql Server Configuration Manager->SQL Server Network Configuration->Protocols for SQLEXPRESS.

Once you open it, you have to go to the IP Addresses tab and for me, changing IPAll to TCP port 1433 and deleting the TCP Dynamic Ports value worked.

Follow the other steps to make sure 1433 is listening (Use netstat -an to make sure 0.0.0.0:1433 is LISTENING.), and that you can telnet to the port from the client machine.

Finally, I second the suggestion to remove the \SQLEXPRESS from the connection.

AND ----> That last line is important! It looks like to be Windows 10 specific; remove \SQLEXPRESS from your connection string. What was frusting was that SQL Management Studio connects just fine using either connection string (full or short), however Visual Studio only accepted the connection string without the \SQLEXPRESS.

JQuery - Storing ajax response into global variable

I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.

jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.

I tried many, many, many different methods, but in the end, it was Charles Guilbert's method that worked best for me.

Hats off to Charles Guilbert! Using his answer, I am able to get data into my variables, even when my page first loads.

Here's an example of the working script:

    jQuery.extend
    (
        {
            getValues: function(url) 
            {
                var result = null;
                $.ajax(
                    {
                        url: url,
                        type: 'get',
                        dataType: 'html',
                        async: false,
                        cache: false,
                        success: function(data) 
                        {
                            result = data;
                        }
                    }
                );
               return result;
            }
        }
    );

    // Option List 1, when "Cats" is selected elsewhere
    optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");

    // Option List 1, when "Dogs" is selected elsewhere
    optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");

    // Option List 2, when "Cats" is selected elsewhere
    optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");

    // Option List 2, when "Dogs" is selected elsewhere
    optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");

Load CSV data into MySQL in Python

I think you have to do mydb.commit() all the insert into.

Something like this

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

PHP - remove <img> tag from string

simply use the form_validation class of codeigniter:

strip_image_tags($str).

$this->load->library('form_validation');
$this->form_validation->set_rules('nombre_campo', 'label', 'strip_image_tags');

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

Use Invalidations to clear the cache, you can put the path to the files you want to clear, or simply use wild cards to clear everything.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidating-objects-api

This can also be done using the API! http://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.html

The AWS PHP SDK now has the methods but if you want to use something lighter check out this library: http://www.subchild.com/2010/09/17/amazon-cloudfront-php-invalidator/

user3305600's solution doesn't work as setting it to zero is the equivalent of Using the Origin Cache Headers.

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

Disable back button in android

Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();

@Override
public void onBackPressed() {

}

Change some value inside the List<T>

You could use ForEach, but you have to convert the IEnumerable<T> to a List<T> first.

list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);

What is the JavaScript version of sleep()?

If you're on node.js, you can have a look at fibers – a native C extension to node, a kinda-multi-threading simulation.

It allows you to do a real sleep in a way which is blocking execution in a fiber, but it's non-blocking in the main thread and other fibers.

Here's an example fresh from their own readme:

// sleep.js

var Fiber = require('fibers');

function sleep(ms) {
    var fiber = Fiber.current;
    setTimeout(function() {
        fiber.run();
    }, ms);
    Fiber.yield();
}

Fiber(function() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);
}).run();
console.log('back in main');

– and the results are:

$ node sleep.js
wait... Fri Jan 21 2011 22:42:04 GMT+0900 (JST)
back in main
ok... Fri Jan 21 2011 22:42:05 GMT+0900 (JST)

Global Git ignore

Before reconfiguring the global excludes file, you might want to check what it's currently configured to, using this command:

git config --get core.excludesfile

In my case, when I ran it I saw my global excludes file was configured to

~/.gitignore_global
and there were already a couple things listed there. So in the case of the given question, it might make sense to first check for an existing excludes file, and add the new file mask to it.

Odd behavior when Java converts int to byte?

In Java, an int is 32 bits. A byte is 8 bits .

Most primitive types in Java are signed, and byte, short, int, and long are encoded in two's complement. (The char type is unsigned, and the concept of a sign is not applicable to boolean.)

In this number scheme the most significant bit specifies the sign of the number. If more bits are needed, the most significant bit ("MSB") is simply copied to the new MSB.

So if you have byte 255: 11111111 and you want to represent it as an int (32 bits) you simply copy the 1 to the left 24 times.

Now, one way to read a negative two's complement number is to start with the least significant bit, move left until you find the first 1, then invert every bit afterwards. The resulting number is the positive version of that number

For example: 11111111 goes to 00000001 = -1. This is what Java will display as the value.

What you probably want to do is know the unsigned value of the byte.

You can accomplish this with a bitmask that deletes everything but the least significant 8 bits. (0xff)

So:

byte signedByte = -1;
int unsignedByte = signedByte & (0xff);

System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);

Would print out: "Signed: -1 Unsigned: 255"

What's actually happening here?

We are using bitwise AND to mask all of the extraneous sign bits (the 1's to the left of the least significant 8 bits.) When an int is converted into a byte, Java chops-off the left-most 24 bits

1111111111111111111111111010101
&
0000000000000000000000001111111
=
0000000000000000000000001010101

Since the 32nd bit is now the sign bit instead of the 8th bit (and we set the sign bit to 0 which is positive), the original 8 bits from the byte are read by Java as a positive value.

How do I specify local .gem files in my Gemfile?

You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"

On your development machine:

bundle install

(Installs required gems and makes Gemfile.lock)

bundle package

(Caches the gems in vendor/cache)

On the server:

bundle install --local

(--local means "use the gems from vendor/cache")

How to add a line break in an Android TextView?

Tried all the above, did some research of my own resulting in the following solution for rendering linefeed escape chars:

string = string.replace("\\\n", System.getProperty("line.separator"));
  1. Using the replace method you need to filter escaped linefeeds (e.g. '\\n')

  2. Only then each instance of line feed '\n' escape chars gets rendered into the actual linefeed

For this example I used a Google Apps Scripting noSQL database (ScriptDb) with JSON formatted data.

Cheers :D

Getting CheckBoxList Item values

You can try this:-

string values = "";
foreach(ListItem item in myCBL.Items){
if(item.Selected)
{
values += item.Value.ToString() + ",";  
}
}
values = values.TrimEnd(',');  //To eliminate comma in last.

How to upgrade PowerShell version from 2.0 to 3.0

The latest PowerShell version as of Aug 2016 is PowerShell 5.1. It's bundled with Windows Management Framework 5.1.

Here's the download page for PowerShell 5.1 for all versions of Windows, including Windows 7 x64 and x86.

It is worth noting that PowerShell 5.1 is the first version available in two editions of "Desktop" and "Core". Powershell Core 6.x is cross-platform, its latest version for Jan 2019 is 6.1.2. It also works on Windows 7 SP1.

Javascript - How to extract filename from a file input control

I assume you want to strip all extensions, i.e. /tmp/test/somefile.tar.gz to somefile.

Direct approach with regex:

var filename = filepath.match(/^.*?([^\\/.]*)[^\\/]*$/)[1];

Alternative approach with regex and array operation:

var filename = filepath.split(/[\\/]/g).pop().split('.')[0];

Return index of highest value in an array

$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));

How to correctly get image from 'Resources' folder in NetBeans

This was a pain, using netBeans IDE 7.2.

  1. You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
  2. Add a resource folder to the src folder:

    • (project)
      • src
        • project package folder (contains .java files)
        • resources (whatever name you want)
        • images (optional subfolders)
  3. After the clean/build this structure is propogated into the Build folder:

    • (project)
      • build
        • classes
          • project package folder (contains generated .class files)
          • resources (your resources)
          • images (your optional subfolders)

To access the resources:

dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));

and:

if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {

worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.

Double click on the executable jar file in the dist folder. The path to the resources still works.

Setting up FTP on Amazon Cloud Server

maybe worth mentioning in addition to clone45's answer:

Fixing Write Permissions for Chrooted FTP Users in vsftpd

The vsftpd version that comes with Ubuntu 12.04 Precise does not permit chrooted local users to write by default. By default you will have this in /etc/vsftpd.conf:

chroot_local_user=YES
write_enable=YES

In order to allow local users to write, you need to add the following parameter:

allow_writeable_chroot=YES

Note: Issues with write permissions may show up as following FileZilla errors:

Error: GnuTLS error -15: An unexpected TLS packet was received.
Error: Could not connect to server

References:
Fixing Write Permissions for Chrooted FTP Users in vsftpd
VSFTPd stopped working after update

python to arduino serial read & write

First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,

C:\Python34\Scripts  

Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd will pop up. Write the below code in that cmd window,

pip install PySerial

and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.


after successfully installed the module open python IDLE and write down the bellow code and run it.

import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using        
ser = serial.Serial("COM11", 9600)
while True:
    cc=str(ser.readline())
    print(cc[2:][:-5])   

CSS to set A4 paper size

https://github.com/cognitom/paper-css seems to solve all my needs.

Paper CSS for happy printing

Front-end printing solution - previewable and live-reloadable!

Should __init__() call the parent class's __init__()?

In Python, calling the super-class' __init__ is optional. If you call it, it is then also optional whether to use the super identifier, or whether to explicitly name the super class:

object.__init__(self)

In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__.

On the other hand, for __new__, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.

How to check if a file exists from a url

You have to use CURL

function does_url_exists($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 200) {
        $status = true;
    } else {
        $status = false;
    }
    curl_close($ch);
    return $status;
}

How to implement "select all" check box in HTML?

Slightly changed version which checks and unchecks respectfully

$('#select-all').click(function(event) {
        var $that = $(this);
        $(':checkbox').each(function() {
            this.checked = $that.is(':checked');
        });
    });

How to use the COLLATE in a JOIN in SQL Server?

Correct syntax looks like this. See MSDN.

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p

  ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS 

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

While not contesting the other answers, I think the following is worthy of mentioning.

  1. The “long” (http-equiv) notation and the “short” one are equal, whichever comes first wins;
  2. Web server headers will override all the <meta> tags;
  3. BOM (Byte order mark) will override everything, and in many cases it will affect html 4 (and probably other stuff, too);
  4. If you don't declare any encoding, you will probably get your text in “fallback text encoding” that is defined your browser. Neither in Firefox nor in Chrome it's utf-8;
  5. In absence of other clues the browser will attempt to read your document as if it was in ASCII to get the encoding, so you can't use any weird encodings (utf-16 with BOM should do, though);
  6. While the specs say that the encoding declaration must be within the first 512 bytes of the document, most browsers will try reading more than that.

You can test by running echo 'HTTP/1.1 200 OK\r\nContent-type: text/html; charset=windows-1251\r\n\r\n\xef\xbb\xbf<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta charset="windows-1251"><title>??????</title></head><body>??????</body></html>' | nc -lp 4500 and pointing your browser at localhost:4500. (Of course you will want to change or remove parts. The BOM part is \xef\xbb\xbf. Be wary of the encoding of your shell.)

Please mind that it's very important that you explicitly declare the encoding. Letting browsers guess can lead to security issues.

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Using the passwd command from within a shell script

Read the wise words from:

I quote:

Nothing you can do in bash can possibly work. passwd(1) does not read from standard input. This is intentional. It is for your protection. Passwords were never intended to be put into programs, or generated by programs. They were intended to be entered only by the fingers of an actual human being, with a functional brain, and never, ever written down anywhere.

Nonetheless, we get hordes of users asking how they can circumvent 35 years of Unix security.

It goes on to explain how you can set your shadow(5) password properly, and shows you the GNU-I-only-care-about-security-if-it-doesn't-make-me-think-too-much-way of abusing passwd(1).

Lastly, if you ARE going to use the silly GNU passwd(1) extension --stdin, do not pass the password putting it on the command line.

echo $mypassword | passwd --stdin # Eternal Sin.
echo "$mypassword" | passwd --stdin # Eternal Sin, but at least you remembered to quote your PE.
passwd --stdin <<< "$mypassword" # A little less insecure, still pretty insecure, though.
passwd --stdin < "passwordfile" # With a password file that was created with a secure `umask(1)`, a little bit secure.

The last is the best you can do with GNU passwd. Though I still wouldn't recommend it.

Putting the password on the command line means anyone with even the remotest hint of access to the box can be monitoring ps or such and steal the password. Even if you think your box is safe; it's something you should really get in the habit of avoiding at all cost (yes, even the cost of doing a bit more trouble getting the job done).

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank(foo) will perform a null check for you. If you perform foo.isEmpty() and foo is null, you will raise a NullPointerException.

Commit history on remote repository

git log remotename/branchname

Will display the log of a given remote branch in that repository, but only the logs that you have "fetched" from their repository to your personal "copy" of the remote repository.

Remember that your clone of the repository will update its state of any remote branches only by doing git fetch. You can't connect directly to the server to check the log there, what you do is download the state of the server with git fetch and then locally see the log of the remote branches.

Perhaps another useful command could be:

git log HEAD..remote/branch

which will show you the commits that are in the remote branch, but not in your current branch (HEAD).

Select rows with same id but different value in another column

This ought to do it:

SELECT *
FROM YourTable
WHERE ARIDNR IN (
    SELECT ARIDNR
    FROM YourTable
    GROUP BY ARIDNR
    HAVING COUNT(*) > 1
)

The idea is to use the inner query to identify the records which have a ARIDNR value that occurs 1+ times in the data, then get all columns from the same table based on that set of values.

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

The problem is you are not in the correct directory. A simple fix in Jupyter is to do the following command:

  1. Move to the GitHub directory for your installation
  2. Run the GitHub command

Here is an example command to use in Jupyter:

%%bash
cd /home/ec2-user/ml_volume/GitHub_BMM
git show

Note you need to do the commands in the same cell.

Java integer list

code that works, but output is:

10
20
30
40
50

so:

    List<Integer> myCoords = new ArrayList<Integer>();
    myCoords.add(10);
    myCoords.add(20);
    myCoords.add(30);
    myCoords.add(40);
    myCoords.add(50);
    for (Integer number : myCoords) {
        System.out.println(number);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

Download a specific tag with Git

Use the --single-branch switch (available as of Git 1.7.10). The syntax is:

git clone -b <tag_name> --single-branch <repo_url> [<dest_dir>] 

For example:

git clone -b 'v1.9.5' --single-branch https://github.com/git/git.git git-1.9.5

The benefit: Git will receive objects and (need to) resolve deltas for the specified branch/tag only - while checking out the exact same amount of files! Depending on the source repository, this will save you a lot of disk space. (Plus, it'll be much quicker.)

Long vs Integer, long vs int, what to use and when?

Long is the Object form of long, and Integer is the object form of int.

The long uses 64 bits. The int uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1).

You should use long and int, except where you need to make use of methods inherited from Object, such as hashcode. Java.util.collections methods usually use the boxed (Object-wrapped) versions, because they need to work for any Object, and a primitive type, like int or long, is not an Object.

Another difference is that long and int are pass-by-value, whereas Long and Integer are pass-by-reference value, like all non-primitive Java types. So if it were possible to modify a Long or Integer (it's not, they're immutable without using JNI code), there would be another reason to use one over the other.

A final difference is that a Long or Integer could be null.

Android: Share plain text using intent (to all messaging apps)

This code is for sharing through sms

     String smsBody="Sms Body";
     Intent sendIntent = new Intent(Intent.ACTION_VIEW);
     sendIntent.putExtra("sms_body", smsBody);
     sendIntent.setType("vnd.android-dir/mms-sms");
     startActivity(sendIntent);

Update MongoDB field using value of another field

The best way to do this is in version 4.2+ which allows using of aggregation pipeline in the update document and the updateOne, updateMany or update collection method. Note that the latter has been deprecated in most if not all languages drivers.

MongoDB 4.2+

Version 4.2 also introduced the $set pipeline stage operator which is an alias for $addFields. I will use $set here as it maps with what we are trying to achieve.

db.collection.<update method>(
    {},
    [
        {"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
    ]
)

MongoDB 3.4+

In 3.4+ you can use $addFields and the $out aggregation pipeline operators.

db.collection.aggregate(
    [
        { "$addFields": { 
            "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
        }},
        { "$out": "collection" }
    ]
)

Note that this does not update your collection but instead replace the existing collection or create a new one. Also for update operations that require "type casting" you will need client side processing, and depending on the operation, you may need to use the find() method instead of the .aggreate() method.

MongoDB 3.2 and 3.0

The way we do this is by $projecting our documents and use the $concat string aggregation operator to return the concatenated string. we From there, you then iterate the cursor and use the $set update operator to add the new field to your documents using bulk operations for maximum efficiency.

Aggregation query:

var cursor = db.collection.aggregate([ 
    { "$project":  { 
        "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
    }}
])

MongoDB 3.2 or newer

from this, you need to use the bulkWrite method.

var requests = [];
cursor.forEach(document => { 
    requests.push( { 
        'updateOne': {
            'filter': { '_id': document._id },
            'update': { '$set': { 'name': document.name } }
        }
    });
    if (requests.length === 500) {
        //Execute per 500 operations and re-init
        db.collection.bulkWrite(requests);
        requests = [];
    }
});

if(requests.length > 0) {
     db.collection.bulkWrite(requests);
}

MongoDB 2.6 and 3.0

From this version you need to use the now deprecated Bulk API and its associated methods.

var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;

cursor.snapshot().forEach(function(document) { 
    bulk.find({ '_id': document._id }).updateOne( {
        '$set': { 'name': document.name }
    });
    count++;
    if(count%500 === 0) {
        // Excecute per 500 operations and re-init
        bulk.execute();
        bulk = db.collection.initializeUnorderedBulkOp();
    }
})

// clean up queues
if(count > 0) {
    bulk.execute();
}

MongoDB 2.4

cursor["result"].forEach(function(document) {
    db.collection.update(
        { "_id": document._id }, 
        { "$set": { "name": document.name } }
    );
})

Which ORM should I use for Node.js and MySQL?

May I suggest Node ORM?

https://github.com/dresende/node-orm2

There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.

MongoDB is available since version 2.1.x (released in July 2013)

UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize

Access POST values in Symfony2 request object

I think that in order to get the request data, bound and validated by the form object, you must use :

$form->getClientData();

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

Using flexbox, this is easy to achieve.

Set the wrapper containing your 3 compartments to display: flex; and give it a height of 100% or 100vh. The height of the wrapper will fill the entire height, and the display: flex; will cause all children of this wrapper which has the appropriate flex-properties (for example flex:1;) to be controlled with the flexbox-magic.

Example markup:

<div class="wrapper">
    <header>I'm a 30px tall header</header>
    <main>I'm the main-content filling the void!</main>
    <footer>I'm a 30px tall footer</footer>
</div>

And CSS to accompany it:

.wrapper {
    height: 100vh;
    display: flex;

    /* Direction of the items, can be row or column */
    flex-direction: column;
}

header,
footer {
    height: 30px;
}

main {
    flex: 1;
}

Here's that code live on Codepen: http://codepen.io/enjikaka/pen/zxdYjX/left

You can see more flexbox-magic here: http://philipwalton.github.io/solved-by-flexbox/

Or find a well made documentation here: http://css-tricks.com/snippets/css/a-guide-to-flexbox/

--[Old answer below]--

Here you go: http://jsfiddle.net/pKvxN/

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Layout</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  header {
    height: 30px;
    background: green;
  }
  footer {
    height: 30px;
    background: red;
  }
</style>
</head>
<body>
  <header>
    <h1>I am a header</h1>
  </header>
  <article>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula dolor.
    </p>
  </article>
  <footer>
    <h4>I am a footer</h4>
  </footer>
</body>
</html>

That works on all modern browsers (FF4+, Chrome, Safari, IE8 and IE9+)

UIView's frame, bounds, center, origin, when to use what?

Marco's answer above is correct, but just to expand on the question of "under what context"...

frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.

center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.

bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds] on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.

Why is there an frame rectangle and an bounds rectangle in an UIView?

Hopefully this helps clarify the circumstances where each property might get used.

HttpClient - A task was cancelled?

In my situation, the controller method was not made as async and the method called inside the controller method was async.

So I guess its important to use async/await all the way to top level to avoid issues like these.

How to find all occurrences of a substring?

This is solution of a similar question from hackerrank. I hope this could help you.

import re
a = input()
b = input()
if b not in a:
    print((-1,-1))
else:
    #create two list as
    start_indc = [m.start() for m in re.finditer('(?=' + b + ')', a)]
    for i in range(len(start_indc)):
        print((start_indc[i], start_indc[i]+len(b)-1))

Output:

aaadaa
aa
(0, 1)
(1, 2)
(4, 5)

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

Bootstrap 3 scrollable div for table

A scrolling comes from a box with class pre-scrollable

<div class="pre-scrollable"></div>

There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

With this chunk of code, you will get something like this title and image alignment

extension UIButton {
    func alignTextUnderImage() {
        guard let imageView = imageView else {
                return
        }
        self.contentVerticalAlignment = .Top
        self.contentHorizontalAlignment = .Center
        let imageLeftOffset = (CGRectGetWidth(self.bounds) - CGRectGetWidth(imageView.bounds)) / 2//put image in center
        let titleTopOffset = CGRectGetHeight(imageView.bounds) + 5
        self.imageEdgeInsets = UIEdgeInsetsMake(0, imageLeftOffset, 0, 0)
        self.titleEdgeInsets = UIEdgeInsetsMake(titleTopOffset, -CGRectGetWidth(imageView.bounds), 0, 0)
    }
}

Closing JFrame with button click

JButton b3 = new JButton("CLOSE");

b3.setBounds(50, 375, 250, 50);

b3.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }
});

Remove Object from Array using JavaScript

This is what I use.

Array.prototype.delete = function(pos){
    this[pos] = undefined;
    var len = this.length - 1;
    for(var a = pos;a < this.length - 1;a++){
      this[a] = this[a+1];
    }
    this.pop();
  }

Then it is as simple as saying

var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);

Replace any number in place of three. After the expected output should be:

console.log(myArray); //Expected output 1,2,3,5,6,7,8,9

How to create a inner border for a box in html?

Take a look at this , we can simply do this with outline-offset property

Output image look like

enter image description here

_x000D_
_x000D_
.black_box {_x000D_
    width:500px;_x000D_
    height:200px;_x000D_
    background:#000;_x000D_
    float:left;_x000D_
    border:2px solid #000;_x000D_
    outline: 1px dashed #fff;_x000D_
    outline-offset: -10px;_x000D_
}
_x000D_
<div class="black_box"></div>
_x000D_
_x000D_
_x000D_

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

How to check if a file exists in Documents folder?

NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error to do so

NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
NSError * __autoreleasing error = nil;
if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
    NSLog(@"%@ exists", fileURL);
} else {
    NSLog(@"%@ existence checking error: %@", fileURL, error);
}

Or using Swift

if let url = URL(fileURLWithPath: NSHomeDirectory()) {
    do {
        let result = try url.checkResourceIsReachable()
    } catch {
        print(error)
    }
}

Windows command to convert Unix line endings?

Late to the party, but there is still no correct answer using a FOR /F loop.
(But you don't need a FOR loop at all, the solution from @TampaHaze works too and is much simpler)

The answer from @IR relevant has some drawbacks.
It drops the exclamation marks and can also drop carets.

@echo off
(
    setlocal Disabledelayedexpansion
    for /f "tokens=* delims=" %%L in ('findstr /n "^" "%~1"') do (
        set "line=%%L"
        setlocal enabledelayedexpansion
        set "line=!line:*:=!"
        (echo(!line!)
        endlocal
    )
) > file.dos

The trick is to use findstr /n to prefix each line with <line number>:, this avoids skipping of empty lines or lines beginning with ;.
To remove the <number>: the FOR "tokens=1,* delims=:" option can't be used, because this would remove all leading colons in a line, too.

Therefore the line number is removed by set "line=!line:*:=!", this requires EnableDelayedExpansion.
But with EnableDelayedExpansion the line set "line=%%L" would drop all exclamation marks and also carets (only when exclams are in the line).

That's why I disable the delayed expansion before and only enable it for the two lines, where it is required.

The (echo(!line!) looks strange, but has the advantage, that echo( can display any content in !line! and the outer parenthesis avoids accidentials whitespaces at the line end.

How to get text from each cell of an HTML table?

Thanks for the earlier reply.

I figured out the solutions using selenium 2.0 classes.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebTableExample 
{
    public static void main(String[] args) 
    {
        WebDriver driver = new InternetExplorerDriver();
        driver.get("http://localhost/test/test.html");      

        WebElement table_element = driver.findElement(By.id("testTable"));
        List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));

        System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
        int row_num,col_num;
        row_num=1;
        for(WebElement trElement : tr_collection)
        {
            List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
            System.out.println("NUMBER OF COLUMNS="+td_collection.size());
            col_num=1;
            for(WebElement tdElement : td_collection)
            {
                System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
                col_num++;
            }
            row_num++;
        } 
    }
}

Source file not compiled Dev C++

I was having this issue and fixed it by going to: C:\Dev-Cpp\libexec\gcc\mingw32\3.4.2 , then deleting collect2.exe

Stop Visual Studio from launching a new browser window when starting debug?

This workaround works for me for VS 2019

Tools => Options

Then type Projects and solutions in the search box.

Select the Web Projects.

Then deselect the option below.

Stop debugger when browser window is closed, close browser when debugging stops.

This works for me. Hope this will help.

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

How to add jQuery in JS file

Dynamic adding jQuery, CSS from js file. When we added onload function to body we can use jQuery to create page from js file.

_x000D_
_x000D_
init();_x000D_
_x000D_
function init()_x000D_
{_x000D_
 addJQuery();_x000D_
 addBodyAndOnLoadScript();_x000D_
 addCSS();_x000D_
}_x000D_
_x000D_
function addJQuery()_x000D_
{_x000D_
 var head = document.getElementsByTagName( 'head' )[0];_x000D_
 var scriptjQuery = document.createElement( 'script' );_x000D_
 scriptjQuery.type = 'text/javascript';_x000D_
 scriptjQuery.id = 'jQuery'_x000D_
 scriptjQuery.src = 'https://code.jquery.com/jquery-3.4.1.min.js';_x000D_
 var script = document.getElementsByTagName( 'script' )[0];_x000D_
 head.insertBefore(scriptjQuery, script);_x000D_
}_x000D_
_x000D_
function addBodyAndOnLoadScript()_x000D_
{_x000D_
 var body = document.createElement('body')_x000D_
 body.onload = _x000D_
 function()_x000D_
 {_x000D_
  onloadFunction();_x000D_
 };_x000D_
}_x000D_
_x000D_
function addCSS()_x000D_
{_x000D_
 var head = document.getElementsByTagName( 'head' )[0];_x000D_
 var linkCss = document.createElement( 'link' );_x000D_
 linkCss.rel = 'stylesheet';_x000D_
 linkCss.href = 'E:/Temporary_files/temp_css.css';_x000D_
 head.appendChild( linkCss );_x000D_
}_x000D_
_x000D_
function onloadFunction()_x000D_
{_x000D_
 var body = $( 'body' );_x000D_
 body.append('<strong>Hello world</strong>');_x000D_
}
_x000D_
html _x000D_
{_x000D_
 background-color: #f5f5dc;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
 <head>_x000D_
  <meta charset="UTF-8">_x000D_
  <title>Temp Study HTML Page</title>_x000D_
  <script type="text/javascript" src="E:\Temporary_files\temp_script.js"></script>_x000D_
 </head>_x000D_
 <body></body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Get unicode value of a character

are you picky with using Unicode because with java its more simple if you write your program to use "dec" value or (HTML-Code) then you can simply cast data types between char and int

char a = 98;
char b = 'b';
char c = (char) (b+0002);

System.out.println(a);
System.out.println((int)b);
System.out.println((int)c);
System.out.println(c);

Gives this output

b
98
100
d

Convert Rows to columns using 'Pivot' in SQL Server

If you are using SQL Server 2005+, then you can use the PIVOT function to transform the data from rows into columns.

It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.

First up, here are some quick table definitions and data for use:

CREATE TABLE #yt 
(
  [Store] int, 
  [Week] int, 
  [xCount] int
);

INSERT INTO #yt
(
  [Store], 
  [Week], [xCount]
)
VALUES
    (102, 1, 96),
    (101, 1, 138),
    (105, 1, 37),
    (109, 1, 59),
    (101, 2, 282),
    (102, 2, 212),
    (105, 2, 78),
    (109, 2, 97),
    (105, 3, 60),
    (102, 3, 123),
    (101, 3, 220),
    (109, 3, 87);

If your values are known, then you will hard-code the query:

select *
from 
(
  select store, week, xCount
  from yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;

See SQL Demo

Then if you need to generate the week number dynamically, your code will be:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Week) 
                    from yt
                    group by Week
                    order by Week
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT store,' + @cols + ' from 
             (
                select store, week, xCount
                from yt
            ) x
            pivot 
            (
                sum(xCount)
                for week in (' + @cols + ')
            ) p '

execute(@query);

See SQL Demo.

The dynamic version, generates the list of week numbers that should be converted to columns. Both give the same result:

| STORE |   1 |   2 |   3 |
---------------------------
|   101 | 138 | 282 | 220 |
|   102 |  96 | 212 | 123 |
|   105 |  37 |  78 |  60 |
|   109 |  59 |  97 |  87 |

Configure apache to listen on port other than 80

For FC22 server

cd /etc/httpd/conf edit httpd.conf [enter]

Change: Listen 80 to: Listen whatevernumber

Save the file

systemctl restart httpd.service [enter] if required, open whatevernumber in your router / firewall

Assert that a method was called in a Python unit test

I use Mock (which is now unittest.mock on py3.3+) for this:

from mock import patch
from PyQt4 import Qt


@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)

For your case, it could look like this:

import mock
from mock import patch


def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.

Caveat emptor! (Buyer beware!)

If you mistype assert_called_with (to assert_called_once or assert_called_wiht) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true. For more info read assert_called_once: Threat or Menace.

Facebook API error 191

Had the same problem:

$params = array('redirect_uri' => 'facebook.com/pages/foobar-dev');
$facebook->getLoginUrl($params);

When I changed the redirect_uri from the devloper page to the live page, 191 Error came up.

So I deleted the $params:

$facebook->getLoginUrl();

After the app-request now FB redirects to the app url itself f.e.: my.domain.com

What I do now is checking in index.php of my app if I'm inside FB iframe or not. If not I redirect to the live FB page f.e.:

$app = 'facebook.com/pages/foobar-live';
$rd = (isset($_SERVER['HTTP_REFERER'])) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) : false;
if ($rd == 'apps.facebook.com' || (!isset($_REQUEST['signed_request'])))  {
    echo '<script>window.parent.location = "'.$app.'";</script>';
    die();
}

How to call javascript function from code-behind

There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:

<head runat="server"> 
    <title>Calling javascript function from code behind example</title> 
        <script type="text/javascript"> 
            function showDialogue() { 
                alert("this dialogue has been invoked through codebehind."); 
            } 
        </script> 
</head>

..........

lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm

Python, Matplotlib, subplot: How to set the axis range?

If you know the exact axis you want, then

pylab.ylim([0,1000])

works as answered previously. But if you want a more flexible axis to fit your exact data, as I did when I found this question, then set axis limit to be the length of your dataset. If your dataset is fft as in the question, then add this after your plot command:

length = (len(fft)) pylab.ylim([0,length])

text-overflow: ellipsis not working

Add the Following lines in CSS for ellipsis to work

 p {
     display: block; // change it as per your requirement
     overflow: hidden;
     text-overflow: ellipsis;
     white-space: nowrap;
   }

What is the list of supported languages/locales on Android?

Update for 4.0

Android 4.0.3 Platform

Arabic, Egypt (ar_EG)
Arabic, Israel (ar_IL)
Bulgarian, Bulgaria (bg_BG)
Catalan, Spain (ca_ES)
Chinese, PRC (zh_CN)
Chinese, Taiwan (zh_TW)
Croatian, Croatia (hr_HR)
Czech, Czech Republic (cs_CZ)
Danish, Denmark(da_DK)
Dutch, Belgium (nl_BE)
Dutch, Netherlands (nl_NL)
English, Australia (en_AU)
English, Britain (en_GB)
English, Canada (en_CA)
English, India (en_IN)
English, Ireland (en_IE)
English, New Zealand (en_NZ)
English, Singapore(en_SG)
English, South Africa (en_ZA)
English, US (en_US)
Finnish, Finland (fi_FI)
French, Belgium (fr_BE)
French, Canada (fr_CA)
French, France (fr_FR)
French, Switzerland (fr_CH)
German, Austria (de_AT)
German, Germany (de_DE)
German, Liechtenstein (de_LI)
German, Switzerland (de_CH)
Greek, Greece (el_GR)
Hebrew, Israel (he_IL)
Hindi, India (hi_IN)
Hungarian, Hungary (hu_HU)
Indonesian, Indonesia (id_ID)
Italian, Italy (it_IT)
Italian, Switzerland (it_CH)
Japanese (ja_JP)
Korean (ko_KR)
Latvian, Latvia (lv_LV)
Lithuanian, Lithuania (lt_LT)
Norwegian bokmål, Norway (nb_NO)
Polish (pl_PL)
Portuguese, Brazil (pt_BR)
Portuguese, Portugal (pt_PT)
Romanian, Romania (ro_RO)
Russian (ru_RU)
Serbian (sr_RS)
Slovak, Slovakia (sk_SK)
Slovenian, Slovenia (sl_SI)
Spanish (es_ES)
Spanish, US (es_US)
Swedish, Sweden (sv_SE)
Tagalog, Philippines (tl_PH)
Thai, Thailand (th_TH)
Turkish, Turkey (tr_TR)
Ukrainian, Ukraine (uk_UA)
Vietnamese, Vietnam (vi_VN)

SOURCE: http://us.dinodirect.com/Forum/Latest-Posts-5/Android-Versions-and-their-Locales-1-86587/

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

Get Application Directory

There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):

getApplicationInfo().dataDir

http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()

jquery ajax get responsetext from http url

try this

alert( data['responseText'] );

Image overlay on responsive sized images bootstrap

Add a class to the containing div, then set the following css on it:

.img-overlay {
    position: relative;
    max-width: 500px; //whatever your max-width should be 
}

position: relative is required on a parent element of children with position: absolute for the children to be positioned in relation to that parent.

DEMO

How to make a phone call programmatically?

You forgot to call startActivity. It should look like this:

Intent intent = new Intent(Intent.ACTION_CALL);

intent.setData(Uri.parse("tel:" + bundle.getString("mobilePhone")));
context.startActivity(intent);

An intent by itself is simply an object that describes something. It doesn't do anything.

Don't forget to add the relevant permission to your manifest:

<uses-permission android:name="android.permission.CALL_PHONE" />

Output data from all columns in a dataframe in pandas

you can also use DataFrame.head(x) / .tail(x) to display the first / last x rows of the DataFrame.

How to store Node.js deployment settings/configuration files?

I am a bit late in the game, but I couldn't find what I needed here- or anywhere else - so I wrote something myself.

My requirements for a configuration mechanism are the following:

  1. Support front-end. What is the point if the front-end cannot use the configuration?
  2. Support settings-overrides.js - which looks the same but allows overrides of configuration at settings.js. The idea here is to modify configuration easily without changing the code. I find it useful for saas.

Even though I care less about supporting environments - the will explain how to add it easily to my solution

var publicConfiguration = {
    "title" : "Hello World"
    "demoAuthToken" : undefined, 
    "demoUserId" : undefined, 
    "errorEmail" : null // if null we will not send emails on errors. 

};

var privateConfiguration = {
    "port":9040,
    "adminAuthToken":undefined,
    "adminUserId":undefined
}

var meConf = null;
try{
    meConf = require("../conf/dev/meConf");
}catch( e ) { console.log("meConf does not exist. ignoring.. ")}




var publicConfigurationInitialized = false;
var privateConfigurationInitialized = false;

function getPublicConfiguration(){
    if (!publicConfigurationInitialized) {
        publicConfigurationInitialized = true;
        if (meConf != null) {
            for (var i in publicConfiguration) {
                if (meConf.hasOwnProperty(i)) {
                    publicConfiguration[i] = meConf[i];
                }
            }
        }
    }
    return publicConfiguration;
}


function getPrivateConfiguration(){
    if ( !privateConfigurationInitialized ) {
        privateConfigurationInitialized = true;

        var pubConf = getPublicConfiguration();

        if ( pubConf != null ){
            for ( var j in pubConf ){
                privateConfiguration[j] = pubConf[j];
            }
        }
        if ( meConf != null ){
              for ( var i in meConf ){
                  privateConfiguration[i] = meConf[i];
              }
        }
    }
    return privateConfiguration;

}


exports.sendPublicConfiguration = function( req, res ){
    var name = req.param("name") || "conf";

    res.send( "window." + name + " = " + JSON.stringify(getPublicConfiguration()) + ";");
};


var prConf = getPrivateConfiguration();
if ( prConf != null ){
    for ( var i in prConf ){
        if ( prConf[i] === undefined ){

            throw new Error("undefined configuration [" + i + "]");
        }
        exports[i] = prConf[i];
    }
}


return exports;

Explanation

  • undefined means this property is required
  • null means it is optional
  • meConf - currently the code is target to a file under app. meConf is the overrides files which is targeted to conf/dev - which is ignored by my vcs.
  • publicConfiguration - will be visible from front-end and back-end.
  • privateConfiguration - will be visible from back-end only.
  • sendPublicConfiguration - a route that will expose the public configuration and assign it to a global variable. For example the code below will expose the public configuration as global variable myConf in the front-end. By default it will use the global variable name conf.

    app.get("/backend/conf", require("conf").sendPublicConfiguration);

Logic of overrides

  • privateConfiguration is merged with publicConfiguration and then meConf.
  • publicConfiguration checks each key if it has an override, and uses that override. This way we are not exposing anything private.

Adding environment support

Even though I don't find an "environment support" useful, maybe someone will.

To add environment support you need to change the meConf require statement to something like this (pseudocode)

if ( environment == "production" ) { meConf = require("../conf/dev/meConf").production; }

if ( environment == "development" ) { meConf = require("../conf/dev/meConf").development; }

Similarly you can have a file per environment

 meConf.development.js
 meConf.production.js

and import the right one. The rest of the logic stays the same.

Must declare the scalar variable

This is most likely not an answer to the issue itself but this question pops up as first result when searching for Sql declare scalar variable hence i share a possible solution to this error.

In my case this error was caused by the use of ; after a SQL statement. Just remove it and the error will be gone.

I guess the cause is the same as @IronSean already posted in an comment above:

it's worth noting that using GO (or in this case ;) causes a new branch where declared variables aren't visible past the statement.

For example:

DECLARE @id int
SET @id = 78

SELECT * FROM MyTable WHERE Id = @var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = @var

How to animate RecyclerView items when they appear

Animating items in the recyclerview when they are binded in the adapter might not be the best idea as that can cause the items in the recyclerview to animate at different speeds. In my case, the item at the end of the recyclerview animate to their position quicker then the ones at the top as the ones at the top have further to travel so it made it look untidy.

The original code that I used to animate each item into the recyclerview can be found here:

http://frogermcs.github.io/Instagram-with-Material-Design-concept-is-getting-real/

But I will copy and paste the code in case the link breaks.

STEP 1: Set this inside your onCreate method so that you ensure the animation only run once:

if (savedInstanceState == null) {
    pendingIntroAnimation = true;
}

STEP 2: You will need to put this code into the method where you want to start the animation:

if (pendingIntroAnimation) {
    pendingIntroAnimation = false;
    startIntroAnimation();
}

In the link, the writer is animating the toolbar icons, so he put it inside this method:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    inboxMenuItem = menu.findItem(R.id.action_inbox);
    inboxMenuItem.setActionView(R.layout.menu_item_view);
    if (pendingIntroAnimation) {
        pendingIntroAnimation = false;
        startIntroAnimation();
    }
    return true;
}

STEP 3: Now write the logic for the startIntroAnimation():

private static final int ANIM_DURATION_TOOLBAR = 300;

private void startIntroAnimation() {
    btnCreate.setTranslationY(2 * getResources().getDimensionPixelOffset(R.dimen.btn_fab_size));

    int actionbarSize = Utils.dpToPx(56);
    toolbar.setTranslationY(-actionbarSize);
    ivLogo.setTranslationY(-actionbarSize);
    inboxMenuItem.getActionView().setTranslationY(-actionbarSize);

    toolbar.animate()
            .translationY(0)
            .setDuration(ANIM_DURATION_TOOLBAR)
            .setStartDelay(300);
    ivLogo.animate()
            .translationY(0)
            .setDuration(ANIM_DURATION_TOOLBAR)
            .setStartDelay(400);
    inboxMenuItem.getActionView().animate()
            .translationY(0)
            .setDuration(ANIM_DURATION_TOOLBAR)
            .setStartDelay(500)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    startContentAnimation();
                }
            })
            .start();
}

My preferred alternative:

I would rather animate the whole recyclerview instead of the items inside the recyclerview.

STEP 1 and 2 remains the same.

In STEP 3, as soon as your API call returns with your data, I would start the animation.

private void startIntroAnimation() {
    recyclerview.setTranslationY(latestPostRecyclerview.getHeight());
    recyclerview.setAlpha(0f);
    recyclerview.animate()
            .translationY(0)
            .setDuration(400)
            .alpha(1f)
            .setInterpolator(new AccelerateDecelerateInterpolator())
            .start();
}

This would animate your entire recyclerview so that it flys in from the bottom of the screen.

How to set -source 1.7 in Android Studio and Gradle

Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle.

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 19
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.

Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.

Link to android gradle plugin user guide

Link to see how source vs target are different

What does ':' (colon) do in JavaScript?

You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

var result = (condition) ? (value1) : (value2) ;

A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

How to uncommit my last commit in Git

If you haven't pushed your changes yet use git reset --soft [Hash for one commit] to rollback to a specific commit. --soft tells git to keep the changes being rolled back (i.e., mark the files as modified). --hard tells git to delete the changes being rolled back.

Constructor overload in TypeScript

It sounds like you want the object parameter to be optional, and also each of the properties in the object to be optional. In the example, as provided, overload syntax isn't needed. I wanted to point out some bad practices in some of the answers here. Granted, it's not the smallest possible expression of essentially writing box = { x: 0, y: 87, width: 4, height: 0 }, but this provides all the code hinting niceties you could possibly want from the class as described. This example allows you to call a function with one, some, all, or none of the parameters and still get default values.

 /** @class */
 class Box {
     public x?: number;
     public y?: number;
     public height?: number;
     public width?: number;     

     constructor(params: Box = {} as Box) {

         // Define the properties of the incoming `params` object here. 
         // Setting a default value with the `= 0` syntax is optional for each parameter
         let {
             x = 0,
             y = 0,
             height = 1,
             width = 1
         } = params;
         
         //  If needed, make the parameters publicly accessible
         //  on the class ex.: 'this.var = var'.
         /**  Use jsdoc comments here for inline ide auto-documentation */
         this.x = x;
         this.y = y;
         this.height = height;
         this.width = width;
     }
 }

Need to add methods? A verbose but more extendable alternative: The Box class above can work double-duty as the interface since they are identical. If you choose to modify the above class, you will need to define and reference a new interface for the incoming parameters object since the Box class no longer would look exactly like the incoming parameters. Notice where the question marks (?:) denoting optional properties move in this case. Since we're setting default values within the class, they are guaranteed to be present, yet they are optional within the incoming parameters object:

    interface BoxParams {
        x?: number;
         // Add Parameters ...
    }

    class Box {
         public x: number;
         // Copy Parameters ...
         constructor(params: BoxParams = {} as BoxParams) {
         let { x = 0 } = params;
         this.x = x;
    }
    doSomething = () => {
        return this.x + this.x;
        }
    }

Whichever way you choose to define your class, this technique offers the guardrails of type safety, yet the flexibility write any of these:

const box1 = new Box();
const box2 = new Box({});
const box3 = new Box({x:0});
const box4 = new Box({x:0, height:10});
const box5 = new Box({x:0, y:87,width:4,height:0});

 // Correctly reports error in TypeScript, and in js, box6.z is undefined
const box6 = new Box({z:0});  

Compiled, you see how the default settings are only used if an optional value is undefined; it avoids the pitfalls of a widely used (but error-prone) fallback syntax of var = isOptional || default; by checking against void 0, which is shorthand for undefined:

The Compiled Output

var Box = (function () {
    function Box(params) {
        if (params === void 0) { params = {}; }
        var _a = params.x, x = _a === void 0 ? 0 : _a, _b = params.y, y = _b === void 0 ? 0 : _b, _c = params.height, height = _c === void 0 ? 1 : _c, _d = params.width, width = _d === void 0 ? 1 : _d;
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
    }
    return Box;
}());

Addendum: Setting default values: the wrong way

The || (or) operator

Consider the danger of ||/or operators when setting default fallback values as shown in some other answers. This code below illustrates the wrong way to set defaults. You can get unexpected results when evaluating against falsey values like 0, '', null, undefined, false, NaN:

var myDesiredValue = 0;
var result = myDesiredValue || 2;

// This test will correctly report a problem with this setup.
console.assert(myDesiredValue === result && result === 0, 'Result should equal myDesiredValue. ' + myDesiredValue + ' does not equal ' + result);

Object.assign(this,params)

In my tests, using es6/typescript destructured object can be 15-90% faster than Object.assign. Using a destructured parameter only allows methods and properties you've assigned to the object. For example, consider this method:

class BoxTest {
    public x?: number = 1;

    constructor(params: BoxTest = {} as BoxTest) {
        Object.assign(this, params);
    }
}

If another user wasn't using TypeScript and attempted to place a parameter that didn't belong, say, they might try putting a z property

var box = new BoxTest({x: 0, y: 87, width: 4, height: 0, z: 7});

// This test will correctly report an error with this setup. `z` was defined even though `z` is not an allowed property of params.
console.assert(typeof box.z === 'undefined')

No resource found that matches the given name '@style/Theme.AppCompat.Light'

Below are the steps you can try it out to resolve the issue: -

  1. Provide reference of AppCompat Library into your project.
  2. If option 1 doesn't solve the issue then you can try to change the style.xml file to below code.
 parent="android:Theme.Holo.Light"  

instead.

 parent="android:Theme.AppCompat.Light"  

But option 2 will require minimum sdk version 14.

Hope this will help !

Summved

Can I prevent text in a div block from overflowing?

Recommendations for how to catch which part of your CSS is causing the issue:

1) set style="height:auto;" on all the <div> elements and retry again.

2) Set style="border: 3px solid red;" on all the <div> elements to see how wide of an area your <div>'s box is taking up.

3) Take away all the css height:#px; properties from your CSS and start over.

So for example:

<div id="I" style="height:auto;border: 3px solid red;">I
    <div id="A" style="height:auto;border: 3px solid purple;">A
        <div id="1A" style="height:auto;border: 3px solid green;">1A
        </div>
        <div id="2A" style="height:auto;border: 3px solid green;">2A
        </div>
    </div>
    <div id="B" style="height:auto;border: 3px solid purple;">B
        <div id="1B" style="height:auto;border: 3px solid green;">1B
        </div>
        <div id="2B" style="height:auto;border: 3px solid green;">2B
        </div>
    </div>
</div>

How to know the size of the string in bytes?

From MSDN:

A String object is a sequential collection of System.Char objects that represent a string.

So you can use this:

var howManyBytes = yourString.Length * sizeof(Char);

Is there a performance difference between i++ and ++i in C?

Taking a leaf from Scott Meyers, More Effective c++ Item 6: Distinguish between prefix and postfix forms of increment and decrement operations.

The prefix version is always preferred over the postfix in regards to objects, especially in regards to iterators.

The reason for this if you look at the call pattern of the operators.

// Prefix
Integer& Integer::operator++()
{
    *this += 1;
    return *this;
}

// Postfix
const Integer Integer::operator++(int)
{
    Integer oldValue = *this;
    ++(*this);
    return oldValue;
}

Looking at this example it is easy to see how the prefix operator will always be more efficient than the postfix. Because of the need for a temporary object in the use of the postfix.

This is why when you see examples using iterators they always use the prefix version.

But as you point out for int's there is effectively no difference because of compiler optimisation that can take place.

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

What is the pythonic way to detect the last element in a 'for' loop?

So, this is definitely not the "shorter" version - and one might digress if "shortest" and "Pythonic" are actually compatible.

But if one needs this pattern often, just put the logic in to a 10-liner generator - and get any meta-data related to an element's position directly on the for call. Another advantage here is that it will work wit an arbitrary iterable, not only Sequences.

_sentinel = object()

def iter_check_last(iterable):
    iterable = iter(iterable)
    current_element = next(iterable, _sentinel)
    while current_element is not _sentinel:
        next_element = next(iterable, _sentinel)
        yield (next_element is _sentinel, current_element)
        current_element = next_element
In [107]: for is_last, el in iter_check_last(range(3)):
     ...:     print(is_last, el)
     ...: 
     ...: 
False 0
False 1
True 2

Go To Definition: "Cannot navigate to the symbol under the caret."

For me the navigate works just NO XAMARIN SOLUTIONS. That suggestions here DIDN´T WORKS. :( Devenv.exe /resetuserdata not works for me.

My solution was: Re-create the solutions, project, folders and works. No import. Detail: my project was on the VS 2015, the error was on the VS 2017.

How do I trim whitespace from a string?

Just one space or all consecutive spaces? If the second, then strings already have a .strip() method:

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'

If you only need to remove one space however, you could do it with:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'

Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:

>>> "  Hello\n".strip(" ")
'Hello\n'

Delete sql rows where IDs do not have a match from another table

Using LEFT JOIN/IS NULL:

DELETE b FROM BLOB b 
  LEFT JOIN FILES f ON f.id = b.fileid 
      WHERE f.id IS NULL

Using NOT EXISTS:

DELETE FROM BLOB 
 WHERE NOT EXISTS(SELECT NULL
                    FROM FILES f
                   WHERE f.id = fileid)

Using NOT IN:

DELETE FROM BLOB
 WHERE fileid NOT IN (SELECT f.id 
                        FROM FILES f)

Warning

Whenever possible, perform DELETEs within a transaction (assuming supported - IE: Not on MyISAM) so you can use rollback to revert changes in case of problems.

Where can I find php.ini?

Best way to find this is: create a php file and add the following code:

<?php phpinfo(); ?>

and open it in browser, it will show the file which is actually being read!

Updates by OP:

  1. The previously accepted answer is likely to be faster and more convenient for you, but it is not always correct. See comments on that answer.
  2. Please also note the more convenient alternative <?php echo php_ini_loaded_file(); ?> mentioned in this answer.

Foreign Key to multiple tables

The first option in @Nathan Skerl's list is what was implemented in a project I once worked with, where a similar relationship was established between three tables. (One of them referenced two others, one at a time.)

So, the referencing table had two foreign key columns, and also it had a constraint to guarantee that exactly one table (not both, not neither) was referenced by a single row.

Here's how it could look when applied to your tables:

CREATE TABLE dbo.[Group]
(
    ID int NOT NULL CONSTRAINT PK_Group PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.[User]
(
    ID int NOT NULL CONSTRAINT PK_User PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL CONSTRAINT PK_Ticket PRIMARY KEY,
    OwnerGroup int NULL
      CONSTRAINT FK_Ticket_Group FOREIGN KEY REFERENCES dbo.[Group] (ID),
    OwnerUser int NULL
      CONSTRAINT FK_Ticket_User  FOREIGN KEY REFERENCES dbo.[User]  (ID),
    Subject varchar(50) NULL,
    CONSTRAINT CK_Ticket_GroupUser CHECK (
      CASE WHEN OwnerGroup IS NULL THEN 0 ELSE 1 END +
      CASE WHEN OwnerUser  IS NULL THEN 0 ELSE 1 END = 1
    )
);

As you can see, the Ticket table has two columns, OwnerGroup and OwnerUser, both of which are nullable foreign keys. (The respective columns in the other two tables are made primary keys accordingly.) The CK_Ticket_GroupUser check constraint ensures that only one of the two foreign key columns contains a reference (the other being NULL, that's why both have to be nullable).

(The primary key on Ticket.ID is not necessary for this particular implementation, but it definitely wouldn't harm to have one in a table like this.)

How to calculate difference in hours (decimal) between two dates in SQL Server?

You are probably looking for the DATEDIFF function.

DATEDIFF ( datepart , startdate , enddate )

Where you code might look like this:

DATEDIFF ( hh , startdate , enddate )

ReactJS: Warning: setState(...): Cannot update during an existing state transition

If you are trying to add arguments to a handler in recompose, make sure that you're defining your arguments correctly in the handler. It is essentially a curried function, so you want to be sure to require the correct number of arguments. This page has a good example of using arguments with handlers.

Example (from the link):

withHandlers({
  handleClick: props => (value1, value2) => event => {
    console.log(event)
    alert(value1 + ' was clicked!')
    props.doSomething(value2)
  },
})

for your child HOC and in the parent

class MyComponent extends Component {
  static propTypes = {
    handleClick: PropTypes.func, 
  }
  render () {
    const {handleClick} = this.props
    return (
      <div onClick={handleClick(value1, value2)} />
    )
  }
}

this avoids writing an anonymous function out of your handler to patch fix the problem with not supplying enough parameter names on your handler.

Enter key in textarea

You could do something like this:

<body>

<textarea id="txtArea" onkeypress="onTestChange();"></textarea>

<script>
function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
        return false;
    }
    else {
        return true;
    }
}
</script>

</body>

Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.

How to read the RGB value of a given pixel in Python?

You could use the Tkinter module, which is the standard Python interface to the Tk GUI toolkit and you don't need extra download. See https://docs.python.org/2/library/tkinter.html.

(For Python 3, Tkinter is renamed to tkinter)

Here is how to set RGB values:

#from http://tkinter.unpythonic.net/wiki/PhotoImage
from Tkinter import *

root = Tk()

def pixel(image, pos, color):
    """Place pixel at pos=(x,y) on image, with color=(r,g,b)."""
    r,g,b = color
    x,y = pos
    image.put("#%02x%02x%02x" % (r,g,b), (y, x))

photo = PhotoImage(width=32, height=32)

pixel(photo, (16,16), (255,0,0))  # One lone pixel in the middle...

label = Label(root, image=photo)
label.grid()
root.mainloop()

And get RGB:

#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py
def getRGB(image, x, y):
    value = image.get(x, y)
    return tuple(map(int, value.split(" ")))

How to install Laravel's Artisan?

While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory. Just follow below step to fix issue. check composer status using : composer -v

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Please check with below command:

php artisan serve

still not work then create new project with existing code. using LINK

Get current domain

Everybody is using the parse_url function, but sometimes user may pass the argumet in different format.

So as to fix that, I have created the function. Check this out:

function fixDomainName($url='')
{
    $strToLower = strtolower(trim($url));
    $httpPregReplace = preg_replace('/^http:\/\//i', '', $strToLower);
    $httpsPregReplace = preg_replace('/^https:\/\//i', '', $httpPregReplace);
    $wwwPregReplace = preg_replace('/^www\./i', '', $httpsPregReplace);
    $explodeToArray = explode('/', $wwwPregReplace);
    $finalDomainName = trim($explodeToArray[0]);
    return $finalDomainName;
}

Just pass the URL and get the domain.

For example,

echo fixDomainName('https://stackoverflow.com');

will return the result will be

stackoverflow.com

And in some situation:

echo fixDomainName('stackoverflow.com/questions/id/slug');

And it will also return stackoverflow.com.

Connect to external server by using phpMyAdmin

In the config file, change the "host" variable to point to the external server. The config file is called config.inc.php and it will be in the main phpMyAdmin folder. There should be a line like this:

$cfg['Servers'][$i]['host'] = 'localhost';

Just change localhost to your server's IP address.

Note: you may have to configure the external server to allow remote connections, but I've done this several times on shared hosting so it should be fine.

Number of days between two dates in Joda-Time

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
                               end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
                               end.toLocalDate()).getDays());
// prints 1

Going via a LocalDate sidesteps the whole issue.

Mockito : how to verify method was called on an object created within a method?

Yes, if you really want / need to do it you can use PowerMock. This should be considered a last resort. With PowerMock you can cause it to return a mock from the call to the constructor. Then do the verify on the mock. That said, csturtz's is the "right" answer.

Here is the link to Mock construction of new objects

when exactly are we supposed to use "public static final String"?

You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.

Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.

An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).

Here's why:

  1. Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
  2. What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.

What are the consequences?

Imagine you have this:

class Foo {
  public static final String VERSION = "1.0";
}

class Bar {
  public static void main(String[] args) {
    System.out.println("I am using version " + Foo.VERSION);
  }
}

After compiling and running Bar, you'll get:

I am using version 1.0

Now, you improve Foo and change the version to "1.1". After recompiling Foo, you run Bar and get this wrong output:

I am using version 1.0

This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.

I've seen this a couple of times and it is really hard to debug.

If by final you mean a constant that might change in later versions of your program, a better solution would be this:

class Foo {
  private static String version = "1.0";
  public static final String getVersion() {
    return version;
  }
}

The performance penalty of this is negligible, since JIT code generator will inline it at run-time.

operator << must take exactly one argument

If you define operator<< as a member function it will have a different decomposed syntax than if you used a non-member operator<<. A non-member operator<< is a binary operator, where a member operator<< is a unary operator.

// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);

struct MyObj
{
    // This is a member unary-operator, hence one argument
    MyObj& operator<<(std::ostream& os) { os << *this; return *this; }

    int value = 8;
};

// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
    return os << myObj.value;
}

So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...) syntax in your head to make things make sense.

MyObj mo;

// Calling the unary operator
mo << std::cout;

// which decomposes to...
mo.operator<<(std::cout);

Or you could attempt to call the non-member binary operator:

MyObj mo;

// Calling the binary operator
std::cout << mo;

// which decomposes to...
operator<<(std::cout, mo);

You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int) to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.

Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.

Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)

struct MyObj
{
    // Note that we now return the ostream
    std::ostream& operator<<(std::ostream& os) { os << *this; return os; }

    int value = 8;
};

This syntax will irritate many coders now....

MyObj mo;

mo << std::cout << "Words words words";

// this decomposes to...
mo.operator<<(std::cout) << "Words words words";

// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");

Note how the cout is the second argument in the chain here.... odd right?

Use grep to report back only line numbers

If you're open to using AWK:

awk '/textstring/ {print FNR}' textfile

In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

What values for checked and selected are false?

The checked and selected attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.

If you don't want to set the attribute, then the entire attribute must be omitted.

Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).

Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:

<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ...          checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked          > <!-- Only HTML 5 and later -->
<input ... checked=""       > <!-- Only HTML 5 and later -->

Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true", checked="yes", and checked="false" will all trigger the checked state.

I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.

(And all the above applies equally to selected as it does to checked.)

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

How to drop all stored procedures at once in SQL Server database?

ANSI compliant, without cursor

PRINT ('1.a. Delete stored procedures ' + CONVERT( VARCHAR(19), GETDATE(), 121));
GO
DECLARE @procedure NVARCHAR(max)
DECLARE @n CHAR(1)
SET @n = CHAR(10)
SELECT @procedure = isnull( @procedure + @n, '' ) +
'DROP PROCEDURE [' + schema_name(schema_id) + '].[' + name + ']'
FROM sys.procedures

EXEC sp_executesql @procedure
PRINT ('1.b. Stored procedures deleted ' + CONVERT( VARCHAR(19), GETDATE(), 121));
GO

How to disable copy/paste from/to EditText

For smartphone with clipboard, is possible prevent like this.

editText.setFilters(new InputFilter[]{new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.length() > 1) {
                return "";
            }  return null;
        }
    }});

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

How to backup a local Git repository?

The way I do this is to create a remote (bare) repository (on a separate drive, USB Key, backup server or even github) and then use push --mirror to make that remote repo look exactly like my local one (except the remote is a bare repository).

This will push all refs (branches and tags) including non-fast-forward updates. I use this for creating backups of my local repository.

The man page describes it like this:

Instead of naming each ref to push, specifies that all refs under $GIT_DIR/refs/ (which includes but is not limited to refs/heads/, refs/remotes/, and refs/tags/) be mirrored to the remote repository. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end. This is the default if the configuration option remote.<remote>.mirror is set.

I made an alias to do the push:

git config --add alias.bak "push --mirror github"

Then, I just run git bak whenever I want to do a backup.

C++ JSON Serialization

The jsoncons C++ header-only library also supports conversion between JSON text and C++ objects. Decode and encode are defined for all C++ classes that have json_type_traits defined. The standard library containers are already supported, and json_type_traits can be specialized for user types in the jsoncons namespace.

Below is an example:

#include <iostream>
#include <jsoncons/json.hpp>

namespace ns {
    enum class hiking_experience {beginner,intermediate,advanced};

    class hiking_reputon
    {
        std::string rater_;
        hiking_experience assertion_;
        std::string rated_;
        double rating_;
    public:
        hiking_reputon(const std::string& rater,
                       hiking_experience assertion,
                       const std::string& rated,
                       double rating)
            : rater_(rater), assertion_(assertion), rated_(rated), rating_(rating)
        {
        }

        const std::string& rater() const {return rater_;}
        hiking_experience assertion() const {return assertion_;}
        const std::string& rated() const {return rated_;}
        double rating() const {return rating_;}
    };

    class hiking_reputation
    {
        std::string application_;
        std::vector<hiking_reputon> reputons_;
    public:
        hiking_reputation(const std::string& application, 
                          const std::vector<hiking_reputon>& reputons)
            : application_(application), 
              reputons_(reputons)
        {}

        const std::string& application() const { return application_;}
        const std::vector<hiking_reputon>& reputons() const { return reputons_;}
    };

} // namespace ns

// Declare the traits using convenience macros. Specify which data members need to be serialized.

JSONCONS_ENUM_TRAITS_DECL(ns::hiking_experience, beginner, intermediate, advanced)
JSONCONS_ALL_CTOR_GETTER_TRAITS(ns::hiking_reputon, rater, assertion, rated, rating)
JSONCONS_ALL_CTOR_GETTER_TRAITS(ns::hiking_reputation, application, reputons)

using namespace jsoncons; // for convenience

int main()
{

std::string data = R"(
    {
       "application": "hiking",
       "reputons": [
       {
           "rater": "HikingAsylum",
           "assertion": "advanced",
           "rated": "Marilyn C",
           "rating": 0.90
         }
       ]
    }
)";

    // Decode the string of data into a c++ structure
    ns::hiking_reputation v = decode_json<ns::hiking_reputation>(data);

    // Iterate over reputons array value
    std::cout << "(1)\n";
    for (const auto& item : v.reputons())
    {
        std::cout << item.rated() << ", " << item.rating() << "\n";
    }

    // Encode the c++ structure into a string
    std::string s;
    encode_json<ns::hiking_reputation>(v, s, indenting::indent);
    std::cout << "(2)\n";
    std::cout << s << "\n";
}    

Output:

(1)
Marilyn C, 0.9
(2)
{
    "application": "hiking",
    "reputons": [
        {
            "assertion": "advanced",
            "rated": "Marilyn C",
            "rater": "HikingAsylum",
            "rating": 0.9
        }
    ]
}

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

I was able to solve similar Warning: session_start(): Cannot send session cache limiter - headers already sent by just removing a space in front of the <?php tag.

It worked.

Update Multiple Rows in Entity Framework from a list of ids

var idList=new int[]{1, 2, 3, 4};
var friendsToUpdate = await Context.Friends.Where(f => 
    idList.Contains(f.Id).ToListAsync();

foreach(var item in previousEReceipts)
{
  item.msgSentBy = "1234";
}

You can use foreach to update each element that meets your condition.

Here is an example in a more generic way:

var itemsToUpdate = await Context.friends.Where(f => f.Id == <someCondition>).ToListAsync();

foreach(var item in itemsToUpdate)
{
   item.property = updatedValue;
}
Context.SaveChanges()

In general you will most probably use async methods with await for db queries.

Printing all variables value from a class

Another simple approach is to let Lombok generate the toString method for you.

For this:

  1. Simply add Lombok to your project
  2. Add the annotation @ToString to the definition of your class
  3. Compile your class/project, and it is done

So for example in your case, your class would look like this:

@ToString
public class Contact {
    private String name;
    private String location;
    private String address;
    private String email;
    private String phone;
    private String fax;

    // Getters and setters.
}

Example of output in this case:

Contact(name=John, location=USA, address=SF, [email protected], phone=99999, fax=88888)

More details about how to use the annotation @ToString.

NB: You can also let Lombok generate the getters and setters for you, here is the full feature list.

Dropdownlist validation in Asp.net Using Required field validator

<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
    ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
    Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>

ALTER DATABASE failed because a lock could not be placed on database

In SQL Management Studio, go to Security -> Logins and double click your Login. Choose Server Roles from the left column, and verify that sysadmin is checked.

In my case, I was logged in on an account without that privilege.

HTH!

Node JS Promise.all and forEach

It's pretty straightforward with some simple rules:

  • Whenever you create a promise in a then, return it - any promise you don't return will not be waited for outside.
  • Whenever you create multiple promises, .all them - that way it waits for all the promises and no error from any of them are silenced.
  • Whenever you nest thens, you can typically return in the middle - then chains are usually at most 1 level deep.
  • Whenever you perform IO, it should be with a promise - either it should be in a promise or it should use a promise to signal its completion.

And some tips:

  • Mapping is better done with .map than with for/push - if you're mapping values with a function, map lets you concisely express the notion of applying actions one by one and aggregating the results.
  • Concurrency is better than sequential execution if it's free - it's better to execute things concurrently and wait for them Promise.all than to execute things one after the other - each waiting before the next.

Ok, so let's get started:

var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
    return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns

var actions = items.map(fn); // run the function over all items

// we now have a promises array and we want to wait for it

var results = Promise.all(actions); // pass array of promises

results.then(data => // or just .then(console.log)
    console.log(data) // [2, 4, 6, 8, 10]
);

// we can nest this of course, as I said, `then` chains:

var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
    data => Promise.all(data.map(fn))
).then(function(data){
    // the next `then` is executed after the promise has returned from the previous
    // `then` fulfilled, in this case it's an aggregate promise because of 
    // the `.all` 
    return Promise.all(data.map(fn));
}).then(function(data){
    // just for good measure
    return Promise.all(data.map(fn));
});

// now to get the results:

res2.then(function(data){
    console.log(data); // [16, 32, 48, 64, 80]
});

Is there a numpy builtin to reject outliers from a list

Benjamin Bannier's answer yields a pass-through when the median of distances from the median is 0, so I found this modified version a bit more helpful for cases as given in the example below.

def reject_outliers_2(data, m=2.):
    d = np.abs(data - np.median(data))
    mdev = np.median(d)
    s = d / (mdev if mdev else 1.)
    return data[s < m]

Example:

data_points = np.array([10, 10, 10, 17, 10, 10])
print(reject_outliers(data_points))
print(reject_outliers_2(data_points))

Gives:

[[10, 10, 10, 17, 10, 10]]  # 17 is not filtered
[10, 10, 10, 10, 10]  # 17 is filtered (it's distance, 7, is greater than m)

Using Chrome, how to find to which events are bound to an element

findEventHandlers is a jquery plugin, the raw code is here: https://raw.githubusercontent.com/ruidfigueiredo/findHandlersJS/master/findEventHandlers.js

Steps

  1. Paste the raw code directely into chrome's console(note:must have jquery loaded already)

  2. Use the following function call: findEventHandlers(eventType, selector);
    to find the corresponding's selector specified element's eventType handler.

Example:

findEventHandlers("click", "#clickThis");

Then if any, the available event handler will show bellow, you need to expand to find the handler, right click the function and select show function definition

See: https://blinkingcaret.wordpress.com/2014/01/17/quickly-finding-and-debugging-jquery-event-handlers/

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

how to get the base url in javascript

You can make PHP and JavaScript work together by generating the following line in each page template:

<script>
document.mybaseurl='<?php echo base_url('assets/css/themes/default.css');?>';
</script>

Then you can refer to document.mybaseurl anywhere in your JavaScript. This saves you some debugging and complexity because this variable is always consistent with the PHP calculation.

What is the difference between up-casting and down-casting with respect to class variable

Upcasting and downcasting are important part of Java, which allow us to build complicated programs using simple syntax, and gives us great advantages, like Polymorphism or grouping different objects. Java permits an object of a subclass type to be treated as an object of any superclass type. This is called upcasting. Upcasting is done automatically, while downcasting must be manually done by the programmer, and i'm going to give my best to explain why is that so.

Upcasting and downcasting are NOT like casting primitives from one to other, and i believe that's what causes a lot of confusion, when programmer starts to learn casting objects.

Polymorphism: All methods in java are virtual by default. That means that any method can be overridden when used in inheritance, unless that method is declared as final or static.

You can see the example below how getType(); works according to the object(Dog,Pet,Police Dog) type.

Assume you have three dogs

  1. Dog - This is the super Class.

  2. Pet Dog - Pet Dog extends Dog.

  3. Police Dog - Police Dog extends Pet Dog.

    public class Dog{ 
       public String getType () {
          System.out.println("NormalDog");
          return "NormalDog";
       }
     }
    
    /**
     * Pet Dog has an extra method dogName()
     */   
    public class PetDog extends Dog{ 
       public String getType () {
          System.out.println("PetDog");
          return "PetDog";
       }
       public String dogName () {
          System.out.println("I don't have Name !!");
          return "NO Name";
       }
     }
    
    /**
     * Police Dog has an extra method secretId()
     */
    public class PoliceDog extends PetDog{
    
     public String secretId() {
        System.out.println("ID");
        return "ID";
     }
    
     public String getType () {
         System.out.println("I am a Police Dog");
         return "Police Dog";
     }
    }
    

Polymorphism : All methods in java are virtual by default. That means that any method can be overridden when used in inheritance, unless that method is declared as final or static.(Explanation Belongs to Virtual Tables Concept)

Virtual Table / Dispatch Table : An object's dispatch table will contain the addresses of the object's dynamically bound methods. Method calls are performed by fetching the method's address from the object's dispatch table. The dispatch table is the same for all objects belonging to the same class, and is therefore typically shared between them.

public static void main (String[] args) {
      /**
       * Creating the different objects with super class Reference
       */
     Dog obj1 = new Dog();
`         /**
           *  Object of Pet Dog is created with Dog Reference since                
           *  Upcasting is done automatically for us we don't have to worry about it 
           *  
           */
     Dog obj2 = new PetDog();
`         /**
           *  Object of Police Dog is created with Dog Reference since                
           *  Upcasting is done automatically for us we don't have to worry       
           *  about it here even though we are extending PoliceDog with PetDog 
           *  since PetDog is extending Dog Java automatically upcast for us 
           */
      Dog obj3 = new PoliceDog();
}



 obj1.getType();

Prints Normal Dog

  obj2.getType();

Prints Pet Dog

 obj3.getType();

Prints Police Dog

Downcasting need to be done by the programmer manually

When you try to invoke the secretID(); method on obj3 which is PoliceDog object but referenced to Dog which is a super class in the hierarchy it throws error since obj3 don't have access to secretId() method.In order to invoke that method you need to Downcast that obj3 manually to PoliceDog

  ( (PoliceDog)obj3).secretID();

which prints ID

In the similar way to invoke the dogName();method in PetDog class you need to downcast obj2 to PetDog since obj2 is referenced to Dog and don't have access to dogName(); method

  ( (PetDog)obj2).dogName();

Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Dogs and want to downcast them all to a to their types, then there's a chance, that some of these Dogs are actually of different types i.e., PetDog, PoliceDog, and process fails, by throwing ClassCastException.

This is the reason you need to downcast your objects manually if you have referenced your objects to the super class type.

Note: Here by referencing means you are not changing the memory address of your ojects when you downcast it it still remains same you are just grouping them to particular type in this case Dog

Set background color of WPF Textbox in C# code

You can use hex colors:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

Converting a Uniform Distribution to a Normal Distribution

Where R1, R2 are random uniform numbers:

NORMAL DISTRIBUTION, with SD of 1:

sqrt(-2*log(R1))*cos(2*pi*R2)

This is exact... no need to do all those slow loops!

Reference: dspguide.com/ch2/6.htm

Get webpage contents with Python?

You can use urlib2 and parse the HTML yourself.

Or try Beautiful Soup to do some of the parsing for you.

Why can't Python parse this JSON data?

There are two types in this parsing.

  1. Parsing data from a file from a system path
  2. Parsing JSON from remote URL.

From a file, you can use the following

import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']

This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

How to activate JMX on my JVM for access with jconsole?

Running in a Docker container introduced a whole slew of additional problems for connecting so hopefully this helps someone. I ended up needed to add the following options which I'll explain below:

-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=${DOCKER_HOST_IP}
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.rmi.port=9998

DOCKER_HOST_IP

Unlike using jconsole locally, you have to advertise a different IP than you'll probably see from within the container. You'll need to replace ${DOCKER_HOST_IP} with the externally resolvable IP (DNS Name) of your Docker host.

JMX Remote & RMI Ports

It looks like JMX also requires access to a remote management interface (jstat) that uses a different port to transfer some data when arbitrating the connection. I didn't see anywhere immediately obvious in jconsole to set this value. In the linked article the process was:

  • Try and connect from jconsole with logging enabled
  • Fail
  • Figure out which port jconsole attempted to use
  • Use iptables/firewall rules as necessary to allow that port to connect

While that works, it's certainly not an automatable solution. I opted for an upgrade from jconsole to VisualVM since it let's you to explicitly specify the port on which jstatd is running. In VisualVM, add a New Remote Host and update it with values that correlate to the ones specified above:

Add Remote Host

Then right-click the new Remote Host Connection and Add JMX Connection...

Add JMX Connection

Don't forget to check the checkbox for Do not require SSL connection. Hopefully, that should allow you to connect.

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

Java dynamic array sizes?

It is a good practice get the amount you need to store first then initialize the array.

for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store. if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.

//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList(); 
//add a certain amount of data
for(int i=0;i<x;i++)
{
  al.add("data "+i); 
}

//get size of data inside
int size = al.size(); 
//initialize String array with the size you have
String strArray[] = new String[size]; 
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
  strArray[i] = al.get(i);
}

doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack

Creating threads - Task.Factory.StartNew vs new Thread()

Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.

Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.

This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.

How to convert timestamps to dates in Bash?

date -r <number>

works for me on Mac OS X.

How can I check if the current date/time is past a set date/time?

date_default_timezone_set('Asia/Kolkata');

$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
    echo "active";exit;
}else{
    echo "inactive";exit;
}

javascript jquery radio button click

it is always good to restrict the DOM search. so better to use a parent also, so that the entire DOM won't be traversed.

IT IS VERY FAST

<div id="radioBtnDiv">
  <input name="myButton" type="radio" class="radioClass" value="manual" checked="checked"/>
 <input name="myButton" type="radio" class="radioClass" value="auto" checked="checked"/>
</div>



 $("input[name='myButton']",$('#radioBtnDiv')).change(
    function(e)
    {
        // your stuffs go here
    });

How to set value to variable using 'execute' in t-sql?

The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised

You'll have to use a temp table/table variable outside of the dynamic SQL:

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)

INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')  

select * FROM @siteId

Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

Quicksort: Choosing the pivot

Don't try and get too clever and combine pivoting strategies. If you combined median of 3 with random pivot by picking the median of the first, last and a random index in the middle, then you'll still be vulnerable to many of the distributions which send median of 3 quadratic (so its actually worse than plain random pivot)

E.g a pipe organ distribution (1,2,3...N/2..3,2,1) first and last will both be 1 and the random index will be some number greater than 1, taking the median gives 1 (either first or last) and you get an extermely unbalanced partitioning.

'App not Installed' Error on Android

In the end I found out that no apps were being installed successfully, not just mine. I set the Install App default from SD card to Automatic. That fixed it.

postgres: upgrade a user to be a superuser?

You can create a SUPERUSER or promote USER, so for your case

$ sudo -u postgres psql -c "ALTER USER myuser WITH SUPERUSER;"

or rollback

$ sudo -u postgres psql -c "ALTER USER myuser WITH NOSUPERUSER;"

To prevent a command from logging when you set password, insert a whitespace in front of it, but check that your system supports this option.

$  sudo -u postgres psql -c "CREATE USER my_user WITH PASSWORD 'my_pass';"
$  sudo -u postgres psql -c "CREATE USER my_user WITH SUPERUSER PASSWORD 'my_pass';"

Python write line by line to a text file

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)

How to remove the focus from a TextBox in WinForms?

    //using System;
    //using System.Collections.Generic;
    //using System.Linq;

    private void Form1_Load(object sender, EventArgs e)
    {
        FocusOnOtherControl(Controls.Cast<Control>(), button1);
    }

    private void FocusOnOtherControl<T>(IEnumerable<T> controls, Control focusOnMe) where T : Control
    {
        foreach (var control in controls)
        {
            if (control.GetType().Equals(typeof(TextBox)))
            {
                control.TabStop = false;
                control.LostFocus += new EventHandler((object sender, EventArgs e) =>
                {                     
                    focusOnMe.Focus();
                });
            }
        }
    }

Store images in a MongoDB database

You can try this one:

String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();

Why is my JavaScript function sometimes "not defined"?

Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)

JPA entity without id

I know that JPA entities must have primary key but I can't change database structure due to reasons beyond my control.

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?

If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id in JPA.

If your table has no unique columns at all, you can use all of the columns as the Id.

And if your table has some id but your entity doesn't, make it an Embeddable.

ImportError: No module named PIL

use pil instead of PIL

from pil import Image

Java - Search for files in a directory

This looks like a homework question, so I'll just give you a few pointers:

Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.

You're not using Scanner for anything, and it's not needed here, get rid of it.

Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

insert data into database using servlet and jsp in eclipse

In your JSP at line <form> tag, try this code

<form name="registrationform" action="Register" method="post">

How can I get the values of data attributes in JavaScript code?

if you are targeting data attribute in Html element,

document.dataset will not work

you should use

document.querySelector("html").dataset.pbUserId

or

document.getElementsByTagName("html")[0].dataset.pbUserId

is inaccessible due to its protection level

myClub.distance = Console.ReadLine();

should be

myClub.mydistance = Console.ReadLine(); 

use your public properties that you have defined for others as well instead of the protected field members.

How can I remove specific rules from iptables?

Use -D command, this is how man page explains it:

-D, --delete chain rule-specification
-D, --delete chain rulenum
    Delete  one  or more rules from the selected chain.  
    There are two versions of this command: 
    the rule can be specified as a number in the chain (starting at 1 for the first rule) or a rule to match.

Do realize this command, like all other command(-A, -I) works on certain table. If you'are not working on the default table(filter table), use -t TABLENAME to specify that target table.

Delete a rule to match

iptables -D INPUT -i eth0 -p tcp --dport 443 -j ACCEPT

Note: This only deletes the first rule matched. If you have many rules matched(this can happen in iptables), run this several times.

Delete a rule specified as a number

iptables -D INPUT 2

Other than counting the number you can list the line-number with --line-number parameter, for example:

iptables -t nat -nL --line-number

Switch statement for greater-than/less-than

Updating the accepted answer (can't comment yet). As of 1/12/16 using the demo jsfiddle in chrome, switch-immediate is the fastest solution.

Results: Time resolution: 1.33

   25ms "if-immediate" 150878146 
   29ms "if-indirect" 150878146
   24ms "switch-immediate" 150878146
   128ms "switch-range" 150878146
   45ms "switch-range2" 150878146
   47ms "switch-indirect-array" 150878146
   43ms "array-linear-switch" 150878146
   72ms "array-binary-switch" 150878146

Finished

 1.04 (   25ms) if-immediate
 1.21 (   29ms) if-indirect
 1.00 (   24ms) switch-immediate
 5.33 (  128ms) switch-range
 1.88 (   45ms) switch-range2
 1.96 (   47ms) switch-indirect-array
 1.79 (   43ms) array-linear-switch
 3.00 (   72ms) array-binary-switch

How to get height of Keyboard?

// Step 1 :- Register NotificationCenter

ViewDidLoad() {

   self.yourtextfield.becomefirstresponder()

   // Register your Notification, To know When Key Board Appears.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides

    func keyboardWillShow(notification:NSNotification) {
        let userInfo:NSDictionary = notification.userInfo! as NSDictionary
        let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
    }

    func keyboardWillHide(notification:NSNotification) {
        tblViewListData.frame.size.height = fltTblHeight
    }

How can one display images side by side in a GitHub README.md?

For markdown table syntax see:

https://www.markdownguide.org/extended-syntax/#tables


Quick summary:

To quickly understand the syntax used in other answers, it helps to start from a more complete intuitive and easier to remember syntax, and then a minimalized version with the same result.

Basic example:

| Header A       | Header B       |
| -------------- | -------------- |
| row 1 col 1    | row 1 col 2    |
| row 2 column 1 | row 2 column 2 |

Same result in a more minimalist form (cell widths can vary) :

Header A | Header B
--- | ---
row 1 col 1 | row 1 col 2
row 2 column 1 | row 2 column 2

And more related to the question: side by side images with labels on top:

label 1 | label 2
--- | ---
![](https://...image1.png) | ![](https://...image2.png)

( use :--- , ---: , and :---: for (text) alignment in the column, respectively: left, right, center )