Programs & Examples On #Signedxml

The SignedXml class is the main class used for XML signing and verification (XMLDSIG) in the .NET Framework.

xcopy file, rename, suppress "Does xxx specify a file name..." message

Place an asterisk(*) at the end of the destination path to skip the dispute of D and F.

Example:

xcopy "compressedOutput.xml" "../../Execute Scripts/APIAutomation/Libraries/rerunlastfailedbuild.xml*"

How can I use modulo operator (%) in JavaScript?

It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:

10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.

Apparently it is not the same as the modulo operator entirely.

Tesseract OCR simple example

Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing

Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.

Setup

To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.

Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.

VC++ Directories>Include Directories:

..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:

include

include

Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.

When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.

tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample

You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.

How to add an extra row to a pandas dataframe

Upcoming pandas 0.13 version will allow to add rows through loc on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.

Description is here and this new feature is called Setting With Enlargement.

Comments in Android Layout xml

As other said, the comment in XML are like this

<!-- this is a comment -->

Notice that they can span on multiple lines

<!--
    This is a comment
    on multiple lines
-->

But they cannot be nested

<!-- This <!-- is a comment --> This is not -->

Also you cannot use them inside tags

<EditText <!--This is not valid--> android:layout_width="fill_parent" />

Exception from HRESULT: 0x800A03EC Error

Got the same error when tried to export a large Excel file (~150.000 rows) Fixed with the following code

Application xlApp = new Application();
xlApp.DefaultSaveFormat = XlFileFormat.xlOpenXMLWorkbook;

Why doesn't C++ have a garbage collector?

Imposing garbage collection is really a low level to high level paradigm shift.

If you look at the way strings are handled in a language with garbage collection, you will find they ONLY allow high level string manipulation functions and do not allow binary access to the strings. Simply put, all string functions first check the pointers to see where the string is, even if you are only drawing out a byte. So if you are doing a loop that processes each byte in a string in a language with garbage collection, it must compute the base location plus offset for each iteration, because it cannot know when the string has moved. Then you have to think about heaps, stacks, threads, etc etc.

How can I pause setInterval() functions?

I know this thread is old, but this could be another solution:

var do_this = null;

function y(){
   // what you wanna do
}

do_this = setInterval(y, 1000);

function y_start(){
    do_this = setInterval(y, 1000);
};
function y_stop(){
    do_this = clearInterval(do_this);
};

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Nobody used the STL algorithm/mismatch function yet. If this returns true, prefix is a prefix of 'toCheck':

std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()

Full example prog:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char** argv) {
    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "Will print true if 'prefix' is a prefix of string" << std::endl;
        return -1;
    }
    std::string prefix(argv[1]);
    std::string toCheck(argv[2]);
    if (prefix.length() > toCheck.length()) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "'prefix' is longer than 'string'" <<  std::endl;
        return 2;
    }
    if (std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()) {
        std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck << '"' << std::endl;
        return 0;
    } else {
        std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"' << toCheck << '"' << std::endl;
        return 1;
    }
}

Edit:

As @James T. Huggett suggests, std::equal is a better fit for the question: Is A a prefix of B? and is slight shorter code:

std::equal(prefix.begin(), prefix.end(), toCheck.begin())

Full example prog:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char **argv) {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "Will print true if 'prefix' is a prefix of string"
              << std::endl;
    return -1;
  }
  std::string prefix(argv[1]);
  std::string toCheck(argv[2]);
  if (prefix.length() > toCheck.length()) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "'prefix' is longer than 'string'" << std::endl;
    return 2;
  }
  if (std::equal(prefix.begin(), prefix.end(), toCheck.begin())) {
    std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck
              << '"' << std::endl;
    return 0;
  } else {
    std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"'
              << toCheck << '"' << std::endl;
    return 1;
  }
}

Download old version of package with NuGet

In NuGet 3.0 the Get-Package command is deprecated and replaced with Find-Package command.

Find-Package Common.Logging -AllVersions

See the NuGet command reference docs for details.

This is the message shown if you try to use Get-Package in Visual Studio 2015.

This Command/Parameter combination has been deprecated and will be removed
in the next release. Please consider using the new command that replaces it: 
'Find-Package [-Id] -AllVersions'

Or as @Yishai said, you can use the version number dropdown in the NuGet screen in Visual Studio.

What is the strict aliasing rule?

After reading many of the answers, I feel the need to add something:

Strict aliasing (which I'll describe in a bit) is important because:

  1. Memory access can be expensive (performance wise), which is why data is manipulated in CPU registers before being written back to the physical memory.

  2. If data in two different CPU registers will be written to the same memory space, we can't predict which data will "survive" when we code in C.

    In assembly, where we code the loading and unloading of CPU registers manually, we will know which data remains intact. But C (thankfully) abstracts this detail away.

Since two pointers can point to the same location in the memory, this could result in complex code that handles possible collisions.

This extra code is slow and hurts performance since it performs extra memory read / write operations which are both slower and (possibly) unnecessary.

The Strict aliasing rule allows us to avoid redundant machine code in cases in which it should be safe to assume that two pointers don't point to the same memory block (see also the restrict keyword).

The Strict aliasing states it's safe to assume that pointers to different types point to different locations in the memory.

If a compiler notices that two pointers point to different types (for example, an int * and a float *), it will assume the memory address is different and it will not protect against memory address collisions, resulting in faster machine code.

For example:

Lets assume the following function:

void merge_two_ints(int *a, int *b) {
  *b += *a;
  *a += *b;
}

In order to handle the case in which a == b (both pointers point to the same memory), we need to order and test the way we load data from the memory to the CPU registers, so the code might end up like this:

  1. load a and b from memory.

  2. add a to b.

  3. save b and reload a.

    (save from CPU register to the memory and load from the memory to the CPU register).

  4. add b to a.

  5. save a (from the CPU register) to the memory.

Step 3 is very slow because it needs to access the physical memory. However, it's required to protect against instances where a and b point to the same memory address.

Strict aliasing would allow us to prevent this by telling the compiler that these memory addresses are distinctly different (which, in this case, will allow even further optimization which can't be performed if the pointers share a memory address).

  1. This can be told to the compiler in two ways, by using different types to point to. i.e.:

    void merge_two_numbers(int *a, long *b) {...}
    
  2. Using the restrict keyword. i.e.:

    void merge_two_ints(int * restrict a, int * restrict b) {...}
    

Now, by satisfying the Strict Aliasing rule, step 3 can be avoided and the code will run significantly faster.

In fact, by adding the restrict keyword, the whole function could be optimized to:

  1. load a and b from memory.

  2. add a to b.

  3. save result both to a and to b.

This optimization couldn't have been done before, because of the possible collision (where a and b would be tripled instead of doubled).

Jackson and generic type reference

I modified rushidesai1's answer to include a working example.

JsonMarshaller.java

import java.io.*;
import java.util.*;

public class JsonMarshaller<T> {
    private static ClassLoader loader = JsonMarshaller.class.getClassLoader();

    public static void main(String[] args) {
        try {
            JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
            String jsonString = read(loader.getResourceAsStream("data.json"));
            List<Station> stations = marshaller.unmarshal(jsonString);
            stations.forEach(System.out::println);
            System.out.println(marshaller.marshal(stations));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("resource")
    public static String read(InputStream ios) {
        return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
    }
}

Output

Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]

JsonMarshallerUnmarshaller.java

import java.io.*;
import java.util.List;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

public class JsonMarshallerUnmarshaller<T> {
    private ObjectMapper mapper;
    private Class<T> targetClass;

    public JsonMarshallerUnmarshaller(Class<T> targetClass) {
        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

        mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(introspector);
        mapper.getSerializationConfig().with(introspector);

        this.targetClass = targetClass;
    }

    public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
        return parseList(jsonString, mapper, targetClass);
    }

    public String marshal(List<T> list) throws JsonProcessingException {
        return mapper.writeValueAsString(list);
    }

    public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(str, listType(mapper, clazz));
    }

    public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(is, listType(mapper, clazz));
    }

    public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
        return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
    }
}

Station.java

public class Station {
    private long id;
    private String title;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
    }
}

data.json

[{
  "id": 123,
  "title": "my title",
  "name": "my name"
}, {
  "id": 456,
  "title": "my title 2",
  "name": "my name 2"
}]

how to install apk application from my pc to my mobile android

1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.

2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...

Bootstrap 3 select input form inline

It requires a minor CSS addition to make it work with Bootstrap 3:

_x000D_
_x000D_
.input-group-btn:last-child > .form-control {_x000D_
  margin-left: -1px;_x000D_
  width: auto;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
  <div class="input-group">_x000D_
    <input class="form-control" name="q" type="text" placeholder="Search">_x000D_
    _x000D_
    <div class="input-group-btn">_x000D_
      <select class="form-control" name="category">_x000D_
        <option>select</option>_x000D_
        <option>1</option>_x000D_
        <option>2</option>_x000D_
        <option>3</option>_x000D_
      </select>_x000D_
    </div>_x000D_
    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

128M == 134217728, the number you are seeing.

The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.

Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.

How to call any method asynchronously in c#

Starting with .Net 4.5 you can use Task.Run to simply start an action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

Task.Run vs Task.Factory.StartNew

How do you use math.random to generate random ints?

int abc= (Math.random()*100);//  wrong 

you wil get below error message

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int

int abc= (int) (Math.random()*100);// add "(int)" data type

,known as type casting

if the true result is

int abc= (int) (Math.random()*1)=0.027475

Then you will get output as "0" because it is a integer data type.

int abc= (int) (Math.random()*100)=0.02745

output:2 because (100*0.02745=2.7456...etc)

A transport-level error has occurred when receiving results from the server

I know this may not help everyone (who knows, maybe yes), but I had the same problem and after some time, we realized that the cause was something out of the code itself.

The computer trying to reach the server, was in another network, the connection could be established but then dropped.

The way we used to fix it, was to add a static route to the computer, allowing direct access to the server without passing thru the firewall.

route add –p YourServerNetwork mask NetworkMask Router 

Sample:

route add –p 172.16.12.0 mask 255.255.255.0 192.168.11.2 

I hope it helps someone, it's better to have this, at least as a clue, so if you face it, you know how to solve it.

Where can I get a list of Countries, States and Cities?

geonames.org has an api and a data dump of worldwide geographical places.

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

I came across this question searching for a simular problem. I'm making a webpage with responsive design and the width of elements placed on the page is set to a percent of the screen width. The height is set with a vw value.

Since I'm adding posts with PHP and a database backend, pure CSS was out of the question. I did however find the jQuery/javascript solution a bit troblesome, so I came up with a neat (so I think myself at least) solution.

HTML (or php)

_x000D_
_x000D_
div.imgfill {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: 50%  50%;_x000D_
  background-size: cover;_x000D_
  width: 33.333%;_x000D_
  height: 18vw;_x000D_
  border: 1px solid black; /*frame of the image*/_x000D_
  margin: -1px;_x000D_
}
_x000D_
<div class="imgfill" style="background-image:url(source/image.jpg);">_x000D_
  This might be some info_x000D_
</div>_x000D_
<div class="imgfill" style="background-image:url(source/image2.jpg);">_x000D_
  This might be some info_x000D_
</div>_x000D_
<div class="imgfill" style="background-image:url(source/image3.jpg);">_x000D_
  This might be some info_x000D_
</div>
_x000D_
_x000D_
_x000D_

By using style="" it's posible to have PHP update my page dynamically and the CSS-styling together with style="" will end up in a perfectly covered image, scaled to cover the dynamic div-tag.

Clearing a string buffer/builder after loop

The easiest way to reuse the StringBuffer is to use the method setLength()

public void setLength(int newLength)

You may have the case like

StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

Eclipse: All my projects disappeared from Project Explorer

I tried differently for the same issue and worked .

Go to your project location in hard drive. ex: /home/user/workspace/project/settings and Delete this file org.eclipse.core.resources.prefs

For full details check out bellow link

http://errorkode.com/viewtopic.php?f=20&t=8&sid=40cff1661bf0ace12878d6d6fb7e75ac

Multiple parameters in a List. How to create without a class?

To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.

public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
    public void Add(Tkey key, TValue value){
        base.Add(new KeyValuePair<Tkey, TValue>(key, value));
    }
}

What this means is that the constructor can be initialized with better syntax::

var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};

I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.

If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple is a class not a struct like KeyValuePair this is an interesting distinction).

Curiously enough, the initializer list syntax is available on any IEnumerable and it allows you to use any Add method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[] member as a params object[] member.

How to disable CSS in Browser for testing purposes

Firefox (Win and Mac)

  • Via the menu toolbar, choose: "View" > "Page Style" > "No Style"
  • Via the Web Developer Toolbar, choose: "CSS" > "Disable Styles" > "All Styles"

If the Web Dev Toolbar is installed, people can use this keyboard shortcuts: Command + Shift + S (Mac) and Control + Shift + S (Win)

  • Safari (Mac): Via the menu toolbar, choose "Develop" > "Disable Styles"
  • Opera (Win): Via the menu, choose "Page" > "Style" > "User Mode"
  • Chrome (Win): Via the gear icon, choose the "CSS" tab > "Disable All Styles"
  • Internet Explorer 8: Via the menu toolbar, choose "View" > "Style" > "No Style"
  • Internet Explorer 7: via the IE Developer Toolbar menu: Disable > All CSS
  • Internet Explorer 6: Via the Web Accessibility Toolbar, choose "CSS" > "Disable CSS"

ASP.Net MVC How to pass data from view to controller

In case you don't want/need to post:

@Html.ActionLink("link caption", "actionName", new { Model.Page })  // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);

[HttpGet]
public ActionResult actionName(int reportID)
{

Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)

Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.

Get the current language in device

If you choose a language you can't type this Greek may be helpful.

getDisplayLanguage().toString() = English
getLanguage().toString() = en 
getISO3Language().toString() = eng
getDisplayLanguage()) = English
getLanguage() = en
getISO3Language() = eng

Now try it with Greek

getDisplayLanguage().toString() = ????????
getLanguage().toString() = el
getISO3Language().toString() = ell
getDisplayLanguage()) = ????????
getLanguage() = el
getISO3Language() = ell

How to count occurrences of a column value efficiently in SQL?

select s.id, s.age, c.count
from students s
inner join (
    select age, count(*) as count
    from students
    group by age
) c on s.age = c.age
order by id

Delayed function calls

Building upon the answer from David O'Donoghue here is an optimized version of the Delayed Delegate:

using System.Windows.Forms;
using System.Collections.Generic;
using System;

namespace MyTool
{
    public class DelayedDelegate
    {
       static private DelayedDelegate _instance = null;

        private Timer _runDelegates = null;

        private Dictionary<MethodInvoker, DateTime> _delayedDelegates = new Dictionary<MethodInvoker, DateTime>();

        public DelayedDelegate()
        {
        }

        static private DelayedDelegate Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DelayedDelegate();
                }

                return _instance;
            }
        }

        public static void Add(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay * 1000);
        }

        public static void AddMilliseconds(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay);
        }

        private void AddNewDelegate(MethodInvoker pMethod, int pDelay)
        {
            if (_runDelegates == null)
            {
                _runDelegates = new Timer();
                _runDelegates.Tick += RunDelegates;
            }
            else
            {
                _runDelegates.Stop();
            }

            _delayedDelegates.Add(pMethod, DateTime.Now + TimeSpan.FromMilliseconds(pDelay));

            StartTimer();
        }

        private void StartTimer()
        {
            if (_delayedDelegates.Count > 0)
            {
                int delay = FindSoonestDelay();
                if (delay == 0)
                {
                    RunDelegates();
                }
                else
                {
                    _runDelegates.Interval = delay;
                    _runDelegates.Start();
                }
            }
        }

        private int FindSoonestDelay()
        {
            int soonest = int.MaxValue;
            TimeSpan remaining;

            foreach (MethodInvoker invoker in _delayedDelegates.Keys)
            {
                remaining = _delayedDelegates[invoker] - DateTime.Now;
                soonest = Math.Max(0, Math.Min(soonest, (int)remaining.TotalMilliseconds));
            }

            return soonest;
        }

        private void RunDelegates(object pSender = null, EventArgs pE = null)
        {
            try
            {
                _runDelegates.Stop();

                List<MethodInvoker> removeDelegates = new List<MethodInvoker>();

                foreach (MethodInvoker method in _delayedDelegates.Keys)
                {
                    if (DateTime.Now >= _delayedDelegates[method])
                    {
                        method();

                        removeDelegates.Add(method);
                    }
                }

                foreach (MethodInvoker method in removeDelegates)
                {
                    _delayedDelegates.Remove(method);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                StartTimer();
            }
        }
    }
}

The class could be slightly more improved by using a unique key for the delegates. Because if you add the same delegate a second time before the first one fired, you might get a problem with the dictionary.

How to go back last page

in angular 4 use preserveQueryParams, ex:

url: /list?page=1

<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>

When clicking the link, you are redirected edit/10?page=1, preserving params

ref: https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

Returning pointer from a function

Allocate memory before using the pointer. If you don't allocate memory *point = 12 is undefined behavior.

int *fun()
{
    int *point = malloc(sizeof *point); /* Mandatory. */
    *point=12;  
    return point;
}

Also your printf is wrong. You need to dereference (*) the pointer.

printf("%d", *ptr);
             ^

How can getContentResolver() be called in Android?

The getContentResolver()method is also used when you query a Contact, using a Cursor object. I have used getContentResolver() to query the Android phone Contacts app, looking for contact info from a person's phone number, to include in my app. The different elements in a query (as shown below) represent what kind of contact details you want, and if they should be ordered, etc. Here is another example.

From the Content Provider Basics page from Android docs.

// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
    UserDictionary.Words.CONTENT_URI,   // The content URI of the words table
    mProjection,                        // The columns to return for each row
    mSelectionClause                    // Selection criteria
    mSelectionArgs,                     // Selection criteria
    mSortOrder);                        // The sort order for the returned rows

how do I use an enum value on a switch statement in C++

You can use an enumerated value just like an integer:

myChoice c;

...

switch( c ) {
case EASY:
    DoStuff();
    break;
case MEDIUM:
    ...
}

Convert SVG image to PNG with PHP

When converting SVG to transparent PNG, don't forget to put this BEFORE $imagick->readImageBlob():

$imagick->setBackgroundColor(new ImagickPixel('transparent'));

How do I check for a network connection?

Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:

  1. NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt. This file is a plain-text file and contains only the text 'Microsoft NCSI'.
  2. NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.

Using :before CSS pseudo element to add image to modal

You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.

.Modal:before{
  content: '';
  background:url('blackCarrot.png');
  width: /* width of the image */;
  height: /* height of the image */;
  display: block;
}

Get parent directory of running script

Here is what I use since I am not running > 5.2

function getCurrentOrParentDirectory($type='current')
{
    if ($type == 'current') {
        $path = dirname(__FILE__);  
    } else {
        $path = dirname(dirname(__FILE__));
    }
    $position = strrpos($path, '/') + 1;
    return substr($path, $position);
}

Double dirname with file as suggested by @mike b for the parent directory, and current directory is found by just using that syntax once.

Note this function only returns the NAME, slashes have to be added afterwards.

Is there any use for unique_ptr with array?

I have used unique_ptr<char[]> to implement a preallocated memory pools used in a game engine. The idea is to provide preallocated memory pools used instead of dynamic allocations for returning collision requests results and other stuff like particle physics without having to allocate / free memory at each frame. It's pretty convenient for this kind of scenarios where you need memory pools to allocate objects with limited life time (typically one, 2 or 3 frames) that do not require destruction logic (only memory deallocation).

Inserting image into IPython notebook markdown

First make sure you are in markdown edit model in the ipython notebook cell

This is an alternative way to the method proposed by others <img src="myimage.png">:

![title](img/picture.png)

It also seems to work if the title is missing:

![](img/picture.png)

Note no quotations should be in the path. Not sure if this works for paths with white spaces though!

Soft hyphen in HTML (<wbr> vs. &shy;)

Unfortunately, &shy's support is so inconsistent between browsers that it can't really be used.

QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.

2013 edit: According to QuirksMode, &shy; now works/is supported on all major browsers.

Implementing a simple file download servlet

The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.

You can easily achieve it through:

HttpServletResponse.sendRedirect()

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

SQL JOIN and different types of JOINs

Definition:


JOINS are way to query the data that combined together from multiple tables simultaneously.

Types of JOINS:


Concern to RDBMS there are 5-types of joins:

  • Equi-Join: Combines common records from two tables based on equality condition. Technically, Join made by using equality-operator (=) to compare values of Primary Key of one table and Foreign Key values of another table, hence result set includes common(matched) records from both tables. For implementation see INNER-JOIN.

  • Natural-Join: It is enhanced version of Equi-Join, in which SELECT operation omits duplicate column. For implementation see INNER-JOIN

  • Non-Equi-Join: It is reverse of Equi-join where joining condition is uses other than equal operator(=) e.g, !=, <=, >=, >, < or BETWEEN etc. For implementation see INNER-JOIN.

  • Self-Join:: A customized behavior of join where a table combined with itself; This is typically needed for querying self-referencing tables (or Unary relationship entity). For implementation see INNER-JOINs.

  • Cartesian Product: It cross combines all records of both tables without any condition. Technically, it returns the result set of a query without WHERE-Clause.

As per SQL concern and advancement, there are 3-types of joins and all RDBMS joins can be achieved using these types of joins.

  1. INNER-JOIN: It merges(or combines) matched rows from two tables. The matching is done based on common columns of tables and their comparing operation. If equality based condition then: EQUI-JOIN performed, otherwise Non-EQUI-Join.

  2. OUTER-JOIN: It merges(or combines) matched rows from two tables and unmatched rows with NULL values. However, can customized selection of un-matched rows e.g, selecting unmatched row from first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.

    2.1. LEFT Outer JOIN (a.k.a, LEFT-JOIN): Returns matched rows from two tables and unmatched from the LEFT table(i.e, first table) only.

    2.2. RIGHT Outer JOIN (a.k.a, RIGHT-JOIN): Returns matched rows from two tables and unmatched from the RIGHT table only.

    2.3. FULL OUTER JOIN (a.k.a OUTER JOIN): Returns matched and unmatched from both tables.

  3. CROSS-JOIN: This join does not merges/combines instead it performs Cartesian product.

enter image description here Note: Self-JOIN can be achieved by either INNER-JOIN, OUTER-JOIN and CROSS-JOIN based on requirement but the table must join with itself.

For more information:

Examples:

1.1: INNER-JOIN: Equi-join implementation

SELECT  *
FROM Table1 A 
 INNER JOIN Table2 B ON A.<Primary-Key> =B.<Foreign-Key>;

1.2: INNER-JOIN: Natural-JOIN implementation

Select A.*, B.Col1, B.Col2          --But no B.ForeignKeyColumn in Select
 FROM Table1 A
 INNER JOIN Table2 B On A.Pk = B.Fk;

1.3: INNER-JOIN with NON-Equi-join implementation

Select *
 FROM Table1 A INNER JOIN Table2 B On A.Pk <= B.Fk;

1.4: INNER-JOIN with SELF-JOIN

Select *
 FROM Table1 A1 INNER JOIN Table1 A2 On A1.Pk = A2.Fk;

2.1: OUTER JOIN (full outer join)

Select *
 FROM Table1 A FULL OUTER JOIN Table2 B On A.Pk = B.Fk;

2.2: LEFT JOIN

Select *
 FROM Table1 A LEFT OUTER JOIN Table2 B On A.Pk = B.Fk;

2.3: RIGHT JOIN

Select *
 FROM Table1 A RIGHT OUTER JOIN Table2 B On A.Pk = B.Fk;

3.1: CROSS JOIN

Select *
 FROM TableA CROSS JOIN TableB;

3.2: CROSS JOIN-Self JOIN

Select *
 FROM Table1 A1 CROSS JOIN Table1 A2;

//OR//

Select *
 FROM Table1 A1,Table1 A2;

Enable UTF-8 encoding for JavaScript

The encoding for the page is not set correctly. Either add a header

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

or use set the appropriate http header.

Content-Type:text/html; charset=UTF-8

Firefox also allows you to change the encoding in View -> Character encoding.

If that's ok, I think javascript should handle UTF8 just fine.

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Html.Partial: returns MvcHtmlString and slow

Html.RenderPartial: directly render/write on output stream and returns void and it's very fast in comparison to Html.Partial

React-router urls don't work when refreshing or writing manually

The router can be called in two different ways, depending on whether the navigation occurs on the client or on the server. You have it configured for client-side operation. The key parameter is the second one to the run method, the location.

When you use the React Router Link component, it blocks browser navigation and calls transitionTo to do a client-side navigation. You are using HistoryLocation, so it uses the HTML5 history API to complete the illusion of navigation by simulating the new URL in the address bar. If you're using older browsers, this won't work. You would need to use the HashLocation component.

When you hit refresh, you bypass all of the React and React Router code. The server gets the request for /joblist and it must return something. On the server you need to pass the path that was requested to the run method in order for it to render the correct view. You can use the same route map, but you'll probably need a different call to Router.run. As Charles points out, you can use URL rewriting to handle this. Another option is to use a node.js server to handle all requests and pass the path value as the location argument.

In express, for example, it might look like this:

var app = express();

app.get('*', function (req, res) { // This wildcard method handles all requests

    Router.run(routes, req.path, function (Handler, state) {
        var element = React.createElement(Handler);
        var html = React.renderToString(element);
        res.render('main', { content: html });
    });
});

Note that the request path is being passed to run. To do this, you'll need to have a server-side view engine that you can pass the rendered HTML to. There are a number of other considerations using renderToString and in running React on the server. Once the page is rendered on the server, when your app loads in the client, it will render again, updating the server-side rendered HTML as needed.

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Git vs Team Foundation Server

I think, the statement

everyone hates it except me

makes any further discussion waste: when you keep using Git, they will blame you if anything goes wrong.

Apart from this, for me Git has two advantages over a centralized VCS that I appreciate most (as partly described by Rob Sobers):

  • automatic backup of the whole repo: everytime someone pulls from the central repo, he/she gets a full history of the changes. When one repo gets lost: don't worry, take one of those present on every workstation.
  • offline repo access: when I'm working at home (or in an airplane or train), I can see the full history of the project, every single checkin, without starting up my VPN connection to work and can work like I were at work: checkin, checkout, branch, anything.

But as I said: I think that you're fighting a lost battle: when everyone hates Git, don't use Git. It could help you more to know why they hate Git instead of trying them to convince them.

If they simply don't want it 'cause it's new to them and are not willing to learn something new: are you sure that you will do successful development with that staff?

Does really every single person hate Git or are they influenced by some opinion leaders? Find the leaders and ask them what's the problem. Convince them and you'll convince the rest of the team.

If you cannot convince the leaders: forget about using Git, take the TFS. Will make your life easier.

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Here is how I got without '[' and ']' in C#:

        var text = "This is a test string [more or less]";
        //Getting only string between '[' and ']'
        Regex regex = new Regex(@"\[(.+?)\]");
        var matchGroups = regex.Matches(text);
        for (int i = 0; i < matchGroups.Count; i++)
        {
            Console.WriteLine(matchGroups[i].Groups[1]);
        }

The output is:

more or less

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Postgresql : syntax error at or near "-"

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

Split page vertically using CSS

I guess your elements on the page messes up because you don't clear out your floats, check this out

Demo

HTML

<div class="wrap">
    <div class="floatleft"></div>
    <div class="floatright"></div>
    <div style="clear: both;"></div>
</div>

CSS

.wrap {
    width: 100%;
}

.floatleft {
    float:left; 
    width: 80%;
    background-color: #ff0000;
    height: 400px;
}

.floatright {
float: right;
    background-color: #00ff00;
    height: 400px;
    width: 20%;
}

typesafe select onChange event using reactjs and typescript

In addition to @thoughtrepo's answer:

Until we do not have definitely typed events in React it might be useful to have a special target interface for input controls:

export interface FormControlEventTarget extends EventTarget{
    value: string;
}

And then in your code cast to this type where is appropriate to have IntelliSense support:

 import {FormControlEventTarget} from "your.helper.library"

 (event.target as FormControlEventTarget).value;

remove legend title in ggplot

You were almost there : just add theme(legend.title=element_blank())

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  theme(legend.title=element_blank())

This page on Cookbook for R gives plenty of details on how to customize legends.

The Role Manager feature has not been enabled

I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager> tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.

Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:

  1. Press Ctrl+Q, type nuget and click on "Manage NuGet Packages";
  2. Press Ctrl+E, type providers and in the list it should show up "Microsoft ASP.NET Universal Providers Core Libraries" and "Microsoft ASP.NET Universal Providers for LocalDB" (both created by Microsoft);
  3. Click on the Install button in both of them and close the NuGet window;
  4. Check your Web.config and now you should have at least one <providers> tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:

    <roleManager defaultProvider="DefaultRoleProvider">
        <providers>
           <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
        </providers>
    </roleManager>
    
  5. Add enabled="true" like so:

    <roleManager defaultProvider="DefaultRoleProvider" enabled="true">
    
  6. Press F6 to Build and now it should be OK to proceed to a database update without having that exception:

    1. Press Ctrl+Q, type manager, click on "Package Manager Console";
    2. Type update-database -verbose and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;
    3. Press Ctrl+W+L to open the Server Explorer and you should be able to check in Data Connections > DefaultConnection > Tables the Roles and UsersInRoles tables among the newly created tables!

Getting MAC Address

You can do this with psutil which is cross-platform:

import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]

How do I stop/start a scheduled task on a remote computer programmatically?

Try this:

schtasks /change /ENABLE /tn "Auto Restart" /s mycomutername /u mycomputername\username/p mypassowrd

php: check if an array has duplicates

$duplicate = false;

 if(count(array) != count(array_unique(array))){
   $duplicate = true;
}

How to solve ADB device unauthorized in Android ADB host device?

Try this steps:

  1. unplug device
  2. adb kill-server
  3. adb start-server
  4. plug device

You need to allow Allow USB debugging in your device when popup.

Editing specific line in text file in Python

If your text contains only one individual:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def roplo(file_name,what):
    patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
    with open(file_name,'rb+') as f:
        ch = f.read()
        f.seek(0)
        f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')


# after treatment
with open('pers.txt','rb') as h:
    print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If your text contains several individuals:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim  \n  dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def ripli(file_name,who,what):
    with open(file_name,'rb+') as f:
        ch = f.read()
        x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
        f.seek(x)
        f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')


# after treatment
with open('pers.txt','rb') as h:
    print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that’s the same idea as senderle’s one.

But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:

from cPickle import dump, load

with open('cards','wb') as f:
    dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)

with open('cards','rb') as g:
    id_cards = load(g)
print 'id_cards before change==',id_cards

id_cards['Jim'][0] = 'Wizard'

with open('cards','w') as h:
    dump(id_cards,h)

with open('cards') as e:
    id_cards = load(e)
print '\nid_cards after change==',id_cards

Pure CSS to make font-size responsive based on dynamic amount of characters

Create a lookup table that computes font-size based on the length of the string inside your <div>.

const fontSizeLookupTable = () => {
  // lookup table looks like: [ '72px', ..., '32px', ..., '16px', ..., ]
  let a = [];
  // adjust this based on how many characters you expect in your <div>
  a.length = 32;
  // adjust the following ranges empirically
  a.fill( '72px' ,     );
  a.fill( '32px' , 4 , );
  a.fill( '16px' , 8 , );
  // add more ranges as necessary
  return a;
}

const computeFontSize = stringLength => {
  const table = fontSizeLookupTable();
  return stringLength < table.length ? table[stringLength] : '16px';
}

Adjust and tune all parameters by empirical test.

Jquery, set value of td in a table?

Try the code below :

$('#detailInfo').html('your value')

How do I login and authenticate to Postgresql after a fresh install?

The main difference between logging in with a postgres user or any other user created by us, is that when using the postgres user it is NOT necessary to specify the host with -h and instead for another user if.

Login with postgres user

$ psql -U postgres 

Creation and login with another user

# CREATE ROLE usertest LOGIN PASSWORD 'pwtest';
# CREATE DATABASE dbtest WITH OWNER = usertest;
# SHOW port;
# \q

$ psql -h localhost -d dbtest -U usertest -p 5432

GL

Source

Font is not available to the JVM with Jasper Reports

Actually I fixed this issue in a very simple way

  1. go to your home path, like /root
  2. create a folder named .fonts
  3. copy your all your font files to .fonts, you can copy the font from C:\windows\fonts if you use windows.
  4. sudo apt-get install fontconfig
  5. fc-cache –fv to rebuid fonts caches.

How to convert a DataTable to a string in C#?

using(var writer = new StringWriter()) {
    results.WriteXml(writer);
    Console.WriteLine(writer.ToString());
}

Of course the usefulness of this depends on how important the formatting is. If it's just a debug dump, I find XML outputs like this very readable. However, if the formatting is important to you, then you have no choice but to write your own method to do it.

TypeError: unsupported operand type(s) for -: 'list' and 'list'

You can't subtract a list from a list.

>>> [3, 7] - [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'

Simple way to do it is using numpy:

>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])

You can also use list comprehension, but it will require changing code in the function:

>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]

>>> import numpy as np
>>>
>>> def Naive_Gauss(Array,b):
...     n = len(Array)
...     for column in xrange(n-1):
...         for row in xrange(column+1, n):
...             xmult = Array[row][column] / Array[column][column]
...             Array[row][column] = xmult
...             #print Array[row][col]
...             for col in xrange(0, n):
...                 Array[row][col] = Array[row][col] - xmult*Array[column][col]
...             b[row] = b[row]-xmult*b[column]
...     print Array
...     print b
...     return Array, b  # <--- Without this, the function will return `None`.
...
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
...                   np.array([[6],[7]]))
[[ 2  3]
 [-2 -1]]
[[ 6]
 [-5]]
(array([[ 2,  3],
       [-2, -1]]), array([[ 6],
       [-5]]))

Angular 2 Unit Tests: Cannot find name 'describe'

I hope you've installed -

npm install --save-dev @types/jasmine

Then put following import at the top of the hero.spec.ts file -

import 'jasmine';

It should solve the problem.

Jersey client: How to add a list as query parameter

i agree with you about alternative solutions which you mentioned above

1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.

and its true that you can't add List to MultiValuedMap because of its impl class MultivaluedMapImpl have capability to accept String Key and String Value. which is shown in following figure

enter image description here

still you want to do that things than try following code.

Controller Class

package net.yogesh.test;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.google.gson.Gson;

@Path("test")
public class TestController {
       @Path("testMethod")
       @GET
       @Produces("application/text")
       public String save(
               @QueryParam("list") List<String> list) {

           return  new Gson().toJson(list) ;
       }
}

Client Class

package net.yogesh.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class Client {
    public static void main(String[] args) {
        String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
        System.out.println(op);
    }

    private static String doGet(String url){
        List<String> list = new ArrayList<String>();
        list = Arrays.asList(new String[]{"string1,string2,string3"});

        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
        String lst = (list.toString()).substring(1, list.toString().length()-1);
        params.add("list", lst);

        ClientConfig config = new DefaultClientConfig();
        com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
        WebResource resource = client.resource(url);

        ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
        String en = response.getEntity(String.class);
        return en;
    }
}

hope this'll help you.

How to get height of Keyboard?

Swift 4 .

Simplest Method

override func viewDidLoad() {
      super.viewDidLoad()
      NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}

func keyboardWillShow(notification: NSNotification) {  

      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
             let keyboardHeight : Int = Int(keyboardSize.height)
             print("keyboardHeight",keyboardHeight) 
      }

}

Rollback a Git merge

If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.

The easiest way I felt was to:

  1. Take out a new branch from develop/master (where you merged)
  2. Revert the "revert" using git revert -m 1 xxxxxx (if the revert was merged using a branch) or using git revert xxxxxx if it was a simple revert
  3. The new branch should now have the changes you want to merge again.
  4. Make changes or merge this branch to develop/master

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

try this:

public class SomAsyncTask extends AsyncTask<String, Integer, JSONObject> {

    private CallBack callBack;

    public interface CallBack {
        void async( JSONObject jsonResult );
        void sync( JSONObject jsonResult );
        void progress( Integer... status );
        void cancel();
    }

    public SomAsyncTask(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected JSONObject doInBackground(String... strings) {

        JSONObject dataJson = null;

        //TODO query, get some dataJson

        if(this.callBack != null)
            this.callBack.async( dataJson );// asynchronize with MAIN LOOP THREAD

        return dataJson;

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        if(this.callBack != null)
            this.callBack.progress(values);// synchronize with MAIN LOOP THREAD

    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);

        if(this.callBack != null)
            this.callBack.sync(jsonObject);// synchronize with MAIN LOOP THREAD
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();

        if(this.callBack != null)
            this.callBack.cancel();

    }
}

And usage example:

public void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         final Context _localContext = getContext();
         SomeAsyncTask.CallBack someCallBack = new SomeAsyncTask.CallBack() {

                @Override
                public void async(JSONObject jsonResult) {//async thread
                    //some async process, e.g. send data to server...
                }

                @Override
                public void sync(JSONObject jsonResult) {//sync thread
                    //get result...

                    //get some resource of Activity variable...
                    Resources resources = _localContext.getResources();
                }

                @Override
                public void progress(Integer... status) {//sync thread
                    //e.g. change status progress bar...
                }

                @Override
                public void cancel() {

                }

            };

            new SomeAsyncTask( someCallBack )
                                .execute("someParams0", "someParams1", "someParams2");

    }

How to replace four spaces with a tab in Sublime Text 2?

Bottom right hand corner on the status bar, click Spaces: N (or Tab Width: N, where N is an integer), ensure it says Tab Width: 4 for converting from four spaces, and then select Convert Indentation to Tabs from the contextual menu that will appear from the initial click.

Similarly, if you want to do the opposite, click the Spaces or Tab Width text on the status bar and select from the same menu.

enter image description hereenter image description here

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

pip install --user package-name

Seems to work, but the package is install the the path of user. such as :

"c:\users\***\appdata\local\temp\pip-req-tracker-_akmzo\42a6c7d627641b148564ff35597ec30fd5543aa1cf6e41118b98d7a3"

I want to install the package in python folder such c:\Python27. I install the module into the expected folder by:

pip install package-name --no-cache-dir

select from one table, insert into another table oracle sql query

You can use

insert into <table_name> select <fieldlist> from <tables>

Build project into a JAR automatically in Eclipse

Using Thomas Bratt's answer above, just make sure your build.xml is configured properly :

<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file --> 
<project name="TestMain" default="CreateJar">
  <target name="CreateJar" description="Create Jar file">
        <jar jarfile="Test.jar" basedir="bin/" includes="**/*.class" />
  </target>
</project>

(Notice the double asterisk - it will tell build to look for .class files in all sub-directories.)

Is it possible to break a long line to multiple lines in Python?

If you want to assign a long str to variable, you can do it as below:

net_weights_pathname = (
    '/home/acgtyrant/BigDatas/'
    'model_configs/lenet_iter_10000.caffemodel')

Do not add any comma, or you will get a tuple which contains many strs!

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

A little late to the party, but if you are looking for a solution like Yury's the following code will help you identify if the issue is related to a self-sign certificate and, if so ignore the self-sign error. You could obviously check for other SSL errors if you so desired.

The code we use (courtesy of Microsoft - http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx) is as follows:

  private static bool CertificateValidationCallBack(
         object sender,
         System.Security.Cryptography.X509Certificates.X509Certificate certificate,
         System.Security.Cryptography.X509Certificates.X509Chain chain,
         System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
  // If the certificate is a valid, signed certificate, return true.
  if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
  {
    return true;
  }

  // If there are errors in the certificate chain, look at each error to determine the cause.
  if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
  {
    if (chain != null && chain.ChainStatus != null)
    {
      foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
      {
        if ((certificate.Subject == certificate.Issuer) &&
           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
        {
          // Self-signed certificates with an untrusted root are valid. 
          continue;
        }
        else
        {
          if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
          {
            // If there are any other errors in the certificate chain, the certificate is invalid,
         // so the method returns false.
            return false;
          }
        }
      }
    }

    // When processing reaches this line, the only errors in the certificate chain are 
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
    return true;
  }
  else
  {
 // In all other cases, return false.
    return false;
  }
}

Format Instant to String

Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString() it:

Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z


Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):

instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763


Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):

instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664

etc.

How to extract IP Address in Spring MVC Controller get call?

Put this method in your BaseController:

@SuppressWarnings("ConstantConditions")
protected String fetchClientIpAddr() {
    HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
    String ip = Optional.ofNullable(request.getHeader("X-FORWARDED-FOR")).orElse(request.getRemoteAddr());
    if (ip.equals("0:0:0:0:0:0:0:1")) ip = "127.0.0.1";
    Assert.isTrue(ip.chars().filter($ -> $ == '.').count() == 3, "Illegal IP: " + ip);
    return ip;
}

C fopen vs open

open() is a low-level os call. fdopen() converts an os-level file descriptor to the higher-level FILE-abstraction of the C language. fopen() calls open() in the background and gives you a FILE-pointer directly.

There are several advantages to using FILE-objects rather raw file descriptors, which includes greater ease of usage but also other technical advantages such as built-in buffering. Especially the buffering generally results in a sizeable performance advantage.

Android ListView headers

As an alternative, there's a nice 3rd party library designed just for this use case. Whereby you need to generate headers based on the data being stored in the adapter. They are called Rolodex adapters and are used with ExpandableListViews. They can easily be customized to behave like a normal list with headers.

Using the OP's Event objects and knowing the headers are based on the Date associated with it...the code would look something like this:

The Activity

    //There's no need to pre-compute what the headers are. Just pass in your List of objects. 
    EventDateAdapter adapter = new EventDateAdapter(this, mEvents);
    mExpandableListView.setAdapter(adapter);

The Adapter

private class EventDateAdapter extends NFRolodexArrayAdapter<Date, Event> {

    public EventDateAdapter(Context activity, Collection<Event> items) {
        super(activity, items);
    }

    @Override
    public Date createGroupFor(Event childItem) {
        //This is how the adapter determines what the headers are and what child items belong to it
        return (Date) childItem.getDate().clone();
    }

    @Override
    public View getChildView(LayoutInflater inflater, int groupPosition, int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
        //Inflate your view

        //Gets the Event data for this view
        Event event = getChild(groupPosition, childPosition);

        //Fill view with event data
    }

    @Override
    public View getGroupView(LayoutInflater inflater, int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        //Inflate your header view

        //Gets the Date for this view
        Date date = getGroup(groupPosition);

        //Fill view with date data
    }

    @Override
    public boolean hasAutoExpandingGroups() {
        //This forces our group views (headers) to always render expanded.
        //Even attempting to programmatically collapse a group will not work.
        return true;
    }

    @Override
    public boolean isGroupSelectable(int groupPosition) {
        //This prevents a user from seeing any touch feedback when a group (header) is clicked.
        return false;
    }
}

Character Limit in HTML

use the "maxlength" attribute as others have said.

if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript

Using context in a fragment

To do as the answer above, you can override the onAttach method of fragment:

public static class DummySectionFragment extends Fragment{
...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        DBHelper = new DatabaseHelper(activity);
    }
}

What does ||= (or-equals) mean in Ruby?

Suppose a = 2 and b = 3

THEN, a ||= b will be resulted to a's value i.e. 2.

As when a evaluates to some value not resulted to false or nil.. That's why it ll not evaluate b's value.

Now Suppose a = nil and b = 3.

Then a ||= b will be resulted to 3 i.e. b's value.

As it first try to evaluates a's value which resulted to nil.. so it evaluated b's value.

The best example used in ror app is :

#To get currently logged in iser
def current_user
  @current_user ||= User.find_by_id(session[:user_id])
end

# Make current_user available in templates as a helper
helper_method :current_user

Where, User.find_by_id(session[:user_id]) is fired if and only if @current_user is not initialized before.

HTTP requests and JSON parsing in Python

just import requests and use from json() method :

source = requests.get("url").json()
print(source)

OR you can use this :

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)

What is deserialize and serialize in JSON?

In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia

In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict) into its valid JSON pendant (object).

  • Python's True will be converted to JSONs true and the dictionary itself will then be encapsulated in quotes.
  • You can easily spot the difference between a Python dictionary and JSON by their Boolean values:
    • Python: True / False,
    • JSON: true / false
  • Python builtin module json is the standard way to do serialization:

Code example:

data = {
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian",
        "male": True,
    }
}

import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize

# serialized json_data now looks like:
# {
#   "president": {
#     "name": "Zaphod Beeblebrox",
#     "species": "Betelgeusian",
#     "male": true
#   }
# }

Source: realpython.com

Running .sh scripts in Git Bash

I had a similar problem, but I was getting an error message

cannot execute binary file

I discovered that the filename contained non-ASCII characters. When those were fixed, the script ran fine with ./script.sh.

linux find regex

You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex 
          tests which occur later on the command line.  Currently-implemented  
          types  are  emacs (this is the default), posix-awk, posix-basic, 
          posix-egrep and posix-extended. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

Is jQuery $.browser Deprecated?

"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."

From http://api.jquery.com/jQuery.browser/

Regex empty string or email

I prefer /^\s+$|^$/gi to match empty and empty spaces.

_x000D_
_x000D_
console.log("  ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
_x000D_
_x000D_

Constants in Kotlin -- what's a recommended way to create them?

In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below

val MY_CONSTANT = "Constants"

And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.

companion object{

     const val MY_CONSTANT = "Constants"

}

Simulate string split function in Excel formula

A formula to return either the first word or all the other words.

=IF(ISERROR(FIND(" ",TRIM(A2),1)),TRIM(A2),MID(TRIM(A2),FIND(" ",TRIM(A2),1),LEN(A2)))

Examples and results

Text                  Description                      Results

                      Blank 
                      Space 
some                  Text no space                some
some text             Text with space                  text
 some                 Text with leading space          some
some                  Text with trailing space         some
some text some text   Text with multiple spaces        text some text

Comments on Formula:

  • The TRIM function is used to remove all leading and trailing spaces. Duplicate spacing within the text is also removed.
  • The FIND function then finds the first space
  • If there is no space then the trimmed text is returned
  • Otherwise the MID function is used to return any text after the first space

How to run or debug php on Visual Studio Code (VSCode)

If you don't want to install xDebug or other extensions and just want to run a PHP file without debugging, you can accomplish this using build tasks.

Using Build Tasks

First open the command palette (Ctrl+Shift+P in Windows, ?+Shift+P in Mac), and select "Tasks:Open User Tasks". Now copy my configuration below into your tasks.json file. This creates user-level tasks which can be used any time and in any workspace.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Start Server",
            "type": "shell",
            "command": "php -S localhost:8080 -t ${fileDirname}",
            "isBackground": true,
            "group": "build",
            "problemMatcher": []
        },
        {
            "label": "Run In Browser",
            "type": "shell",
            "command": "open http://localhost:8080/${fileBasename}",
            "windows": {
                "command": "explorer 'http://localhost:8080/${fileBasename}'"
            },
            "group": "build",
            "problemMatcher": []
        }
        {
            "label": "Run In Terminal",
            "type": "shell",
            "command": "php ${file}",
            "group": "none",
            "problemMatcher": []
        }
    ]
}

If you want to run your php file in the terminal, open the command palette and select "Tasks: Run Task" followed by "Run In Terminal".

If you want to run your code on a webserver which serves a response to a web browser, open the command palette and select "Tasks: Run Task" followed by "Start Server" to run PHP's built-in server, then "Run In Browser" to run the currently open file from your browser.

Note that if you already have a webserver running, you can remove the Start Server task and update the localhost:8080 part to point to whatever URL you are using.

Using PHP Debug

Note: This section was in my original answer. I originally thought that it works without PHP Debug but it looks like PHP Debug actually exposes the php type in the launch configuration. There is no reason to use it over the build task method described above. I'm keeping it here in case it is useful.

Copy the following configuration into your user settings:

{
    "launch": {
        "version": "0.2.0",
        "configurations": [
            {
            "type": "php",
            "request": "launch",
            "name": "Run using PHP executable",
            "program": "${file}",
            "runtimeExecutable": "/usr/bin/php"
            },
        ]
    },
    // all your other user settings...
}

This creates a global launch configuration that you can use on any PHP file. Note the runtimeExecutable option. You will need to update this with the path to the PHP executable on your machine. After you copy the configuration above, whenever you have a PHP file open, you can press the F5 key to run the PHP code and have the output displayed in the vscode terminal.

How do I set Tomcat Manager Application User Name and Password for NetBeans?

You will find the tomcat-users.xml in \Users\<Name>\AppData\Roaming\Netbeans\. It exists at least twice on your machine, depending on the number of Tomcat installations you have.

JavaScript, Node.js: is Array.forEach asynchronous?

Edit 2018-10-11: It looks like there is a good chance the standard described below may not go through, consider pipelineing as an alternative (does not behave exactly the same but methods could be implemented in a similar manor).

This is exactly why I am excited about es7, in future you will be able to do something like the code below (some of the specs are not complete so use with caution, I will try to keep this up to date). But basically using the new :: bind operator, you will be able to run a method on an object as if the object's prototype contains the method. eg [Object]::[Method] where normally you would call [Object].[ObjectsMethod]

Note to do this today (24-July-16) and have it work in all browsers you will need to transpile your code for the following functionality:Import / Export, Arrow functions, Promises, Async / Await and most importantly function bind. The code below could be modfied to use only function bind if nessesary, all this functionality is neatly available today by using babel.

YourCode.js (where 'lots of work to do' must simply return a promise, resolving it when the asynchronous work is done.)

import { asyncForEach } from './ArrayExtensions.js';

await [many many elements]::asyncForEach(() => lots of work to do);

ArrayExtensions.js

export function asyncForEach(callback)
{
    return Promise.resolve(this).then(async (ar) =>
    {
        for(let i=0;i<ar.length;i++)
        {
            await callback.call(ar, ar[i], i, ar);
        }
    });
};

export function asyncMap(callback)
{
    return Promise.resolve(this).then(async (ar) =>
    {
        const out = [];
        for(let i=0;i<ar.length;i++)
        {
            out[i] = await callback.call(ar, ar[i], i, ar);
        }
        return out;
    });
};

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How do I format a date in Jinja2?

Made it.

from datetime import datetime
dateNow = datetime.now().strftime('%Y%m%d')

How to recover a dropped stash in Git?

The accepted answer by Aristotle will show all reachable commits, including non-stash-like commits. To filter out the noise:

git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
  --grep="WIP on" --min-parents=3 --max-parents=3

This will only include commits which have exactly 3 parent commits (which a stash will have), and whose message includes "WIP on".

Keep in mind, that if you saved your stash with a message (e.g. git stash save "My newly created stash"), this will override the default "WIP on..." message.

You can display more information about each commit, e.g. display the commit message, or pass it to git stash show:

git fsck --no-reflog | \
awk '/dangling commit/ {print $3}' | \
xargs git log --no-walk --format="%H" \
  --grep="WIP on" --min-parents=3 --max-parents=3 | \
xargs -n1 -I '{}' bash -c "\
  git log -1 --format=medium --color=always '{}'; echo; \
  git stash show --color=always '{}'; echo; echo" | \
less -R

JavaScript/jQuery - "$ is not defined- $function()" error

if you are trying to use jquery in your electron app before adding jquery you should add it to your modules:

<script>
    if (typeof module === 'object') {
        window.module = module;
        module = undefined;
    }
</script>
<script src="js/jquery-3.5.1.min.js"></script>

How do I change the UUID of a virtual disk?

The command fails because it has space in one of the folder name, i.e. 'VirtualBox VMs.

VBoxManage internalcommands sethduuid /home/user/VirtualBox VMs/drupal/drupal.vhd

If there is no space at folder name or file name, then the command will work even without quoting it, e.g. after changing 'VirtualBox VMs' into 'VBoxVMs'

VBoxManage internalcommands sethduuid /home/user/VBoxVMs/drupal/drupal.vhd

Random number generator only generating one random number

My answer from here:

Just reiterating the right solution:

namespace mySpace
{
    public static class Util
    {
        private static rnd = new Random();
        public static int GetRandom()
        {
            return rnd.Next();
        }
    }
}

So you can call:

var i = Util.GetRandom();

all throughout.

If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.

public static class Util
{
    public static int GetRandom()
    {
        return Guid.NewGuid().GetHashCode();
    }
}

It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.

But not:

new Random(Guid.NewGuid().GetHashCode()).Next();

The unnecessary object creation is going to make it slower especially under a loop.

And never:

new Random().Next();

Not only it's slower (inside a loop), its randomness is... well not really good according to me..

Can you animate a height change on a UITableViewCell when selected?

Yes It's Possible.

UITableView has a delegate method didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [UIView animateWithDuration:.6
                          delay:0
         usingSpringWithDamping:UIViewAnimationOptionBeginFromCurrentState
          initialSpringVelocity:0
                        options:UIViewAnimationOptionBeginFromCurrentState animations:^{

                            cellindex = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
                            NSArray* indexArray = [NSArray arrayWithObjects:indexPath, nil];
                            [violatedTableView beginUpdates];
                            [violatedTableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
                            [violatedTableView endUpdates];
                        }
                     completion:^(BOOL finished) {
    }];
}

But in your case if the user scrolls and selects a different cell then u need to have the last selected cell to shrink and expand the currently selected cell reloadRowsAtIndexPaths: calls heightForRowAtIndexPath: so handle accordingly.

How do I change the color of radio buttons?

Only if you are targeting webkit-based browsers (Chrome and Safari, maybe you are developing a Chrome WebApp, who knows...), you can use the following:

input[type='radio'] {
   -webkit-appearance: none;
}

And then style it as if it were a simple HTML element, for example applying a background image.

Use input[type='radio']:active for when the input is selected, to provide the alternate graphics

Update: As of 2018 you can add the following to support multiple browser vendors:

input[type="radio"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

Posting another script solution DateX (author) for anyone interested

DateX does NOT wrap the original Date object, but instead offers an identical interface with additional methods to format, localise, parse, diff and validate dates easily. So one can just do new DateX(..) instead of new Date(..) or use the lib as date utilities or even as wrapper or replacement around Date class.

The date format used is identical to php date format.

c-like format is also supported (although not fully)

for the example posted (YYYY/mm/dd hh:m:sec) the format to use would be Y/m/d H:i:s eg

var formatted_date = new DateX().format('Y/m/d H:i:s');

or

var formatted_now_date_gmt = new DateX(DateX.UTC()).format('Y/m/d H:i:s');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

Set color of TextView span in Android

Here's a Kotlin Extension Function I have for this

    fun TextView.setColouredSpan(word: String, color: Int) {
        val spannableString = SpannableString(text)
        val start = text.indexOf(word)
        val end = text.indexOf(word) + word.length
        try {
            spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text = spannableString
        } catch (e: IndexOutOfBoundsException) {
         println("'$word' was not not found in TextView text")
    }
}

Use it after you have set your text to the TextView like so

private val blueberry by lazy { getColor(R.color.blueberry) }

textViewTip.setColouredSpan("Warning", blueberry)

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

Can you do a For Each Row loop using MySQL?

In the link you provided, thats not a loop in sql...

thats a loop in programming language

they are first getting list of all distinct districts, and then for each district executing query again.

How to get all count of mongoose model?

The code below works. Note the use of countDocuments.

 var mongoose = require('mongoose');
 var db = mongoose.connect('mongodb://localhost/myApp');
 var userSchema = new mongoose.Schema({name:String,password:String});
 var userModel =db.model('userlists',userSchema);
 var anand = new userModel({ name: 'anand', password: 'abcd'});
 anand.save(function (err, docs) {
   if (err) {
       console.log('Error');
   } else {
       userModel.countDocuments({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
      });
   }
 }); 

CSS transition fade in

OK, first of all I'm not sure how it works when you create a div using (document.createElement('div')), so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?

If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?

Here's the code for my example:

HTML

<a href="#new">Click</a> 
<div id="new">
    Fade in ... 
</div>

CSS

#new {
    width: 100px;
    height: 100px;
    border: 1px solid #000000;
    opacity: 0;    
}


#new:target {
    -webkit-transition: opacity 2.0s ease-in;
       -moz-transition: opacity 2.0s ease-in;
         -o-transition: opacity 2.0s ease-in;
                                  opacity: 1;
}

... and here's a jsFiddle

How can I build for release/distribution on the Xcode 4?

The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.

That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).

Cross-Domain Cookies

Cross-site cookies are allowed if:

  1. the Set-Cookie response header includes SameSite=None; Secure as seen here and here
  2. and your browser hasn't disabled 3rd-party cookies.*

Let's clarify a "domain" vs a "site"; I always find a quick reminder of "anatomy of a URL" helps me. In this URL https://example.com:8888/examples/index.html, remember these main parts (got from this paper):

  • the "protocol": https://
  • the "hostname/host": example.com
  • the "port": 8888
  • the "path":/examples/index.html.

Notice the difference between "path" and "site" for Cookie purposes. "path" is not security-related; "site" is security-related:

path

Servers can set a Path attribute in the Set-Cookie, but it doesn't seem security related:

Note that path was intended for performance, not security. Web pages having the same origin still can access cookie via document.cookie even though the paths are mismatched.

site

The SameSite attribute, according to web.dev article, can restrict or allow cross-site cookies; but what is a "site"?

It's helpful to understand exactly what 'site' means here. The site is the combination of the domain suffix and the part of the domain just before it. For example, the www.web.dev domain is part of the web.dev site.

This means what's to the left of web.dev is a subdomain; yep, www is the subdomain (but the subdomain is a part of the host; see the BONUS reply in this answer)

In this URL https://www.example.com:8888/examples/index.html, remember these parts:

  • the "protocol": https://
  • the "hostname" aka "host": example.com
  • (in cases like "en.wikipedia.org", the entire "en.example.com" is also a hostname)
  • the "port": 8888
  • the "site": www.example.com
  • the "domain": example.com
  • the "subdomain": www
  • the "path": /examples/index.html

Useful links:

(Be careful; I was testing my feature in Chrome Incognito tab; according to my chrome://settings/cookies; my settings were "Block third party cookies in Incognito", so I can't test Cross-site cookies in Incognito.)

a browser is open to the URL chrome://settings/cookies, which shows that "Block third-party cookies in Incognito" setting is set, choose a setting in your browser that will allow third-party cookies

Checking if a folder exists using a .bat file

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Haversine Formula in Python (Bearing and Distance between two GPS points)

You can try the following:

from haversine import haversine
haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
243.71209416020253

Random shuffling of an array

Using Guava's Ints.asList() it is as simple as:

Collections.shuffle(Ints.asList(array));

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

just add

 <dependency>
      <groupId>com.microsoft.sqlserver</groupId>
      <artifactId>sqljdbc4</artifactId>
      <version>4.0</version>
      <scope>runtime</scope>
 </dependency>

How can I declare and use Boolean variables in a shell script?

Instead of faking a Boolean and leaving a trap for future readers, why not just use a better value than true and false?

For example:

build_state=success
if something-horrible; then
  build_state=failed
fi

if [[ "$build_state" == success ]]; then
  echo go home; you are done
else
  echo your head is on fire; run around in circles
fi

Convert iterator to pointer?

For example, my vector<int> foo contains (5,2,6,87,251). A function takes vector<int>* and I want to pass it a pointer to (2,6,87,251).

A pointer to a vector<int> is not at all the same thing as a pointer to the elements of the vector.

In order to do this you will need to create a new vector<int> with just the elements you want in it to pass a pointer to. Something like:

 vector<int> tempVector( foo.begin()+1, foo.end());

 // now you can pass &tempVector to your function

However, if your function takes a pointer to an array of int, then you can pass &foo[1].

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

Difference between readFile() and readFileSync()

'use strict'
var fs = require("fs");

/***
 * implementation of readFileSync
 */
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");

/***
 * implementation of readFile 
 */
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

For better understanding run the above code and compare the results..

How to convert timestamp to datetime in MySQL?

SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me

How to redirect back to form with input - Laravel 5

write old function on your fields value for example

<input type="text" name="username" value="{{ old('username') }}">

How do I get into a non-password protected Java keystore or change the password?

which means that cacerts keystore isn't password protected

That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:

In order to verify its integrity, you must provide your keystore password.

Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

How to pass a type as a method parameter in Java

Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.

How many types do you plan to deal with?

UPDATE:

If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):

package generics;

public interface XmlGenerator<T>
{
   String getXml(T value);
}

And the concrete implementation XmlGeneratorImpl:

    package generics;

public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
    private Class<T> valueType;
    private static final int DEFAULT_CAPACITY = 1024;

    public static void main(String [] args)
    {
        Integer x = 42;
        String y = "foobar";

        XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
        XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);

        System.out.println("integer: " + intXmlGenerator.getXml(x));
        System.out.println("string : " + stringXmlGenerator.getXml(y));
    }

    public XmlGeneratorImpl(Class<T> clazz)
    {
        this.valueType = clazz;
    }

    public String getXml(T value)
    {
        StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);

        appendTag(builder);
        builder.append(value);
        appendTag(builder, false);

        return builder.toString();
    }

    private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }

    private void appendTag(StringBuilder builder, boolean isClosing)
    {
        String valueTypeName = valueType.getName();
        builder.append("<").append(valueTypeName);
        if (isClosing)
        {
            builder.append("/");
        }
        builder.append(">");
    }
}

If I run this, I get the following result:

integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>

I don't know if this is what you had in mind.

Save and load MemoryStream to/from a file

For loading a file, I like this a lot better

MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(file))
{
    fs.CopyTo(ms);
}

How to import a JSON file in ECMAScript 6?

importing JSON files are still experimental. It can be supported via the below flag.

--experimental-json-modules

otherwise you can load your JSON file relative to import.meta.url with fs directly:-

import { readFile } from 'fs/promises';
const config = JSON.parse(await readFile(new URL('../config.json', import.meta.url)));

you can also use module.createRequire()

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const config = require('../config.json');

Edit seaborn legend

If you just want to change the legend title, you can do the following:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=True
)

g._legend.set_title("New Title")

Post an object as data using Jquery Ajax

You may pass an object to the data option in $.ajax. jQuery will send this as regular post data, just like a normal HTML form.

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: dataO, // same as using {numberId: 1, companyId: 531}
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert('In Ajax');
    }
});

Reflection generic get field value

You are calling get with the wrong argument.

It should be:

Object value = field.get(object);

Java - checking if parseInt throws exception

You could try

NumberUtils.isParsable(yourInput)

It is part of org/apache/commons/lang3/math/NumberUtils and it checks whether the string can be parsed by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String).

See below:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

Got stuck as I was trying to a go get ... I think it was related to git. Here is how was able to fix it ...

  1. I entered the following in terminal:

    sudo xcodebuild -license
    
  2. This will open the agreement. Go all the way to end and type "agree".

That takes care of go get issues.

It was quite interesting how unrelated things were.

How do I install the yaml package for Python?

"There should be one -- and preferably only one -- obvious way to do it." So let me add another one. This one is more like "install from sources" for Debian/Ubuntu, from https://github.com/yaml/pyyaml

Install the libYAML and it's headers:

sudo apt-get install libyaml-dev

Download the pyyaml sources:

wget http://pyyaml.org/download/pyyaml/PyYAML-3.13.tar.gz

Install from sources, (don't forget to activate your venv):

. your/env/bin/activate
tar xzf PyYAML-3.13.tar.gz
cd PyYAML-3.13.tar.gz
(env)$ python setup.py install
(env)$ python setup.py test 

How can I backup a Docker-container with its data-volumes?

UPDATE 2

Raw single volume backup bash script:

#!/bin/bash
# This script allows you to backup a single volume from a container
# Data in given volume is saved in the current directory in a tar archive.
CONTAINER_NAME=$1
VOLUME_NAME=$2

usage() {
  echo "Usage: $0 [container name] [volume name]"
  exit 1
}

if [ -z $CONTAINER_NAME ]
then
  echo "Error: missing container name parameter."
  usage
fi

if [ -z $VOLUME_NAME ]
then
  echo "Error: missing volume name parameter."
  usage
fi

sudo docker run --rm --volumes-from $CONTAINER_NAME -v $(pwd):/backup busybox tar cvf /backup/backup.tar $VOLUME_NAME

Raw single volume restore bash script:

#!/bin/bash
# This script allows you to restore a single volume from a container
# Data in restored in volume with same backupped path
NEW_CONTAINER_NAME=$1

usage() {
  echo "Usage: $0 [container name]"
  exit 1
}

if [ -z $NEW_CONTAINER_NAME ]
then
  echo "Error: missing container name parameter."
  usage
fi

sudo docker run --rm --volumes-from $NEW_CONTAINER_NAME -v $(pwd):/backup busybox tar xvf /backup/backup.tar

Usage can be like this:

$ volume_backup.sh old_container /srv/www
$ sudo docker stop old_container && sudo docker rm old_container
$ sudo docker run -d --name new_container myrepo/new_container
$ volume_restore.sh new_container

Assumptions are: backup file is named backup.tar, it resides in the same directory as backup and restore script, volume name is the same between containers.

UPDATE

It seems to me that backupping volumes from containers is not different from backupping volumes from data containers.

Volumes are nothing else than paths linked to a container so the process is the same.

I don't know if docker-backup works also for same container volumes but you can use:

sudo docker run --rm --volumes-from yourcontainer -v $(pwd):/backup busybox tar cvf /backup/backup.tar /data

and:

sudo docker run --rm --volumes-from yournewcontainer -v $(pwd):/backup busybox tar xvf /backup/backup.tar

END UPDATE

There is this nice tool available which lets you backup and restore docker volumes containers:

https://github.com/discordianfish/docker-backup

if you have a container linked to some container volumes like this:

$ docker run --volumes-from=my-data-container --name my-server ...

you can backup all the volumes like this:

$ docker-backup store my-server-backup.tar my-server

and restore like this:

$ docker-backup restore my-server-backup.tar

Or you can follow the official way:

How to port data-only volumes from one host to another?

sed whole word search and replace

\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):

$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment

How do I create a circle or square with just CSS - with a hollow center?

Try This

_x000D_
_x000D_
div.circle {_x000D_
  -moz-border-radius: 50px/50px;_x000D_
  -webkit-border-radius: 50px 50px;_x000D_
  border-radius: 50px/50px;_x000D_
  border: solid 21px #f00;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
div.square {_x000D_
  border: solid 21px #f0f;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}
_x000D_
<div class="circle">_x000D_
  <img/>_x000D_
</div>_x000D_
 <hr/>_x000D_
<div class="square">_x000D_
  <img/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

More here

Why am I getting string does not name a type Error?

Try a using namespace std; at the top of game.h or use the fully-qualified std::string instead of string.

The namespace in game.cpp is after the header is included.

What is the difference between window, screen, and document in Javascript?

Well, the window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

What about the document object then? The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

dom

That seems simple enough. But what happens once an IFRAME is introduced?

iframe

How to use private Github repo as npm dependency

It can be done via https and oauth or ssh.

https and oauth: create an access token that has "repo" scope and then use this syntax:

"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"

or

ssh: setup ssh and then use this syntax:

"package-name": "git+ssh://[email protected]:<user>/<repo>.git"

(note the use of colon instead of slash before user)

Ruby, Difference between exec, system and %x() or Backticks

They do different things. exec replaces the current process with the new process and never returns. system invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.

How to run a program without an operating system?

I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive

This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.

Handling JSON Post Request in Go

type test struct {
    Test string `json:"test"`
}

func test(w http.ResponseWriter, req *http.Request) {
    var t test_struct

    body, _ := ioutil.ReadAll(req.Body)
    json.Unmarshal(body, &t)

    fmt.Println(t)
}

Does Python have a string 'contains' substring method?

Does Python have a string contains substring method?

99% of use cases will be covered using the keyword, in, which returns True or False:

'substring' in any_string

For the use case of getting the index, use str.find (which returns -1 on failure, and has optional positional arguments):

start = 0
stop = len(any_string)
any_string.find('substring', start, stop)

or str.index (like find but raises ValueError on failure):

start = 100 
end = 1000
any_string.index('substring', start, end)

Explanation

Use the in comparison operator because

  1. the language intends its usage, and
  2. other Python programmers will expect you to use it.
>>> 'foo' in '**foo**'
True

The opposite (complement), which the original question asked for, is not in:

>>> 'foo' not in '**foo**' # returns False
False

This is semantically the same as not 'foo' in '**foo**' but it's much more readable and explicitly provided for in the language as a readability improvement.

Avoid using __contains__

The "contains" method implements the behavior for in. This example,

str.__contains__('**foo**', 'foo')

returns True. You could also call this function from the instance of the superstring:

'**foo**'.__contains__('foo')

But don't. Methods that start with underscores are considered semantically non-public. The only reason to use this is when implementing or extending the in and not in functionality (e.g. if subclassing str):

class NoisyString(str):
    def __contains__(self, other):
        print(f'testing if "{other}" in "{self}"')
        return super(NoisyString, self).__contains__(other)

ns = NoisyString('a string with a substring inside')

and now:

>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True

Don't use find and index to test for "contains"

Don't use the following string methods to test for "contains":

>>> '**foo**'.index('foo')
2
>>> '**foo**'.find('foo')
2

>>> '**oo**'.find('foo')
-1
>>> '**oo**'.index('foo')

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    '**oo**'.index('foo')
ValueError: substring not found

Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is much more efficient to use the in comparison operator.

Also, these are not drop-in replacements for in. You may have to handle the exception or -1 cases, and if they return 0 (because they found the substring at the beginning) the boolean interpretation is False instead of True.

If you really mean not any_string.startswith(substring) then say it.

Performance comparisons

We can compare various ways of accomplishing the same goal.

import timeit

def in_(s, other):
    return other in s

def contains(s, other):
    return s.__contains__(other)

def find(s, other):
    return s.find(other) != -1

def index(s, other):
    try:
        s.index(other)
    except ValueError:
        return False
    else:
        return True



perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}

And now we see that using in is much faster than the others. Less time to do an equivalent operation is better:

>>> perf_dict
{'in:True': 0.16450627865128808,
 'in:False': 0.1609668098178645,
 '__contains__:True': 0.24355481654697542,
 '__contains__:False': 0.24382793854783813,
 'find:True': 0.3067379407923454,
 'find:False': 0.29860888058124146,
 'index:True': 0.29647137792585454,
 'index:False': 0.5502287584545229}

Struct like objects in Java

Here I create a program to input Name and Age of 5 different persons and perform a selection sort (age wise). I used an class which act as a structure (like C programming language) and a main class to perform the complete operation. Hereunder I'm furnishing the code...

import java.io.*;

class NameList {
    String name;
    int age;
}

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

        NameList nl[]=new NameList[5]; // Create new radix of the structure NameList into 'nl' object
        NameList temp=new NameList(); // Create a temporary object of the structure

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        /* Enter data into each radix of 'nl' object */

        for(int i=0; i<5; i++) {
            nl[i]=new NameList(); // Assign the structure into each radix

            System.out.print("Name: ");
            nl[i].name=br.readLine();

            System.out.print("Age: ");
            nl[i].age=Integer.parseInt(br.readLine());

            System.out.println();
        }

        /* Perform the sort (Selection Sort Method) */

        for(int i=0; i<4; i++) {
            for(int j=i+1; j<5; j++) {
                if(nl[i].age>nl[j].age) {
                    temp=nl[i];
                    nl[i]=nl[j];
                    nl[j]=temp;
                }
            }
        }

        /* Print each radix stored in 'nl' object */

        for(int i=0; i<5; i++)
            System.out.println(nl[i].name+" ("+nl[i].age+")");
    }
}

The above code is Error Free and Tested... Just copy and paste it into your IDE and ... You know and what??? :)

Get names of all files from a folder with Ruby

To get all files (strictly files only) recursively:

Dir.glob('path/**/*').select { |e| File.file? e }

Or anything that's not a directory (File.file? would reject non-regular files):

Dir.glob('path/**/*').reject { |e| File.directory? e }

Alternative Solution

Using Find#find over a pattern-based lookup method like Dir.glob is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".

How to export table data in MySql Workbench to csv?

U can use mysql dump or query to export data to csv file

SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products

How do I get the localhost name in PowerShell?

An analogue of the bat file code in Powershell

Cmd

wmic path Win32_ComputerSystem get Name

Powershell

Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name

and ...

hostname.exe

Using DataContractSerializer to serialize, but can't deserialize back

I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html

Using AND/OR in if else PHP statement

"AND" does not work in my PHP code.

Server's version maybe?

"&&" works fine.

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

Removing the remembered login and password list in SQL Server Management Studio

This works for SQL Server Management Studio v18.0

The file "SqlStudio.bin" doesn't seem to exist any longer. Instead my settings are all stored in this file:

C:\Users\*********\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml

  • Open it in any Texteditor like Notepad++
  • ctrl+f for the username to be removed
  • then delete the entire <Element>.......</Element> block that surrounds it.

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Add a shortcut:

$.Shortcuts.add({
    type: 'down',
    mask: 'Ctrl+A',
    handler: function() {
        debug('Ctrl+A');
    }
});

Start reacting to shortcuts:

$.Shortcuts.start();

Add a shortcut to “another” list:

$.Shortcuts.add({
    type: 'hold',
    mask: 'Shift+Up',
    handler: function() {
        debug('Shift+Up');
    },
    list: 'another'
});

Activate “another” list:

$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
    type: 'hold',
    mask: 'Shift+Up',
    list: 'another'
});

Stop (unbind event handlers):

$.Shortcuts.stop();


Tutorial:
http://www.stepanreznikov.com/js-shortcuts/

MYSQL Truncated incorrect DOUBLE value

Try replacing the AND with ,

UPDATE shop_category 
SET name = 'Secolul XVI - XVIII', name_eng = '16th to 18th centuries' 
WHERE category_id = 4768

The UPDATE Syntax shows comma should be used as the separator.

Converting string "true" / "false" to boolean value

If you're using the variable result:

result = result == "true";

How to use foreach with a hash reference?

foreach my $key (keys %$ad_grp_ref) {
    ...
}

Perl::Critic and daxim recommend the style

foreach my $key (keys %{ $ad_grp_ref }) {
    ...
}

out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })

How to get the current logged in user Id in ASP.NET Core

For ASP.NET 5.0, I have an extension method as follow:

using System;
using System.ComponentModel;
using System.Security.Claims;

namespace YOUR_PROJECT.Presentation.WebUI.Extensions
{
    public static class ClaimsPrincipalExtensions
    {
        public static TId GetId<TId>(this ClaimsPrincipal principal)
        {
            if (principal == null || principal.Identity == null || 
                !principal.Identity.IsAuthenticated)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);

            if (typeof(TId) == typeof(string) || 
                typeof(TId) == typeof(int) || 
                typeof(TId) == typeof(long) || 
                typeof(TId) == typeof(Guid))
            {
                var converter = TypeDescriptor.GetConverter(typeof(TId));

                return (TId)converter.ConvertFromInvariantString(loggedInUserId);
            }

            throw new InvalidOperationException("The user id type is invalid.");
        }

        public static Guid GetId(this ClaimsPrincipal principal)
        {
            return principal.GetId<Guid>();
        }
    }
}

So you can use it like:

using Microsoft.AspNetCore.Mvc;
using YOUR_PROJECT.Presentation.WebUI.Extensions;

namespace YOUR_PROJECT.Presentation.WebUI.Controllers
{
    public class YourController :Controller
    {
        public IActionResult YourMethod()
        {
            // If it's Guid
            var userId = User.GetId();

            // Or
            // var userId = User.GetId<int>();

            return View();
        }
    }
}

How to replace case-insensitive literal substrings in Java

If you don't care about case, then you perhaps it doesn't matter if it returns all upcase:

target.toUpperCase().replace("FOO", "");

Execute method on startup in Spring

In Spring 4.2+ you can now simply do:

@Component
class StartupHousekeeper {

    @EventListener(ContextRefreshedEvent.class)
    public void contextRefreshedEvent() {
        //do whatever
    }
}

"Unknown class <MyClass> in Interface Builder file" error at runtime

In my case, the custom UIView class is in an embedded framework. I changed the custom UIView header file to "project" to "public" and include it in the master header file.

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

How can I loop through a C++ map of maps?

As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:

int main() {
    std::map<std::string, std::map<std::string, std::string>> m {
        {"name1", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name2", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name3", {{"value1", "data1"}, {"value2", "data2"}}}
    };

    for (const auto& [k1, v1] : m)
        for (const auto& [k2, v2] : v1)
            std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;

    return 0;
}

Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.

Note 2: If you want to modify the map m within the loops, you have to remove the const keywords.

Code on Coliru

Proxy setting for R

The problem is with your curl options – the RCurl package doesn't seem to use internet2.dll. You need to specify the port separately, and will probably need to give your user login details as network credentials, e.g.,

opts <- list(
  proxy         = "999.999.999.999", 
  proxyusername = "mydomain\\myusername", 
  proxypassword = "mypassword", 
  proxyport     = 8080
)
getURL("http://stackoverflow.com", .opts = opts)

Remember to escape any backslashes in your password. You may also need to wrap the URL in a call to curlEscape.

WPF Image Dynamically changing Image source during runtime

Like for me -> working is:

string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png"; image1.Source = new BitmapImage(new Uri(strUri2));

Check if page gets reloaded or refreshed in JavaScript

Append the below Script in Console:

window.addEventListener("beforeunload", function(event) { 
     console.log("The page is redirecting")           
     debugger; 
});

How to use a WSDL file to create a WCF service (not make a call)

Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.

svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)

This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.

Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.

Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.

wordpress contactform7 textarea cols and rows change in smaller screens

Code will be As below.

[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->

[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->

[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->

[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->

For Details: https://contactform7.com/text-fields/

Append key/value pair to hash with << in Ruby

Similar as they are, merge! and store treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!'s key: "value" syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.

hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash

{:key=>"value"}

hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash

{:key=>"value", "key"=>"value"}

To get the shovel operator << working, I would advise using Mark Thomas's answer.

How do I reload a page without a POSTDATA warning in Javascript?

<html:form name="Form" type="abc" action="abc.do" method="get" onsubmit="return false;">

method="get" - resolves the problem.

if method="post" then only warning comes.

Git: Could not resolve host github.com error while cloning remote repository in git

I got a similar error, and it's caused by incorrect proxy setting. This command saved me:

git config --global --unset http.proxy

https version:

git config --global --unset https.proxy

Is recursion ever faster than looping?

According to theory its the same things. Recursion and loop with the same O() complexity will work with the same theoretical speed, but of course real speed depends on language, compiler and processor. Example with power of number can be coded in iteration way with O(ln(n)):

  int power(int t, int k) {
  int res = 1;
  while (k) {
    if (k & 1) res *= t;
    t *= t;
    k >>= 1;
  }
  return res;
  }

jQuery UI Accordion Expand/Collapse All

I found AlecRust's solution quite helpful, but I add something to resolve one problem: When you click on a single accordion to expand it and then you click on the button to expand, they will all be opened. But, if you click again on the button to collapse, the single accordion expand before won't be collapse.

I've used imageButton, but you can also apply that logic to buttons.

/*** Expand all ***/
$(".expandAll").click(function (event) {
    $('.accordion .ui-accordion-header:not(.ui-state-active)').next().slideDown();

    return false;
});

/*** Collapse all ***/
$(".collapseAll").click(function (event) {
    $('.accordion').accordion({
        collapsible: true,
        active: false
    });

    $('.accordion .ui-accordion-header').next().slideUp();

    return false;
});

Also, if you have accordions inside an accordion and you want to expand all only on that second level, you can add a query:

/*** Expand all Second Level ***/
$(".expandAll").click(function (event) {
    $('.accordion .ui-accordion-header:not(.ui-state-active)').nextAll(':has(.accordion .ui-accordion-header)').slideDown();

    return false;
});

The apk must be signed with the same certificates as the previous version

Here i get the answer for that question . After searching for too long finally i get to crack the key and password for this . I forget my key and alias also the jks file but fortunately i know the bunch of password what i had put in it . but finding correct combinations for that was toughest task for me .

Solution - Download this - Keytool IUI version 2.4.1 plugin enter image description here

the window will pop up now it show the alias name ..if you jks file is correct .. right click on alias and hit "view certificates chain ".. it will show the SHA1 Key .. match this key with tha key you get while you was uploading the apk in google app store ...

if it match then you are with the right jks file and alias ..

now lucky i have bunch of password to match .. enter image description here

now go to this scrren put the same jks path .. and password(among the password you have ) put any path in "Certificate file"

if the screen shows any error then password is not matching .. if it doesn't show any error then it means you are with correct jks file . correct alias and password() now with that you can upload your apk in play store :)

ES6 export default with multiple functions referring to each other

One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.

export function foo() { console.log('foo') }, 
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }

In this case you are export all of the functions with names, so you could do

import * as fns from './foo';

to get an object with properties for each function instead of the import you'd use for your first example:

import fns from './foo';

SQL Server convert select a column and convert it to a string

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon                |
| cat  | Purz                 |
| dog  | Fido                 |
| dog  | Beethoven            |
| dog  | Buddy                |
| bird | Tweety               |
+------+----------------------+

select group_concat(name) from Pets
group by type

Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values

Result:

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon,Purz           |
| dog  | Fido,Beethoven,Buddy |
| bird | Tweety               |
+------+----------------------+

How to enable DataGridView sorting when user clicks on the column header?

As Niraj suggested, use a SortableBindingList. I've used this very successfully with the DataGridView.

Here's a link to the updated code I used - Presenting the SortableBindingList - Take Two - archive

Just add the two source files to your project, and you'll be in business.

Source is in SortableBindingList.zip - 404 dead link

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

Variable number of arguments in C++?

There is no standard C++ way to do this without resorting to C-style varargs (...).

There are of course default arguments that sort of "look" like variable number of arguments depending on the context:

void myfunc( int i = 0, int j = 1, int k = 2 );

// other code...

myfunc();
myfunc( 2 );
myfunc( 2, 1 );
myfunc( 2, 1, 0 );

All four function calls call myfunc with varying number of arguments. If none are given, the default arguments are used. Note however, that you can only omit trailing arguments. There is no way, for example to omit i and give only j.

Java - What does "\n" mean?

\n 

This means insert a newline in the text at this point.

Just example

System.out.println("hello\nworld");

Output:

hello
world

How to pick an image from gallery (SD Card) for my app?

call chooseImage method like-

public void chooseImage(ImageView v)
{
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, SELECT_PHOTO);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    if(imageReturnedIntent != null)
    {
        Uri selectedImage = imageReturnedIntent.getData();
    switch(requestCode) { 
    case SELECT_PHOTO:
        if(resultCode == RESULT_OK)
        {
            Bitmap datifoto = null;
            temp.setImageBitmap(null);
            Uri picUri = null;
            picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
             if(picUri !=null){
               try {
                   datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(),                                 picUri);
                   temp.setImageBitmap(datifoto);
               } catch (FileNotFoundException e) {
                  throw new RuntimeException(e);
               } catch (IOException e) {
                  throw new RuntimeException(e);
               } catch (OutOfMemoryError e) {
                Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
            }

        }
        }
        break;

}
    }
    else
    {
        //Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
    }
}

Javascript to check whether a checkbox is being checked or unchecked

Also make sure you test it both in firefox and IE. There are some nasty bugs with JS manipulated checkboxes.

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

What does Docker add to lxc-tools (the userspace LXC tools)?

Going to keep this pithier, this is already asked and answered above .

I'd step back however and answer it slightly differently, the docker engine itself adds orchestration as one of its extras and this is the disruptive part. Once you start running an app as a combination of containers running 'somewhere' across multiple container engines it gets really exciting. Robustness, Horizontal Scaling, complete abstraction from the underlying hardware, i could go on and on...

Its not just Docker that gives you this, in fact the de facto Container Orchestration standard is Kubernetes which comes in a lot of flavours, a Docker one, but also OpenShift, SuSe, Azure, AWS...

Then beneath K8S there are alternative container engines; the interesting ones are Docker and CRIO - recently built, daemonless, intended as a container engine specifically for Kubernetes but immature. Its the competition between these that I think will be the real long term choice for a container engine.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I wasn't completely happy by the --allow-file-access-from-files solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.

Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !

How to grep (search) committed code in the Git history

So are you trying to grep through older versions of the code looking to see where something last exists?

If I were doing this, I would probably use git bisect. Using bisect, you can specify a known good version, a known bad version, and a simple script that does a check to see if the version is good or bad (in this case a grep to see if the code you are looking for is present). Running this will find when the code was removed.

How can I use custom fonts on a website?

CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf, and upload it to your remote server where your blog or website is hosted.

@font-face {
    font-family: myfont;
    src: url('myfont.ttf');
}

Creating java date object from year,month,day

Make your life easy when working with dates, timestamps and durations. Use HalDateTime from

http://sourceforge.net/projects/haldatetime/?source=directory

For example you can just use it to parse your input like this:

HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate );   // will print in ISO format: 1988-12-25

You can also specify patterns for parsing and printing.

Set ImageView width and height programmatically?

image_view.getLayoutParams().height 

returns height value in pixels. You need to get the screen dimensions first to set the values properly.

 Display display = context.getWindowManager().getDefaultDisplay();
 DisplayMetrics outMetrics = new DisplayMetrics();
 display.getMetrics(outMetrics);
 int screen_height = outMetrics.heightPixels;
 int screen_width = outMetrics.widthPixels;

After you get the screen dimensions, you can set the imageview width&height using proper margins.

 view.getLayoutParams().height = screen_height - 140;
 view.getLayoutParams().width = screen_width - 130 ;

Yarn: How to upgrade yarn version using terminal?

For Windows users

I usually upgrade Yarn with Chocolatey.

choco upgrade yarn

How do I use a third-party DLL file in Visual Studio C++?

I'f you're suppsed to be able to use it, then 3rd-party library should have a *.lib file as well as a *.dll file. You simply need to add the *.lib to the list of input file in your project's 'Linker' options.

This *.lib file isn't necessarily a 'static' library (which contains code): instead a *.lib can be just a file that links your executable to the DLL.

Why Anaconda does not recognize conda command?

If this problem persists, you may want to check all path values in the PATH variable (under Control Panel\System and Security\System\Advanced System Settings). It might be that some other path is invalid or contains an illegal character.

Today, I had the same problem and found a double quote in a different path value in the PATH variable. All paths after that (including a fresly installed conda) were not usable. Removing the double quote solved the problem.