Programs & Examples On #Non static

non-static is a term to define a function or field that is bound to some object instance. Without an instance, non static fields cannot be accessed and non static methods cannot be invoked. Unlike static, non-static methods can be overridden (virtual).

Non-static variable cannot be referenced from a static context

You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.

At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.

So the class says "all cars have a color" and the instance says "this specific car is red".

In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.

Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).

To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).

In your case, try this code as a starting block:

public static void main (String[] args)
{
    try
    {
        MyProgram7 obj = new MyProgram7 ();
        obj.run (args);
    }
    catch (Exception e)
    {
        e.printStackTrace ();
    }
}

// instance variables here

public void run (String[] args) throws Exception
{
    // put your code here
}

The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).

Difference between Static methods and Instance methods

The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

You can do this to execute a static method:

MyClass.staticMethod();  // Simply refers to the class's static code

But to execute a non-static method, you must do this:

MyClass obj = new MyClass();//Create an instance
obj.nonstaticMethod();  // Refer to the instance's class's code

On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.

Calling Non-Static Method In Static Method In Java

You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.

For example, you could just "new up" an instance of your class in the static method, then call the non-static method.

But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.

invalid use of non-static member function

You must make Foo::comparator static or wrap it in a std::mem_fun class object. This is because lower_bounds() expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind too.

Examples:

// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

How to obtain the last path segment of a URI

Get URL from URI and use getFile() if you are not ready to use substring way of extracting file.

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

How to post data in PHP using file_get_contents?

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

How do I rotate a picture in WinForms

Old question but I had to address MrFox's comment in the accepted answer. Rotating an image when the size changes cuts off the edges of the image. One solution is to redraw the original on a larger image, centered, where the larger image's dimensions compensate for the need of not clipping the edges. For example, I wanted to be able to design a game's tiles at a normal angle but re-draw them at a 45-degree angle for an isometric view.

Here are example images (yellow borders are to make it easier to see here).

The original image: water tile

The centered tile in a larger image: enter image description here

The rotated image (where you rotate the larger image, not the original): enter image description here

The code (based in part on this answer in another question):

private Bitmap RotateImage(Bitmap rotateMe, float angle)
{
    //First, re-center the image in a larger image that has a margin/frame
    //to compensate for the rotated image's increased size

    var bmp = new Bitmap(rotateMe.Width + (rotateMe.Width / 2), rotateMe.Height + (rotateMe.Height / 2));

    using (Graphics g = Graphics.FromImage(bmp))
        g.DrawImageUnscaled(rotateMe, (rotateMe.Width / 4), (rotateMe.Height / 4), bmp.Width, bmp.Height);

    bmp.Save("moved.png");
    rotateMe = bmp;

    //Now, actually rotate the image
    Bitmap rotatedImage = new Bitmap(rotateMe.Width, rotateMe.Height);

    using (Graphics g = Graphics.FromImage(rotatedImage))
    {
        g.TranslateTransform(rotateMe.Width / 2, rotateMe.Height / 2);   //set the rotation point as the center into the matrix
        g.RotateTransform(angle);                                        //rotate
        g.TranslateTransform(-rotateMe.Width / 2, -rotateMe.Height / 2); //restore rotation point into the matrix
        g.DrawImage(rotateMe, new Point(0, 0));                          //draw the image on the new bitmap
    }

    rotatedImage.Save("rotated.png");
    return rotatedImage;
}

Garbage collector in Android

My app manage a lot of images and it died with a OutOfMemoryError. This helped me. In the Manifest.xml Add

<application
....
   android:largeHeap="true"> 

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. then sudo nano idlemain.py, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

I just had this problem. Turns out the XML file (not the contents) was not encoded in utf-8, but in ISO-8859-1. You can check this on a Mac with file -I xml_filename.

I used Sublime to change the file encoding to utf-8, and lxml imported it no issues.

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

How to move certain commits to be based on another branch in git?

The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto but is easier for the eyes :)

git cherry-pick quickfix1..quickfix2

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Sometimes the files are actually located at ~/. These are the steps I took to starting Zsh as the default terminal on Visual Studio Code/Windows 10.

  • cd ~/

  • vim .bashrc

  • Paste the following...

if test -t 1; then exec zsh fi

  • Save/close Vim.

  • Restart the terminal

Most efficient way to see if an ArrayList contains an object in Java

Building a HashMap of these objects based on the field value as a key could be worthwhile from the performance perspective, e.g. populate Maps once and find objects very efficiently

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

Select distinct using linq

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<> into a List<> seems to be a mystery to many people, you can simply write:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

The flipside to this advice is that each time you enumerate such an IEnumerable the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

How to extract a floating number from a string

You can use the following regex to get integer and floating values from a string:

re.findall(r'[\d\.\d]+', 'hello -34 42 +34.478m 88 cricket -44.3')

['34', '42', '34.478', '88', '44.3']

Thanks Rex

initialize a numpy array

For your first array example use,

a = numpy.arange(5)

To initialize big_array, use

big_array = numpy.zeros((10,4))

This assumes you want to initialize with zeros, which is pretty typical, but there are many other ways to initialize an array in numpy.

Edit: If you don't know the size of big_array in advance, it's generally best to first build a Python list using append, and when you have everything collected in the list, convert this list to a numpy array using numpy.array(mylist). The reason for this is that lists are meant to grow very efficiently and quickly, whereas numpy.concatenate would be very inefficient since numpy arrays don't change size easily. But once everything is collected in a list, and you know the final array size, a numpy array can be efficiently constructed.

How do you handle a form change in jQuery?

First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:

    $("form")
    .find("input")
    .change(function(){
        if ($("#hdnFormChanged").val() == "no")
        {
            $("#hdnFormChanged").val("yes");
        }
    });

When your button is clicked, you can check the state of your hidden input:

$("#Button").click(function(){
    if($("#hdnFormChanged").val() == "yes")
    {
        // handler code here...
    }
});

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

Storing and Retrieving ArrayList values from hashmap

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry)it.next();

     if(pairs.getKey().equals("mango"))
     {
        map.put(pairs.getKey(), pairs.getValue().add(18));
     }

     else if(!map.containsKey("mango"))
     {
        List<Integer> ints = new ArrayList<Integer>();
        ints.add(18);
        map.put("mango",ints);
     }

     it.remove(); // avoids a ConcurrentModificationException
}

EDIT: So inside the while try this:

map.put(pairs.getKey(), pairs.getValue().add(number))

You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList.

EDIT 2: Then put the following inside your while loop:

if(pairs.getKey().equals("mango"))
{
    map.put(pairs.getKey(), pairs.getValue().add(18));
}

else if(!map.containsKey("mango"))
{
     List<Integer> ints = new ArrayList<Integer>();
     ints.add(18);
     map.put("mango",ints);
 }

EDIT 3: By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango, and if it does add 18, else create a new entry in the map with key mango and value 18.

So all you may need is the following, without the loop:

if(map.containsKey("mango"))
{
    map.put("mango", map.get("mango).add(18));
}

else
{
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(18);
    map.put("mango", ints);
}

Determine what attributes were changed in Rails after_save callback?

The "selected" answer didn't work for me. I'm using rails 3.1 with CouchRest::Model (based on Active Model). The _changed? methods don't return true for changed attributes in the after_update hook, only in the before_update hook. I was able to get it to work using the (new?) around_update hook:

class SomeModel < ActiveRecord::Base
  around_update :send_notification_after_change

  def send_notification_after_change
    should_send_it = self.published_changed? && self.published == true

    yield

    Notification.send(...) if should_send_it
  end

end

Getting multiple keys of specified value of a generic Dictionary?

As everyone else has said, there's no mapping within a dictionary from value to key.

I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.

The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:

using System;
using System.Collections.Generic;

class BiDictionary<TFirst, TSecond>
{
    IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
    IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();

    public void Add(TFirst first, TSecond second)
    {
        if (firstToSecond.ContainsKey(first) ||
            secondToFirst.ContainsKey(second))
        {
            throw new ArgumentException("Duplicate first or second");
        }
        firstToSecond.Add(first, second);
        secondToFirst.Add(second, first);
    }

    public bool TryGetByFirst(TFirst first, out TSecond second)
    {
        return firstToSecond.TryGetValue(first, out second);
    }

    public bool TryGetBySecond(TSecond second, out TFirst first)
    {
        return secondToFirst.TryGetValue(second, out first);
    }
}

class Test
{
    static void Main()
    {
        BiDictionary<int, string> greek = new BiDictionary<int, string>();
        greek.Add(1, "Alpha");
        greek.Add(2, "Beta");
        int x;
        greek.TryGetBySecond("Beta", out x);
        Console.WriteLine(x);
    }
}

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

Rising to @Ankan-Zerob's challenge, this is my estimate of the maximum length which can be stored in each text type measured in words:

      Type |         Bytes | English words | Multi-byte words
-----------+---------------+---------------+-----------------
  TINYTEXT |           255 |           ±44 |              ±23
      TEXT |        65,535 |       ±11,000 |           ±5,900
MEDIUMTEXT |    16,777,215 |    ±2,800,000 |       ±1,500,000
  LONGTEXT | 4,294,967,295 |  ±740,000,000 |     ±380,000,000

In English, 4.8 letters per word is probably a good average (eg norvig.com/mayzner.html), though word lengths will vary according to domain (e.g. spoken language vs. academic papers), so there's no point being too precise. English is mostly single-byte ASCII characters, with very occasional multi-byte characters, so close to one-byte-per-letter. An extra character has to be allowed for inter-word spaces, so I've rounded down from 5.8 bytes per word. Languages with lots of accents such as say Polish would store slightly fewer words, as would e.g. German with longer words.

Languages requiring multi-byte characters such as Greek, Arabic, Hebrew, Hindi, Thai, etc, etc typically require two bytes per character in UTF-8. Guessing wildly at 5 letters per word, I've rounded down from 11 bytes per word.

CJK scripts (Hanzi, Kanji, Hiragana, Katakana, etc) I know nothing of; I believe characters mostly require 3 bytes in UTF-8, and (with massive simplification) they might be considered to use around 2 characters per word, so they would be somewhere between the other two. (CJK scripts are likely to require less storage using UTF-16, depending).

This is of course ignoring storage overheads etc.

TypeError: ObjectId('') is not JSON serializable

SOLUTION for: mongoengine + marshmallow

If you use mongoengine and marshamallow then this solution might be applicable for you.

Basically, I imported String field from marshmallow, and I overwritten default Schema id to be String encoded.

from marshmallow import Schema
from marshmallow.fields import String

class FrontendUserSchema(Schema):

    id = String()

    class Meta:
        fields = ("id", "email")

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Stop all active ajax requests in jQuery

Using ajaxSetup is not correct, as is noted on its doc page. It only sets up defaults, and if some requests override them there will be a mess.

I am way late to the party, but just for future reference if someone is looking for a solution to the same problem, here is my go at it, inspired by and largely identical to the previous answers, but more complete

// Automatically cancel unfinished ajax requests 
// when the user navigates elsewhere.
(function($) {
  var xhrPool = [];
  $(document).ajaxSend(function(e, jqXHR, options){
    xhrPool.push(jqXHR);
  });
  $(document).ajaxComplete(function(e, jqXHR, options) {
    xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
  });
  var abort = function() {
    $.each(xhrPool, function(idx, jqXHR) {
      jqXHR.abort();
    });
  };

  var oldbeforeunload = window.onbeforeunload;
  window.onbeforeunload = function() {
    var r = oldbeforeunload ? oldbeforeunload() : undefined;
    if (r == undefined) {
      // only cancel requests if there is no prompt to stay on the page
      // if there is a prompt, it will likely give the requests enough time to finish
      abort();
    }
    return r;
  }
})(jQuery);

Rounding to 2 decimal places in SQL

Try to avoid formatting in your query. You should return your data in a raw format and let the receiving application (e.g. a reporting service or end user app) do the formatting, i.e. rounding and so on.

Formatting the data in the server makes it harder (or even impossible) for you to further process your data. You usually want export the table or do some aggregation as well, like sum, average etc. As the numbers arrive as strings (varchar), there is usually no easy way to further process them. Some report designers will even refuse to offer the option to aggregate these 'numbers'.

Also, the end user will see the country specific formatting of the server instead of his own PC.

Also, consider rounding problems. If you round the values in the server and then still do some calculations (supposing the client is able to revert the number-strings back to a number), you will end up getting wrong results.

Padding In bootstrap

I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.

<div id="main" class="container" role="main">
    <div class="row">

        <div class="span5 offset1">
            <h2>Welcome</h2>
            <p>Hello and welcome to my website.</p>
        </div>
        <div class="span6">
            Image Here (TODO)
        </div>
    </div>

Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.

I think I know what you are doing wrong. If you are applying padding to the span6 like this:

<div class="span6" style="padding-left:5px;">
    <h2>Welcome</h2>
    <p>Hello and welcome to my website.</p>
</div>

It is wrong. What you have to do is add padding to the elements inside:

<div class="span6">
    <h2 style="padding-left:5px;">Welcome</h2>
    <p  style="padding-left:5px;">Hello and welcome to my website.</p>
</div>

How to use `replace` of directive definition?

Also i got this error if i had the comment in tn top level of template among with the actual root element.

<!-- Just a commented out stuff -->
<div>test of {{value}}</div>

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

Change Spinner dropdown icon

dummy.xml(remember image size should be less)

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <layer-list android:opacity="transparent">
                <item android:width="60dp" android:gravity="left" android:start="20dp">
                    <bitmap  android:src="@drawable/down_button_dummy_dummy" android:gravity="left"/>
                </item>
            </layer-list>
        </item>
    </selector>

layout file snippet be like

<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardUseCompatPadding="true"
        app:cardElevation="5dp"
        >
     <Spinner
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/dummy">

     </Spinner>
    </android.support.v7.widget.CardView>

click to see result layout image

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

If you are using Python 2, the following will be the solution:

import io
for line in io.open("u.item", encoding="ISO-8859-1"):
    # Do something

Because the encoding parameter doesn't work with open(), you will be getting the following error:

TypeError: 'encoding' is an invalid keyword argument for this function

Get the distance between two geo points

you can get distance and time using google Map API Google Map API

just pass downloaded JSON to this method you will get real time Distance and Time between two latlong's

void parseJSONForDurationAndKMS(String json) throws JSONException {

    Log.d(TAG, "called parseJSONForDurationAndKMS");
    JSONObject jsonObject = new JSONObject(json);
    String distance;
    String duration;
    distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
    duration = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text");

    Log.d(TAG, "distance : " + distance);
    Log.d(TAG, "duration : " + duration);

    distanceBWLats.setText("Distance : " + distance + "\n" + "Duration : " + duration);


}

what exactly is device pixel ratio?

Short answer

The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.

  • Physical resolution: 960 x 640
  • Logical resolution: 480 x 320

The formula is:

linres_p/linres_l

Where:

linres_p is the physical linear resolution

and:

linres_l is the logical linear resolution

Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.

Discussion

The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of 0.0213° viewing angle, which is approximately 1/96 of an inch at arm's length. Source: CSS Absolute Lengths

This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.

If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover or explicitly set the background-size to percentage values.

Example

#element { background-image: url('lores.png'); }

@media only screen and (min-device-pixel-ratio: 2) {
    #element { background-image: url('hires.png'); }
}

@media only screen and (min-device-pixel-ratio: 3) {
    #element { background-image: url('superhires.png'); }
}

This way, each device type only loads the correct image resource. Also keep in mind that the px unit in CSS always operates on logical pixels.

A case for vector graphics

As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).

If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.

Count indexes using "for" in Python

use enumerate:

>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
...    print "%d: %s" % (index, val)
... 
0: a
1: b
2: c
3: d

Facebook Post Link Image

Try using something like this:

<link rel="image_src" href="http://yoursite.com/graphics/yourimage.jpg" /link>`

Seems to work just fine on Firefox as long as you use a full path to your image.

Trouble is it get vertically offset downward for some reason. Image is 200 x 200 as recommended somewhere I read.

Why is "using namespace std;" considered bad practice?

With unqualified imported identifiers you need external search tools like grep to find out where identifiers are declared. This makes reasoning about program correctness harder.

How to commit and rollback transaction in sql server?

Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ...... 

Could not find default endpoint element

Several responses here hit upon the correct solution when you're facing the mind-numbingly obscure error of referencing the service from a class file: copy service config info into your app.config web.config of your console or windows app. None of those answers seem to show you what to copy though. Let's try and correct that.

Here's what I copied out of my class library's config file, into my console app's config file, in order to get around this crazy error for a service I write called "TranslationServiceOutbound".

You basically want everything inside the system.serviceModel section:

  <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_ITranslationServiceOutbound" />
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://MyHostName/TranslationServiceOutbound/TranslationServiceOutbound.svc"
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITranslationServiceOutbound"
    contract="TranslationService.ITranslationServiceOutbound" name="BasicHttpBinding_ITranslationServiceOutbound" />
</client>

How to downgrade or install an older version of Cocoapods

Several notes:

Make sure you first get a list of all installed versions. I actually had the version I wanted to downgrade to already installed, but ended up uninstalling that as well. To see the list of all your versions do:

sudo gem list cocoapods

Then when you want to delete a version, specify that version.

sudo gem uninstall cocoapods -v 1.6.2

You could remove the version specifier -v 1.6.2 and that would delete all versions:

You may try all this and still see that the Cocoapods you expected is still installed. If that's the case then it might be because Cocoaposa is stored in a different directory.

sudo gem uninstall -n /usr/local/bin cocoapods -v 1.6.2

Then you will have to also install it in a different directory, otherwise you may get an error saying You don't have write permissions for the /usr/bin directory

sudo gem install -n /usr/local/bin cocoapods -v 1.6.1

To check which version is your default do:

pod --version

For more on the directory problem see here

Basic Ajax send/receive with node.js

  1. Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true); Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.

  2. You are correctly calling listen() but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write() or response.end(). First, you need to include fs=require('fs') to get access to the filesystem. Then, you need to actually serve the file.

  3. XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string will be undefined (or perhaps null), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.

Here is a simple implementation that incorporates all of the above:

server.js:

var http = require('http'),
      fs = require('fs'),
     url = require('url'),
 choices = ["hello world", "goodbye world"];

http.createServer(function(request, response){
    var path = url.parse(request.url).pathname;
    if(path=="/getstring"){
        console.log("request recieved");
        var string = choices[Math.floor(Math.random()*choices.length)];
        console.log("string '" + string + "' chosen");
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.end(string);
        console.log("string sent");
    }else{
        fs.readFile('./index.html', function(err, file) {  
            if(err) {  
                // write an error response or nothing here  
                return;  
            }  
            response.writeHead(200, { 'Content-Type': 'text/html' });  
            response.end(file, "utf-8");  
        });
    }
}).listen(8001);
console.log("server initialized");

frontend (part of index.html):

function newGame()
{
   guessCnt=0;
   guess="";
   server();
   displayHash();
   displayGuessStr();
   displayGuessCnt();
}

function server()
{
   xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET","http://localhost:8001/getstring", true);
   xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
           string=xmlhttp.responseText;
         }
   }
   xmlhttp.send();
}

You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.

UPDATE: I have changed response.sendHeader() to the new response.writeHead() in the code above !!!

How do function pointers in C work?

A function pointer is a variable that contains the address of a function. Since it is a pointer variable though with some restricted properties, you can use it pretty much like you would any other pointer variable in data structures.

The only exception I can think of is treating the function pointer as pointing to something other than a single value. Doing pointer arithmetic by incrementing or decrementing a function pointer or adding/subtracting an offset to a function pointer isn't really of any utility as a function pointer only points to a single thing, the entry point of a function.

The size of a function pointer variable, the number of bytes occupied by the variable, may vary depending on the underlying architecture, e.g. x32 or x64 or whatever.

The declaration for a function pointer variable needs to specify the same kind of information as a function declaration in order for the C compiler to do the kinds of checks that it normally does. If you don't specify a parameter list in the declaration/definition of the function pointer, the C compiler will not be able to check the use of parameters. There are cases when this lack of checking can be useful however just remember that a safety net has been removed.

Some examples:

int func (int a, char *pStr);    // declares a function

int (*pFunc)(int a, char *pStr);  // declares or defines a function pointer

int (*pFunc2) ();                 // declares or defines a function pointer, no parameter list specified.

int (*pFunc3) (void);             // declares or defines a function pointer, no arguments.

The first two declararations are somewhat similar in that:

  • func is a function that takes an int and a char * and returns an int
  • pFunc is a function pointer to which is assigned the address of a function that takes an int and a char * and returns an int

So from the above we could have a source line in which the address of the function func() is assigned to the function pointer variable pFunc as in pFunc = func;.

Notice the syntax used with a function pointer declaration/definition in which parenthesis are used to overcome the natural operator precedence rules.

int *pfunc(int a, char *pStr);    // declares a function that returns int pointer
int (*pFunc)(int a, char *pStr);  // declares a function pointer that returns an int

Several Different Usage Examples

Some examples of usage of a function pointer:

int (*pFunc) (int a, char *pStr);    // declare a simple function pointer variable
int (*pFunc[55])(int a, char *pStr); // declare an array of 55 function pointers
int (**pFunc)(int a, char *pStr);    // declare a pointer to a function pointer variable
struct {                             // declare a struct that contains a function pointer
    int x22;
    int (*pFunc)(int a, char *pStr);
} thing = {0, func};                 // assign values to the struct variable
char * xF (int x, int (*p)(int a, char *pStr));  // declare a function that has a function pointer as an argument
char * (*pxF) (int x, int (*p)(int a, char *pStr));  // declare a function pointer that points to a function that has a function pointer as an argument

You can use variable length parameter lists in the definition of a function pointer.

int sum (int a, int b, ...);
int (*psum)(int a, int b, ...);

Or you can not specify a parameter list at all. This can be useful but it eliminates the opportunity for the C compiler to perform checks on the argument list provided.

int  sum ();      // nothing specified in the argument list so could be anything or nothing
int (*psum)();
int  sum2(void);  // void specified in the argument list so no parameters when calling this function
int (*psum2)(void);

C style Casts

You can use C style casts with function pointers. However be aware that a C compiler may be lax about checks or provide warnings rather than errors.

int sum (int a, char *b);
int (*psplsum) (int a, int b);
psplsum = sum;               // generates a compiler warning
psplsum = (int (*)(int a, int b)) sum;   // no compiler warning, cast to function pointer
psplsum = (int *(int a, int b)) sum;     // compiler error of bad cast generated, parenthesis are required.

Compare Function Pointer to Equality

You can check that a function pointer is equal to a particular function address using an if statement though I am not sure how useful that would be. Other comparison operators would seem to have even less utility.

static int func1(int a, int b) {
    return a + b;
}

static int func2(int a, int b, char *c) {
    return c[0] + a + b;
}

static int func3(int a, int b, char *x) {
    return a + b;
}

static char *func4(int a, int b, char *c, int (*p)())
{
    if (p == func1) {
        p(a, b);
    }
    else if (p == func2) {
        p(a, b, c);      // warning C4047: '==': 'int (__cdecl *)()' differs in levels of indirection from 'char *(__cdecl *)(int,int,char *)'
    } else if (p == func3) {
        p(a, b, c);
    }
    return c;
}

An Array of Function Pointers

And if you want to have an array of function pointers each of the elements of which the argument list has differences then you can define a function pointer with the argument list unspecified (not void which means no arguments but just unspecified) something like the following though you may see warnings from the C compiler. This also works for a function pointer parameter to a function:

int(*p[])() = {       // an array of function pointers
    func1, func2, func3
};
int(**pp)();          // a pointer to a function pointer


p[0](a, b);
p[1](a, b, 0);
p[2](a, b);      // oops, left off the last argument but it compiles anyway.

func4(a, b, 0, func1);
func4(a, b, 0, func2);  // warning C4047: 'function': 'int (__cdecl *)()' differs in levels of indirection from 'char *(__cdecl *)(int,int,char *)'
func4(a, b, 0, func3);

    // iterate over the array elements using an array index
for (i = 0; i < sizeof(p) / sizeof(p[0]); i++) {
    func4(a, b, 0, p[i]);
}
    // iterate over the array elements using a pointer
for (pp = p; pp < p + sizeof(p)/sizeof(p[0]); pp++) {
    (*pp)(a, b, 0);          // pointer to a function pointer so must dereference it.
    func4(a, b, 0, *pp);     // pointer to a function pointer so must dereference it.
}

C style namespace Using Global struct with Function Pointers

You can use the static keyword to specify a function whose name is file scope and then assign this to a global variable as a way of providing something similar to the namespace functionality of C++.

In a header file define a struct that will be our namespace along with a global variable that uses it.

typedef struct {
   int (*func1) (int a, int b);             // pointer to function that returns an int
   char *(*func2) (int a, int b, char *c);  // pointer to function that returns a pointer
} FuncThings;

extern const FuncThings FuncThingsGlobal;

Then in the C source file:

#include "header.h"

// the function names used with these static functions do not need to be the
// same as the struct member names. It's just helpful if they are when trying
// to search for them.
// the static keyword ensures these names are file scope only and not visible
// outside of the file.
static int func1 (int a, int b)
{
    return a + b;
}

static char *func2 (int a, int b, char *c)
{
    c[0] = a % 100; c[1] = b % 50;
    return c;
}

const FuncThings FuncThingsGlobal = {func1, func2};

This would then be used by specifying the complete name of global struct variable and member name to access the function. The const modifier is used on the global so that it can not be changed by accident.

int abcd = FuncThingsGlobal.func1 (a, b);

Application Areas of Function Pointers

A DLL library component could do something similar to the C style namespace approach in which a particular library interface is requested from a factory method in a library interface which supports the creation of a struct containing function pointers.. This library interface loads the requested DLL version, creates a struct with the necessary function pointers, and then returns the struct to the requesting caller for use.

typedef struct {
    HMODULE  hModule;
    int (*Func1)();
    int (*Func2)();
    int(*Func3)(int a, int b);
} LibraryFuncStruct;

int  LoadLibraryFunc LPCTSTR  dllFileName, LibraryFuncStruct *pStruct)
{
    int  retStatus = 0;   // default is an error detected

    pStruct->hModule = LoadLibrary (dllFileName);
    if (pStruct->hModule) {
        pStruct->Func1 = (int (*)()) GetProcAddress (pStruct->hModule, "Func1");
        pStruct->Func2 = (int (*)()) GetProcAddress (pStruct->hModule, "Func2");
        pStruct->Func3 = (int (*)(int a, int b)) GetProcAddress(pStruct->hModule, "Func3");
        retStatus = 1;
    }

    return retStatus;
}

void FreeLibraryFunc (LibraryFuncStruct *pStruct)
{
    if (pStruct->hModule) FreeLibrary (pStruct->hModule);
    pStruct->hModule = 0;
}

and this could be used as in:

LibraryFuncStruct myLib = {0};
LoadLibraryFunc (L"library.dll", &myLib);
//  ....
myLib.Func1();
//  ....
FreeLibraryFunc (&myLib);

The same approach can be used to define an abstract hardware layer for code that uses a particular model of the underlying hardware. Function pointers are filled in with hardware specific functions by a factory to provide the hardware specific functionality that implements functions specified in the abstract hardware model. This can be used to provide an abstract hardware layer used by software which calls a factory function in order to get the specific hardware function interface then uses the function pointers provided to perform actions for the underlying hardware without needing to know implementation details about the specific target.

Function Pointers to create Delegates, Handlers, and Callbacks

You can use function pointers as a way to delegate some task or functionality. The classic example in C is the comparison delegate function pointer used with the Standard C library functions qsort() and bsearch() to provide the collation order for sorting a list of items or performing a binary search over a sorted list of items. The comparison function delegate specifies the collation algorithm used in the sort or the binary search.

Another use is similar to applying an algorithm to a C++ Standard Template Library container.

void * ApplyAlgorithm (void *pArray, size_t sizeItem, size_t nItems, int (*p)(void *)) {
    unsigned char *pList = pArray;
    unsigned char *pListEnd = pList + nItems * sizeItem;
    for ( ; pList < pListEnd; pList += sizeItem) {
        p (pList);
    }

    return pArray;
}

int pIncrement(int *pI) {
    (*pI)++;

    return 1;
}

void * ApplyFold(void *pArray, size_t sizeItem, size_t nItems, void * pResult, int(*p)(void *, void *)) {
    unsigned char *pList = pArray;
    unsigned char *pListEnd = pList + nItems * sizeItem;
    for (; pList < pListEnd; pList += sizeItem) {
        p(pList, pResult);
    }

    return pArray;
}

int pSummation(int *pI, int *pSum) {
    (*pSum) += *pI;

    return 1;
}

// source code and then lets use our function.
int intList[30] = { 0 }, iSum = 0;

ApplyAlgorithm(intList, sizeof(int), sizeof(intList) / sizeof(intList[0]), pIncrement);
ApplyFold(intList, sizeof(int), sizeof(intList) / sizeof(intList[0]), &iSum, pSummation);

Another example is with GUI source code in which a handler for a particular event is registered by providing a function pointer which is actually called when the event happens. The Microsoft MFC framework with its message maps uses something similar to handle Windows messages that are delivered to a window or thread.

Asynchronous functions that require a callback are similar to an event handler. The user of the asynchronous function calls the asynchronous function to start some action and provides a function pointer which the asynchronous function will call once the action is complete. In this case the event is the asynchronous function completing its task.

Apache won't start in wamp

My solution on Windows 10 was just to stop IIS (Internet Information Services).

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

In your case (creating a list) there is no difference in practice. But generally it is better to use setUp(), because that will help Junit to report Exceptions correctly. If an exception occurs in constructor/initializer of a Test, that is a test failure. However, if an exception occurs during setup, it is natural to think of it as some issue in setting up the test, and junit reports it appropriately.

How to "flatten" a multi-dimensional array to simple one in PHP?

Someone might find this useful, I had a problem flattening array at some dimension, I would call it last dimension so for example, if I have array like:

array (
  'germany' => 
  array (
    'cars' => 
    array (
      'bmw' => 
      array (
        0 => 'm4',
        1 => 'x3',
        2 => 'x8',
      ),
    ),
  ),
  'france' => 
  array (
    'cars' => 
    array (
      'peugeot' => 
      array (
        0 => '206',
        1 => '3008',
        2 => '5008',
      ),
    ),
  ),
)

Or:

array (
  'earth' => 
  array (
    'germany' => 
    array (
      'cars' => 
      array (
        'bmw' => 
        array (
          0 => 'm4',
          1 => 'x3',
          2 => 'x8',
        ),
      ),
    ),
  ),
  'mars' => 
  array (
    'france' => 
    array (
      'cars' => 
      array (
        'peugeot' => 
        array (
          0 => '206',
          1 => '3008',
          2 => '5008',
        ),
      ),
    ),
  ),
)

For both of these arrays when I call method below I get result:

array (
  0 => 
  array (
    0 => 'm4',
    1 => 'x3',
    2 => 'x8',
  ),
  1 => 
  array (
    0 => '206',
    1 => '3008',
    2 => '5008',
  ),
)

So I am flattening to last array dimension which should stay the same, method below could be refactored to actually stop at any kind of level:

function flattenAggregatedArray($aggregatedArray) {
    $final = $lvls = [];
    $counter = 1;
    $lvls[$counter] = $aggregatedArray;


    $elem = current($aggregatedArray);

    while ($elem){
        while(is_array($elem)){
            $counter++;
            $lvls[$counter] = $elem;
            $elem =  current($elem);
        }

        $final[] = $lvls[$counter];
        $elem = next($lvls[--$counter]);
        while ( $elem  == null){
            if (isset($lvls[$counter-1])){
                $elem = next($lvls[--$counter]);
            }
            else{
                return $final;
            }
        }
    }
}

convert htaccess to nginx

You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :

$content = $_POST['content'];

    $lines   = explode(PHP_EOL, $content);
    $results = '';

    foreach($lines as $line)
    {
        $items = explode(' ', $line);

        $q = str_replace("^", "^/", $items[1]);

        if (substr($q, strlen($q) - 1) !== '$') $q .= '$';

        $buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';

        $results .= $buffer.PHP_EOL;
    }

    die($results);

How to compress an image via Javascript in the browser?

In short:

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

Source: code.

How to control size of list-style-type disc in CSS?

You can also use 2D transform. It is illustrated in the snippet below with a list being scaled by 25%.

Nota: Bootstrap is used here for the sole purpose of layouting the demo (before/after effect).


_x000D_
_x000D_
ul#before {_x000D_
}_x000D_
_x000D_
ul#after {_x000D_
  transform: scale(1.25);_x000D_
}_x000D_
_x000D_
div.container, div.row {_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  border: 6px solid #000000;_x000D_
}
_x000D_
<!-- Bootstrap CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<!-- Bootstrap theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">_x000D_
_x000D_
<!-- HTML -->_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-5">_x000D_
      Before_x000D_
    </div>_x000D_
    <div class="col-xs-5 col-xs-offset-1">_x000D_
      After (scale 25%)_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="row">_x000D_
    <div class="col-xs-5">_x000D_
      <ul id="before">_x000D_
        <li>Lorem ipsum dolor sit amet...</li>_x000D_
        <li>In vel ante vel est accumsan...</li>_x000D_
        <li>In elementum libero vel...</li>_x000D_
        <li>Nam ut ante a sem mattis...</li>_x000D_
        <li>Curabitur fermentum nisl...</li>_x000D_
        <li>Praesent vel risus ultrices...</li>_x000D_
      </ul>_x000D_
    </div>_x000D_
    <div class="col-xs-5 col-xs-offset-1">_x000D_
      <ul id="after">_x000D_
        <li>Lorem ipsum dolor sit amet...</li>_x000D_
        <li>In vel ante vel est accumsan...</li>_x000D_
        <li>In elementum libero vel...</li>_x000D_
        <li>Nam ut ante a sem mattis...</li>_x000D_
        <li>Curabitur fermentum nisl...</li>_x000D_
        <li>Praesent vel risus ultrices...</li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<!-- JQuery -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Bootstrap JS -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Reference:

Using sed to split a string with a delimiter

Using simply :

$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

If you really need :

$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

Checking if a variable exists in javascript

If you want to check if a variable (say v) has been defined and is not null:

if (typeof v !== 'undefined' && v !== null) {
    // Do some operation  
}

If you want to check for all falsy values such as: undefined, null, '', 0, false:

if (v) {
   // Do some operation
}

Could not find a version that satisfies the requirement tensorflow

I installed it successfully by pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl

Installing Java 7 on Ubuntu

Download java jdk<version>-linux-x64.tar.gz file from https://www.oracle.com/technetwork/java/javase/downloads/index.html.

Extract this file where you want. like: /home/java(Folder name created by user in home directory).

Now open terminal. Set path JAVA_HOME=path of your jdk folder(open jdk folder then right click on any folder, go to properties then copy the path using select all) and paste here.

Like: JAVA_HOME=/home/xxxx/java/JDK1.8.0_201

Let Ubuntu know where our JDK/JRE is located.

sudo update-alternatives --install /usr/bin/java java /home/xxxx/java/jdk1.8.0_201/bin/java 20000
sudo update-alternatives --install /usr/bin/javac javac /home/xxxx/java/jdk1.8.0_201/bin/javac 20000
sudo update-alternatives --install /usr/bin/javaws javaws /home/xxxx/java/jdk1.8.0_201/bin/javaws 20000

Tell Ubuntu that our installation i.e., jdk1.8.0_05 must be the default Java.

sudo update-alternatives --set java /home/xxxx/sipTest/jdk1.8.0_201/bin/java
sudo update-alternatives --set javac /home/xxxx/java/sipTest/jdk1.8.0_201/bin/javac
sudo update-alternatives --set javaws /home/xxxxx/sipTest/jdk1.8.0_201/bin/javaws

Now try:

$ sudo update-alternatives --config java

There are 3 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                  Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-6-oracle1/bin/java   1047      auto mode
  1            /usr/bin/gij-4.6                       1046      manual mode
  2            /usr/lib/jvm/java-6-oracle1/bin/java   1047      manual mode
  3            /usr/lib/jvm/jdk1.7.0_75/bin/java      1         manual mode

Press enter to keep the current choice [*], or type selection number: 3

update-alternatives: using /usr/lib/jvm/jdk1.7.0_75/bin/java to provide /usr/bin/java (java) in manual mode

Repeat the above for:

sudo update-alternatives --config javac
sudo update-alternatives --config javaws

Change background color for selected ListBox item

<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

and

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

You just override the style of the listboxitem (see the: TargetType is ListBoxItem)

How to sort pandas data frame using values from several columns?

I have found this to be really useful:

df = pd.DataFrame({'A' : range(0,10) * 2, 'B' : np.random.randint(20,30,20)})

# A ascending, B descending
df.sort(**skw(columns=['A','-B']))

# A descending, B ascending
df.sort(**skw(columns=['-A','+B']))

Note that unlike the standard columns=,ascending= arguments, here column names and their sort order are in the same place. As a result your code gets a lot easier to read and maintain.

Note the actual call to .sort is unchanged, skw (sortkwargs) is just a small helper function that parses the columns and returns the usual columns= and ascending= parameters for you. Pass it any other sort kwargs as you usually would. Copy/paste the following code into e.g. your local utils.py then forget about it and just use it as above.

# utils.py (or anywhere else convenient to import)
def skw(columns=None, **kwargs):
    """ get sort kwargs by parsing sort order given in column name """
    # set default order as ascending (+)
    sort_cols = ['+' + col if col[0] != '-' else col for col in columns]
    # get sort kwargs
    columns, ascending = zip(*[(col.replace('+', '').replace('-', ''), 
                                False if col[0] == '-' else True) 
                               for col in sort_cols])
    kwargs.update(dict(columns=list(columns), ascending=ascending))
    return kwargs

Can you get the column names from a SqlDataReader?

If you want the column names only, you can do:

List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
    DataTable dt = reader.GetSchemaTable();
    foreach (DataRow row in dt.Rows)
    {
        columns.Add(row.Field<String>("ColumnName"));
    }
}

But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.

public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
    Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                // Add the parameters for the SelectCommand.
                if (queryParams != null)
                    foreach (var param in queryParams)
                        cmd.Parameters.AddWithValue(param.Key, param.Value);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
                        }
                    }
                }
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return CaseInsensitiveDictionary;
}

What is the order of precedence for CSS?

Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest: CSS styling order

Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.

How to VueJS router-link active style

Let's make things simple, you don't need to read the document about a "custom tag" (as a 16 years web developer, I have enough this kind of tags, such as in struts, webwork, jsp, rails and now it's vuejs)

just press F12, and you will see the source code like:

    <div>
        <a href="#/topologies" class="luelue">page1</a> 
        <a href="#/" aria-current="page" class="router-link-exact-active router-link-active">page2</a> 
        <a href="#/databases" class="">page3</a>
    </div>

so just add styles for the .router-link-active or router-link-exact-active

if you want more details, check the router-link api:

https://router.vuejs.org/en/api/#router-link

SQL Server Express CREATE DATABASE permission denied in database 'master'

For SQL server 2012,

  1. First, log in to the SQL server as an administrator and go to Security tab

  2. Then move into Server Roles and double click on sysadmin role

  3. Now add user which you want to give permission to create Database by clicking Add button

  4. Click OK button and now run the query

Hope this will help for someone

Linux Process States

When a process needs to fetch data from a disk, it effectively stops running on the CPU to let other processes run because the operation might take a long time to complete – at least 5ms seek time for a disk is common, and 5ms is 10 million CPU cycles, an eternity from the point of view of the program!

From the programmer point of view (also said "in userspace"), this is called a blocking system call. If you call write(2) (which is a thin libc wrapper around the system call of the same name), your process does not exactly stop at that boundary; it continues, in the kernel, running the system call code. Most of the time it goes all the way up to a specific disk controller driver (filename ? filesystem/VFS ? block device ? device driver), where a command to fetch a block on disk is submitted to the proper hardware, which is a very fast operation most of the time.

THEN the process is put in sleep state (in kernel space, blocking is called sleeping – nothing is ever 'blocked' from the kernel point of view). It will be awakened once the hardware has finally fetched the proper data, then the process will be marked as runnable and will be scheduled. Eventually, the scheduler will run the process.

Finally, in userspace, the blocking system call returns with proper status and data, and the program flow goes on.

It is possible to invoke most I/O system calls in non-blocking mode (see O_NONBLOCK in open(2) and fcntl(2)). In this case, the system calls return immediately and only report submitting the disk operation. The programmer will have to explicitly check at a later time whether the operation completed, successfully or not, and fetch its result (e.g., with select(2)). This is called asynchronous or event-based programming.

Most answers here mentioning the D state (which is called TASK_UNINTERRUPTIBLE in the Linux state names) are incorrect. The D state is a special sleep mode which is only triggered in a kernel space code path, when that code path can't be interrupted (because it would be too complex to program), with the expectation that it would block only for a very short time. I believe that most "D states" are actually invisible; they are very short lived and can't be observed by sampling tools such as 'top'.

You can encounter unkillable processes in the D state in a few situations. NFS is famous for that, and I've encountered it many times. I think there's a semantic clash between some VFS code paths, which assume to always reach local disks and fast error detection (on SATA, an error timeout would be around a few 100 ms), and NFS, which actually fetches data from the network which is more resilient and has slow recovery (a TCP timeout of 300 seconds is common). Read this article for the cool solution introduced in Linux 2.6.25 with the TASK_KILLABLE state. Before this era there was a hack where you could actually send signals to NFS process clients by sending a SIGKILL to the kernel thread rpciod, but forget about that ugly trick.…

Remove decimal values using SQL query

First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.

Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.

There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":

REPLACE(CAST(height as varchar(31)),'.00','')

EDIT:

This script works:

DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

http://api.jquery.com/jQuery.post/

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload

SSL Connection / Connection Reset with IISExpress

In my case I'd simply forgotten I had a binding set up for (in my case) https://localhost:44300 in full IIS. You can't have both!

CSS Background Opacity

.transbg{/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";}

Resize Cross Domain Iframe Height

There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example

<code>
    <?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
    <?php echo $output; ?>
</div>

<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>

<script>
if(window.attachEvent) {
    window.attachEvent('onload', iframeResizer);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            iframeResizer(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = iframeResizer;
    }
}
   function iframeResizer(){
        var result = document.getElementById("iframediv").offsetHeight;

        document.getElementById("iframe").style.height = result;
        document.getElementById("iframediv").style.display = 'none';
        document.getElementById("iframe").style.display = 'inline';
    }
</script>
</code>

TypeError: can't pickle _thread.lock objects

You need to change from queue import Queue to from multiprocessing import Queue.

The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.

For details, you can read some source code or contact me!

Connect to SQL Server database from Node.js

//start the program
var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'datapullman',
        password: 'system',
        server: 'localhost', 
        database: 'chat6' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records

        request.query("select * From emp", function (err, recordset) {            
            if  (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

//create a table as emp in a database (i have created as chat6)

// programs ends here

//save it as app.js and run as node app.js //open in you browser as localhost:5000

Button Center CSS

The problem is with the following CSS line on .nav_button:

margin: 0 auto;

That would only work if you had one button, that's why they're off-centered when there are more than one nav_button divs.

If you want all your buttons centered nest the nav_buttons in another div:

<div class="nav">
    <div class="centerButtons">
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Home</div>
            <div class="b_right"></div>
        </div>
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Contact Us</div>
            <div class="b_right"></div>
        </div>
    </div>
</div>

And style it this way:

.nav{
    margin-top:167px;
    width:1024px;
    height:34px;
}

/* Centers the div that nests the nav_buttons */
.centerButtons {
    margin: 0 auto;
    float: left;
} 

.nav_button{
    height:34px;
    margin-right:10px;
    float: left;
}

What is the use of the JavaScript 'bind' method?

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

Please refer this link for more information

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

How to create a readonly textbox in ASP.NET MVC3 Razor

With credits to the previous answer by @Bronek and @Shimmy:

This is like I have done the same thing in ASP.NET Core:

<input asp-for="DisabledField" disabled="disabled" />
<input asp-for="DisabledField" class="hidden" />

The first input is readonly and the second one passes the value to the controller and is hidden. I hope it will be useful for someone working with ASP.NET Core.

VarBinary vs Image SQL Server Data Type to Store Binary Data?

varbinary(max) is the way to go (introduced in SQL Server 2005)

In javascript, how do you search an array for a substring match

Just search for the string in plain old indexOf

arr.forEach(function(a){
    if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
            console.log(a);
    }        
});

How to use the addr2line command in Linux?

You need to specify an offset to addr2line, not a virtual address (VA). Presumably if you had address space randomization turned off, you could use a full VA, but in most modern OSes, address spaces are randomized for a new process.

Given the VA 0x4005BDC by valgrind, find the base address of your process or library in memory. Do this by examining the /proc/<PID>/maps file while your program is running. The line of interest is the text segment of your process, which is identifiable by the permissions r-xp and the name of your program or library.

Let's say that the base VA is 0x0x4005000. Then you would find the difference between the valgrind supplied VA and the base VA: 0xbdc. Then, supply that to add2line:

addr2line -e a.out -j .text 0xbdc

And see if that gets you your line number.

Redirect to a page/URL after alert button is pressed

You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location.href = "index.php";';
echo '</script>';

For clarity, try leaving PHP tags for this:

?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php

NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.

JavaScript Regular Expression Email Validation

You can add a function to String Object

//Add this wherever you like in your javascript code
String.prototype.isEmail = function() {
    return !!this.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
}

var user_email = "[email protected]";

if(user_email.isEmail()) {
    //Email is valid !
} else {
    //Email is invalid !
}

How to delete file from public folder in laravel 5.1

Its a very old thread, but I don't see that the solution is here or the this thread is marked as solved. I have also stuck into the same problem I solved it like this

  $path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
  if (!File::exists($path)) 
  {
    File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
  }

The key is that you need to remove '..' from the delete method. Keep in mind that this goes true if you are using Storage as well, whether you are using Storage of File don't for get to use them like

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use File; // For File
use Storage; // For Storage

Hope that it will help someone.

Close Bootstrap Modal

Just add this in modal

div tabindex="-1"

How do I return clean JSON from a WCF Service?

In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare

 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]

    List<personClass> Getperson(string id);

Redis: Show database size/size for keys

MEMORY USAGE key command gives you the number of bytes that a key and its value require to be stored in RAM.

The reported usage is the total of memory allocations for data and administrative overheads that a key its value require (source redis documentation)

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

Floating point exception

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

PHP Warning: Module already loaded in Unknown on line 0

In my case I had uncoment the ;extension=php_curl.so in php.ini, but Ubuntu was already calling this extension somewhere else.

To find this "somewhere else", on php.ini will informe. On my case: /etc/php/7.1/apache2/conf.d/20-curl.ini was the path.

So now we edit this file (terminal):

sudo nano /etc/php/7.1/apache2/conf.d/20-curl.ini

Comment the ;extension=php_curl.so

Save file and restart apache:

sudo systemctl restart apache2

update package.json version automatically

First, you need to understand the rules for upgrading the versioning number. You can read more about the semantic version here.

Each version will have x.y.z version where it defines for different purpose as shown below.

  1. x - major, up this when you have major changes and it is huge discrepancy of changes occurred.
  2. y - minor, up this when you have new functionality or enhancement occurred.
  3. z - patch, up this when you have bugs fixed or revert changes on earlier version.

To run the scripts, you can define it in your package.json.

"script": {
    "buildmajor": "npm version major && ng build --prod",
    "buildminor": "npm version minor && ng build --prod",
    "buildpatch": "npm version patch && ng build --prod"
}

In your terminal, you just need to npm run accordingly to your needs like

npm run buildpatch

If run it in git repo, the default git-tag-version is true and if you do not wish to do so, you can add below command into your scripts:

--no-git-tag-version

for eg: "npm --no-git-tag-version version major && ng build --prod"

Java - Check if JTextField is empty or not

Well, the code that renders the button enabled/disabled:

if(name.getText().equals("")) {
    loginbt.setEnabled(false);
}else {
    loginbt.setEnabled(true);
}

must be written in javax.swing.event.ChangeListener and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?

How to get Rails.logger printing to the console/stdout when running rspec?

Tail the log as a background job (&) and it will interleave with rspec output.

tail -f log/test.log &
bundle exec rspec

how to bind datatable to datagridview in c#

foreach (DictionaryEntry entry in Hashtable)
{
    datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}

Compiling an application for use in highly radioactive environments

NASA has a paper on radiation-hardened software. It describes three main tasks:

  1. Regular monitoring of memory for errors then scrubbing out those errors,
  2. robust error recovery mechanisms, and
  3. the ability to reconfigure if something no longer works.

Note that the memory scan rate should be frequent enough that multi-bit errors rarely occur, as most ECC memory can recover from single-bit errors, not multi-bit errors.

Robust error recovery includes control flow transfer (typically restarting a process at a point before the error), resource release, and data restoration.

Their main recommendation for data restoration is to avoid the need for it, through having intermediate data be treated as temporary, so that restarting before the error also rolls back the data to a reliable state. This sounds similar to the concept of "transactions" in databases.

They discuss techniques particularly suitable for object-oriented languages such as C++. For example

  1. Software-based ECCs for contiguous memory objects
  2. Programming by Contract: verifying preconditions and postconditions, then checking the object to verify it is still in a valid state.

And, it just so happens, NASA has used C++ for major projects such as the Mars Rover.

C++ class abstraction and encapsulation enabled rapid development and testing among multiple projects and developers.

They avoided certain C++ features that could create problems:

  1. Exceptions
  2. Templates
  3. Iostream (no console)
  4. Multiple inheritance
  5. Operator overloading (other than new and delete)
  6. Dynamic allocation (used a dedicated memory pool and placement new to avoid the possibility of system heap corruption).

How can I find matching values in two arrays?

Loop through the second array each time you iterate over an element in the first array, then check for matches.

var array1 = ["cat", "sum", "fun", "run"],
    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];

function getMatch(a, b) {
    var matches = [];

    for ( var i = 0; i < a.length; i++ ) {
        for ( var e = 0; e < b.length; e++ ) {
            if ( a[i] === b[e] ) matches.push( a[i] );
        }
    }
    return matches;
}

getMatch(array1, array2); // ["cat"]

Compare two Lists for differences

This approach from Microsoft works very well and provides the option to compare one list to another and switch them to get the difference in each. If you are comparing classes simply add your objects to two separate lists and then run the comparison.

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

How to replace case-insensitive literal substrings in Java

Regular expressions are quite complex to manage due to the fact that some characters are reserved: for example, "foo.bar".replaceAll(".") produces an empty string, because the dot means "anything" If you want to replace only the point should be indicated as a parameter "\\.".

A simpler solution is to use StringBuilder objects to search and replace text. It takes two: one that contains the text in lowercase version while the second contains the original version. The search is performed on the lowercase contents and the index detected will also replace the original text.

public class LowerCaseReplace 
{
    public static String replace(String source, String target, String replacement)
    {
        StringBuilder sbSource = new StringBuilder(source);
        StringBuilder sbSourceLower = new StringBuilder(source.toLowerCase());
        String searchString = target.toLowerCase();

        int idx = 0;
        while((idx = sbSourceLower.indexOf(searchString, idx)) != -1) {
            sbSource.replace(idx, idx + searchString.length(), replacement);
            sbSourceLower.replace(idx, idx + searchString.length(), replacement);
            idx+= replacement.length();
        }
        sbSourceLower.setLength(0);
        sbSourceLower.trimToSize();
        sbSourceLower = null;

        return sbSource.toString();
    }


    public static void main(String[] args)
    {
        System.out.println(replace("xXXxyyyXxxuuuuoooo", "xx", "**"));
        System.out.println(replace("FOoBaR", "bar", "*"));
    }
}

How to get the new value of an HTML input after a keypress has modified it?

You can try this code (requires jQuery):

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#foo').keyup(function(e) {
                var v = $('#foo').val();
                $('#debug').val(v);
            })
        });
    </script>
</head>
<body>
    <form>
        <input type="text" id="foo" value="bar"><br>
        <textarea id="debug"></textarea>
    </form>
</body>
</html>

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

WARNING: sanitizing unsafe style value url

Check this handy pipe for Angular2: Usage:

  1. in the SafePipe code, substitute DomSanitizationService with DomSanitizer

  2. provide the SafePipe if your NgModule

  3. <div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>

How to make UIButton's text alignment center? Using IB

You can do this from storyboard. Select your button. Set Line Break 'Word Wrap', Set your title 'Plain' to 'Attributed'. Select 'Center alignment'. This part is important => Click ...(More) Button. And select line breaking mode to 'Character Wrap'.

Git diff says subproject is dirty

To ignore all untracked files in any submodule use the following command to ignore those changes.

git config --global diff.ignoreSubmodules dirty

It will add the following configuration option to your local git config:

[diff]
  ignoreSubmodules = dirty

Further information can be found here

How to change Java version used by TOMCAT?

You can change the JDK or JRE location using the following steps:

  1. open the terminal or cmd.
  2. go to the [tomcat-home]\bin directory.
    ex: c:\tomcat8\bin
  3. write the following command: Tomcat8W //ES//Tomcat8
  4. will open dialog, select the java tab(top pane).
  5. change the Java virtual Machine value.
  6. click OK.

note: in Apache TomEE same steps, but step (3) the command must be: TomEE //ES

How do I put text on ProgressBar?

I have used this simple code, and it works!

for (int i = 0; i < N * N; i++)
     {
        Thread.Sleep(50);
        progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
        progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
        (float)10.25, FontStyle.Bold),
        Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
     }

It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#

I used this code, and it does work.

How can I get the day of a specific date with PHP

$date = '2014-02-25';
date('D', strtotime($date));

Load data from txt with pandas

I usually take a look at the data first or just try to import it and do data.head(), if you see that the columns are separated with \t then you should specify sep="\t" otherwise, sep = " ".

import pandas as pd     
data = pd.read_csv('data.txt', sep=" ", header=None)

C++ floating point to integer type conversions

One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.

int someint = (somedouble+epsilon);

This Activity already has an action bar supplied by the window decor

Another easy way is to make your theme a child of Theme.AppCompat.Light.NoActionBar like so:

<style name="NoActionBarTheme" parent="Theme.AppCompat.Light.NoActionBar">
     ...
</style>

An invalid XML character (Unicode: 0xc) was found

Whenever invalid xml character comes xml, it gives such error. When u open it in notepad++ it look like VT, SOH,FF like these are invalid xml chars. I m using xml version 1.0 and i validate text data before entering it in database by pattern

Pattern p = Pattern.compile("[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFF]+"); 
retunContent = p.matcher(retunContent).replaceAll("");

It will ensure that no invalid special char will enter in xml

how to insert date and time in oracle?

create table Customer(
       CustId int primary key,
       CustName varchar(20),
       DOB date);

insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));

How to find if a file contains a given string using Windows command line

From other post:

    find /c "string" file >NUL
    if %errorlevel% equ 1 goto notfound
        echo found
    goto done
    :notfound
        echo notfound
    goto done
    :done

Use the /i switch when you want case insensitive checking:

    find /i /c "string" file >NUL

Or something like: if not found write to file.

    find /c "%%P" file.txt  || ( echo %%P >> newfile.txt )

Or something like: if found write to file.

    find /c "%%P" file.txt  && ( echo %%P >> newfile.txt )

Or something like:

    find /c "%%P" file.txt  && ( echo found ) || ( echo not found )

How to find out mySQL server ip address from phpmyadmin

You can ssh to your server and run this command

 ln -s /usr/share/phpmyadmin /var/www/phpmyadmin

It worked for me..

Scale iFrame css width 100% like an image

@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.

The most reliable, simplest answer is:

_x000D_
_x000D_
body {_x000D_
  /* for demo */_x000D_
  background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
  /* anything or nothing, it doesn't matter */_x000D_
  width: 60%;_x000D_
  /* only need if other rulesets give this padding */_x000D_
  padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
  height: 0;_x000D_
  /* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
  padding: 0 0 56.25%;_x000D_
  position: relative;_x000D_
  /* only need next 2 rules if other rulesets change these */_x000D_
  margin: 0;_x000D_
  width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  /* for demo */_x000D_
  border: 0;_x000D_
  background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
  <div class="fixed-aspect-padder">_x000D_
    <iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AlertDialog.Builder with custom layout and EditText; cannot access view

/**
 * Shows  confirmation dialog about signing in.
 */
private void startAuthDialog() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    alertDialog.getWindow().setLayout(800, 1400);
    LayoutInflater inflater = this.getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.auth_dialog, null);
    alertDialog.getWindow().setContentView(dialogView);
    EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
    editText.setText("test label");
}

How to reverse an animation on mouse out after hover

I don't think this is achievable using only CSS animations. I am assuming that CSS transitions do not fulfil your use case, because (for example) you want to chain two animations together, use multiple stops, iterations, or in some other way exploit the additional power animations grant you.

I've not found any way to trigger a CSS animation specifically on mouse-out without using JavaScript to attach "over" and "out" classes. Although you can use the base CSS declaration trigger an animation when the :hover ends, that same animation will then run on page load. Using "over" and "out" classes you can split the definition into the base (load) declaration and the two animation-trigger declarations.

The CSS for this solution would be:

.class {
    /* base element declaration */
}
.class.out {
   animation-name: out;
   animation-duration:2s;

}
.class.over {
   animation-name: in;
   animation-duration:5s;
   animation-iteration-count:infinite;
}
@keyframes in {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
@keyframes out {
    from {
        transform: rotate(360deg);
    }
    to {
        transform: rotate(0deg);
    }
}

And using JavaScript (jQuery syntax) to bind the classes to the events:

$(".class").hover(
    function () {
        $(this).removeClass('out').addClass('over');
    },
    function () {
        $(this).removeClass('over').addClass('out');
    }
);

private constructor

One common use is for template-typedef workaround classes like following:

template <class TObj>
class MyLibrariesSmartPointer
{
  MyLibrariesSmartPointer();
  public:
    typedef smart_ptr<TObj> type;
};

Obviously a public non-implemented constructor would work aswell, but a private construtor raises a compile time error instead of a link time error, if anyone tries to instatiate MyLibrariesSmartPointer<SomeType> instead of MyLibrariesSmartPointer<SomeType>::type, which is desireable.

pass array to method Java

You got a syntax wrong. Just pass in array's name. BTW - it's good idea to read some common formatting stuff too, for example in Java methods should start with lowercase letter (it's not an error it's convention)

Run javascript script (.js file) in mongodb including another file inside js

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

Unable to copy file - access to the path is denied

You aren't supposed to change the folder attribute to not-readonly. The reason you are seeing this error message is that source control assumes that you only store your miscellaneous files somewhere other than bin folder, for it it reserved for files that are automatically created by .Net and it doesn't want to add them to source control.

I suggest instead of using Environment.CurrectDirectory (which I assume you are using currently), you create a folder named "MyProjectName" in %appdata% address and then use:

System.IO.Path.Combine(Environment.GetEnvironmentVariable("appdata"),"YourProjectName").

How to write multiple conditions of if-statement in Robot Framework

You should use small caps "or" and "and" instead of OR and AND.

And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).

Here is a code sample with your three keywords working fine:

Here is the file ts.txt:

  *** test cases ***
  mytest
    ${color} =  set variable  Red
    Run Keyword If  '${color}' == 'Red'  log to console  \nexecuted with single condition
    Run Keyword If  '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink'  log to console  \nexecuted with multiple or

    ${color} =  set variable  Blue
    ${Size} =  set variable  Small
    ${Simple} =  set variable  Simple
    ${Design} =  set variable  Simple
    Run Keyword If  '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}'  log to console  \nexecuted with multiple and

    ${Size} =  set variable  XL
    ${Design} =  set variable  Complicated
    Run Keyword Unless  '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple'  log to console  \nexecuted with unless and multiple or

and here is what I get when I execute it:

$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest                                                                .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest                                                                | PASS |
------------------------------------------------------------------------------

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

How can I be notified when an element is added to the page?

The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver).

So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)

AngularJS : Factory and Service?

Service vs Factory


enter image description here enter image description here

The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Factory are a great way for communicating between controllers like sharing data.

  • Can use other dependencies

  • Usually used when the service instance requires complex creation logic

  • Cannot be injected in .config() function.

  • Used for non configurable services

  • If you're using an object, you could use the factory provider.

  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Services are used for communication between controllers to share data

  • You can add properties and functions to a service object by using the this keyword

  • Dependencies are injected as constructor arguments

  • Used for simple creation logic

  • Cannot be injected in .config() function.

  • If you're using a class you could use the service provider

  • Syntax: module.service(‘serviceName’, function);

Sample Demo

In below example I have define MyService and MyFactory. Note how in .service I have created the service methods using this.methodname. In .factory I have created a factory object and assigned the methods to it.

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});

Also Take a look at this beautiful stuffs

Confused about service vs factory

AngularJS Factory, Service and Provider

Angular.js: service vs provider vs factory?

Plotting multiple time series on the same plot using ggplot()

I prefer using the ggfortify library. It is a ggplot2 wrapper that recognizes the type of object inside the autoplot function and chooses the best ggplot methods to plot. At least I don't have to remember the syntax of ggplot2.

library(ggfortify)
ts1 <- 1:100
ts2 <- 1:100*0.8
autoplot(ts( cbind(ts1, ts2)  , start = c(2010,5), frequency = 12 ),
         facets = FALSE)

Plot

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

This works for me:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

How to get start and end of previous month in VB

I have similar formula for the First and Last Day

The First Day of the month

FirstDay = DateSerial(Year(Date),Month(Date),1)

The zero Day of the next month is the Last Day of the month

LastDay = DateSerial(Year(Date),Month(Date)+ 1,0) 

How to get the month name in C#?

You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.

I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.

Here is an example of how to do it using extension methods:

using System;
using System.Globalization;

class Program
{
    static void Main()
    {

        Console.WriteLine(DateTime.Now.ToMonthName());
        Console.WriteLine(DateTime.Now.ToShortMonthName());
        Console.Read();
    }
}

static class DateTimeExtensions
{
    public static string ToMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
    }

    public static string ToShortMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
    }
}

Hope this helps!

How to Deep clone in javascript

The below function is most efficient way to deep clone javascript objects.

function deepCopy(obj){
    if (!obj || typeof obj !== "object") return obj;

    var retObj = {};

    for (var attr in obj){
        var type = obj[attr];

        switch(true){
            case (type instanceof Date):
                var _d = new Date();
                _d.setDate(type.getDate())
                retObj[attr]= _d;
                break;

            case (type instanceof Function):
                retObj[attr]= obj[attr];
                break;

            case (type instanceof Array):
                var _a =[];
                for (var e of type){
                    //_a.push(e);
                    _a.push(deepCopy(e));
                }
                retObj[attr]= _a;
                break;

            case (type instanceof Object):
                var _o ={};
                for (var e in type){
                    //_o[e] = type[e];
                    _o[e] = deepCopy(type[e]);
                }
                retObj[attr]= _o;
                break;

            default:
                retObj[attr]= obj[attr];
        }
    }
    return retObj;
}

var obj = {
    string: 'test',
    array: ['1'],
    date: new Date(),
    object:{c: 2, d:{e: 3}},
    function: function(){
        return this.date;
    }
};

var copyObj = deepCopy(obj);

console.log('object comparison', copyObj === obj); //false
console.log('string check', copyObj.string === obj.string); //true
console.log('array check', copyObj.array === obj.array); //false
console.log('date check', copyObj2.date === obj.date); //false
console.log('object check', copyObj.object === obj.object); //false
console.log('function check', copyObj.function() === obj.function()); //true

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

I found that using the following, simple code did the trick (requires custom image in bundle):

// Creates a back button instead of default behaviour (displaying title of previous screen)
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"]
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(backAction)];

    tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;
    [backButton release];

How do you fix the "element not interactable" exception?

For the html code:

test.html

<button class="dismiss"  onclick="alert('hello')">
    <string for="exit">Dismiss</string>
</button>

the below python code worked for me. You can just try it.

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()

How to restore default perspective settings in Eclipse IDE

1 - Go to window . 2 - Go to Perspective and click . 3 - Go to Reset Perspective. 4 - Then you will find Eclipse all reset option.

Best way to handle multiple constructors in Java

A slightly simplified answer:

public class Book
{
    private final String title;

    public Book(String title)
    {
      this.title = title;
    }

    public Book()
    {
      this("Default Title");
    }

    ...
}

Should I use pt or px?

A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.

A px is a pixel, which will map on to a screen pixel in most cases.

CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.

A pixel is great if you need to size something to match an image, or if you want a thin border.

Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.

Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)

… and so on.

jQuery check if Cookie exists, if not create it

 $(document).ready(function() {

     var CookieSet = $.cookie('cookietitle', 'yourvalue');

     if (CookieSet == null) {
          // Do Nothing
     }
     if (jQuery.cookie('cookietitle')) {
          // Reactions
     }
 });

How to get input text value from inside td

I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.

I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:

    $('.start').keyup(function() {
        var otherInputs = $(this).parents('td').siblings().find('input');

        for(var i = 0; i < otherInputs.length; i++) {
            alert($(otherInputs[i]).val());
        }
        return false;
    });

How do I delete an exported environment variable?

this may also work.

export GNUPLOT_DRIVER_DIR=

on change event for file input element

Give unique class and different id for file input

           $("#tab-content").on('change',class,function()
               {
                  var id=$(this).attr('id');
                      $("#"+id).trigger(your function); 
               //for name of file input  $("#"+id).attr("name");
               });

Open another application from your own (intent)

Try this code, Hope this will help you. If this package is available then this will open the app or else open the play store for downloads

    String  packageN = "aman4india.com.pincodedirectory";

            Intent i = getPackageManager().getLaunchIntentForPackage(packageN);
            if (i != null) {
                i.addCategory(Intent.CATEGORY_LAUNCHER);
                startActivity(i);
            } else {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
                }
                catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
                }
            }

Using an HTML button to call a JavaScript function

Your HTML and the way you call the function from the button look correct.

The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.

Edit:

Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value

How to disable copy/paste from/to EditText

You can do this by disabling the long press of the EditText

To implement it, just add the following line in the xml -

android:longClickable="false"

What are the differences between a clustered and a non-clustered index?

A clustered index actually describes the order in which records are physically stored on the disk, hence the reason you can only have one.

A Non-Clustered Index defines a logical order that does not match the physical order on disk.

What is the best way to generate a unique and short file name in Java

Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.

For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt

An implementation of the fast Fourier transform (FFT) in C#

Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products.

How to handle-escape both single and double quotes in an SQL-Update statement

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"

How to play a sound in C#, .NET

You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();.

Configuring ObjectMapper in Spring

I am using Spring 3.2.4 and Jackson FasterXML 2.1.1.

I have created a custom JacksonObjectMapper that works with explicit annotations for each attribute of the Objects mapped:

package com.test;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class MyJaxbJacksonObjectMapper extends ObjectMapper {

public MyJaxbJacksonObjectMapper() {

    this.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
            .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY)
            .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);

    this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
}

Then this is instantiated in the context-configuration (servlet-context.xml):

<mvc:annotation-driven>
    <mvc:message-converters>

        <beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <beans:property name="objectMapper">
                <beans:bean class="com.test.MyJaxbJacksonObjectMapper" />
            </beans:property>
        </beans:bean>

    </mvc:message-converters>
</mvc:annotation-driven>

This works fine!

Mockito: List Matchers with generics

For Java 8 and above, it's easy:

when(mock.process(Matchers.anyList()));

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz):

when(mock.process(Matchers.anyListOf(Bar.class)));

How to use npm with node.exe?

I just installed Node.js for the first time and it includes NPM, which can be ran from the Windows cmd. However, make sure that you run it as an administrator. Right click on cmd and choose "run as administrator". This allowed me to call npm commands.

Java - Convert integer to string

One that I use often:

 Integer.parseInt("1234");

Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you'd have to ask someone else.

Build error: "The process cannot access the file because it is being used by another process"

Recently ran into this problem when attempting to build a solution I am working on (not just a winforms proj).
In addition to build failure, I noticed that cleaning projects would quietly fail (checking the bin folder showed that the files had not actually been erased) and closing the Visual Studio did not end the devenv process - rather, it caused it to crash. Windows recovery process would then restart the Visual Studio.

After some trial and error, I found the problems only happened to me when I opened the solution from the "Recent" menu on starting up VS.
Opening the solution from File >> Open >> Project/Solution found it working as per usually.

Currently no idea why - will keep looking into this but for now, at least I can work!

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Android Fragments and animation

If you don't have to use the support library then have a look at Roman's answer.

But if you want to use the support library you have to use the old animation framework as described below.

After consulting Reto's and blindstuff's answers I have gotten the following code working.

The fragments appear sliding in from the right and sliding out to the left when back is pressed.

FragmentManager fragmentManager = getSupportFragmentManager();

FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);

CustomFragment newCustomFragment = CustomFragment.newInstance();
transaction.replace(R.id.fragment_container, newCustomFragment );
transaction.addToBackStack(null);
transaction.commit();

The order is important. This means you must call setCustomAnimations() before replace() or the animation will not take effect!

Next these files have to be placed inside the res/anim folder.

enter.xml:

<?xml version="1.0" encoding="utf-8"?>
<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

exit.xml:

<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="-100%"
               android:interpolator="@android:anim/accelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

pop_enter.xml:

<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="-100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

pop_exit.xml:

<?xml version="1.0" encoding="utf-8"?>
<set>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="100%"
               android:interpolator="@android:anim/accelerate_interpolator"
               android:duration="@android:integer/config_mediumAnimTime"/>
</set>

The duration of the animations can be changed to any of the default values like @android:integer/config_shortAnimTime or any other number.

Note that if in between fragment replacements a configuration change happens (for example rotation) the back action isn't animated. This is a documented bug that still exists in the rev 20 of the support library.

How can I split a string with a string delimiter?

Try this function instead.

string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);

Best Practice for Forcing Garbage Collection in C#

Not sure if it is a best practice, but when working with large amounts of images in a loop (i.e. creating and disposing a lot of Graphics/Image/Bitmap objects), i regularly let the GC.Collect.

I think I read somewhere that the GC only runs when the program is (mostly) idle, and not in the middle of a intensive loop, so that could look like an area where manual GC could make sense.

font awesome icon in select option

In case anybody wants to use the latest Version (v5.7.2)

Please find my latest version (inspired by Victors answer).

It includes all Free Icons of the "Regular"-Set: https://fontawesome.com/icons?d=gallery&s=regular&m=free

Index.html

<head>
   ...
   <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
   ...
</head>

CSS:

select {
    font-family: 'Lato', 'Font Awesome 5 Free';
    font-weight: 900;
}

HTML:

<select id="icon">
    <option value="address-book">&#xf2b9; address-book</option>
    <option value="address-card">&#xf2bb; address-card</option>
    <option value="angry">&#xf556; angry</option>
    <option value="arrow-alt-circle-down">&#xf358; arrow-alt-circle-down</option>
    <option value="arrow-alt-circle-left">&#xf359; arrow-alt-circle-left</option>
    <option value="arrow-alt-circle-right">&#xf35a; arrow-alt-circle-right</option>
    <option value="arrow-alt-circle-up">&#xf35b; arrow-alt-circle-up</option>
    <option value="bell">&#xf0f3; bell</option>
    <option value="bell-slash">&#xf1f6; bell-slash</option>
    <option value="bookmark">&#xf02e; bookmark</option>
    <option value="building">&#xf1ad; building</option>
    <option value="calendar">&#xf133; calendar</option>
    <option value="calendar-alt">&#xf073; calendar-alt</option>
    <option value="calendar-check">&#xf274; calendar-check</option>
    <option value="calendar-minus">&#xf272; calendar-minus</option>
    <option value="calendar-plus">&#xf271; calendar-plus</option>
    <option value="calendar-times">&#xf273; calendar-times</option>
    <option value="caret-square-down">&#xf150; caret-square-down</option>
    <option value="caret-square-left">&#xf191; caret-square-left</option>
    <option value="caret-square-right">&#xf152; caret-square-right</option>
    <option value="caret-square-up">&#xf151; caret-square-up</option>
    <option value="chart-bar">&#xf080; chart-bar</option>
    <option value="check-circle">&#xf058; check-circle</option>
    <option value="check-square">&#xf14a; check-square</option>
    <option value="circle">&#xf111; circle</option>
    <option value="clipboard">&#xf328; clipboard</option>
    <option value="clock">&#xf017; clock</option>
    <option value="clone">&#xf24d; clone</option>
    <option value="closed-captioning">&#xf20a; closed-captioning</option>
    <option value="comment">&#xf075; comment</option>
    <option value="comment-alt">&#xf27a; comment-alt</option>
    <option value="comment-dots">&#xf4ad; comment-dots</option>
    <option value="comments">&#xf086; comments</option>
    <option value="compass">&#xf14e; compass</option>
    <option value="copy">&#xf0c5; copy</option>
    <option value="copyright">&#xf1f9; copyright</option>
    <option value="credit-card">&#xf09d; credit-card</option>
    <option value="dizzy">&#xf567; dizzy</option>
    <option value="dot-circle">&#xf192; dot-circle</option>
    <option value="edit">&#xf044; edit</option>
    <option value="envelope">&#xf40e0 envelope </option>
    <option value="envelope-open">&#xf2b6; envelope-open</option>
    <option value="eye">&#xf06e; eye</option>
    <option value="eye-slash">&#xf070; eye-slash</option>
    <option value="file">&#xf15b; file</option>
    <option value="file-alt">&#xf15c; file-alt</option>
    <option value="file-archive">&#xf1c6; file-archive</option>
    <option value="file-audio">&#xf1c7; file-audio</option>
    <option value="file-code">&#xf1c9; file-code</option>
    <option value="file-excel">&#xf1c3; file-excel </option>
    <option value="file-image">&#xf1c5; file-image</option>
    <option value="file-pdf">&#xf1c1; file-pdf</option>
    <option value="file-powerpoint">&#xf1c4; file-powerpoint</option>
    <option value="file-video">&#xf1c8; file-video</option>
    <option value="file-word">&#xf1c2; file-word</option>
    <option value="flag">&#xf024; flag</option>
    <option value="flushed">&#xf579; flushed</option>
    <option value="folder">&#xf07b; folder</option>
    <option value="folder-open">&#xf07c; folder-open </option>
    <option value="frown">&#xf119; frown</option>
    <option value="frown-open">&#xf57a; frown-open</option>
    <option value="futbol">&#xf1e3; futbol</option>
    <option value="gem">&#xf3a5; gem</option>
    <option value="grimace">&#xf57f; grimace</option>
    <option value="grin">&#xf580; grin</option>
    <option value="grin-alt">&#xf581; grin-alt</option>
    <option value="grin-beam">&#xf582; grin-beam</option>
    <option value="grin-beam-sweet">&#xf583; grin-beam-sweet </option>
    <option value="grin-hearts">&#xf584; grin-hearts</option>
    <option value="grin-squint">&#xf585; grin-squint</option>
    <option value="grin-squint-tears">&#xf586; grin-squint-tears</option>
    <option value="grin-stars">&#xf587; grin-stars</option>
    <option value="grin-tears">&#xf588; grin-tears</option>
    <option value="grin-tongue">&#xf589; grin-tongue</option>
    <option value="grin-tongue-squint">&#xf58a; grin-tongue-squint</option>
    <option value="grin-tongue-wink">&#xf58b; grin-tongue-wink</option>
    <option value="grin-wink">&#xf58c; grin-wink </option>
    <option value="hand-lizard">&#xf258; hand-lizard</option>
    <option value="hand-paper">&#xf256; hand-paper</option>
    <option value="hand-peace">&#xf25b; hand-peace</option>
    <option value="hand-point-down">&#xf0a7; hand-point-down</option>
    <option value="hand-point-left">&#xf0a5; hand-point-left</option>
    <option value="hand-point-right">&#xf0a4; hand-point-right</option>
    <option value="hand-point-up">&#xf0a6; hand-point-up</option>
    <option value="hand-pointer">&#xf25a; hand-pointer</option>
    <option value="hand-rock">&#xf255; hand-rock </option>
    <option value="hand-scissors">&#xf257; hand-scissors</option>
    <option value="hand-spock">&#xf259; hand-spock</option>
    <option value="handshake">&#xf2b5; handshake</option>
    <option value="hdd">&#xf0a0; hdd</option>
    <option value="heart">&#xf004; heart</option>
    <option value="home">&#xf015; home</option>
    <option value="hospital">&#xf0f8; hospital</option>
    <option value="hourglass">&#xf254; hourglass</option>
    <option value="id-badge">&#xf2c1; id-badge</option>
    <option value="id-card">&#xf2c2; id-card </option>
    <option value="image">&#xf03e; image</option>
    <option value="images">&#xf302; images</option>
    <option value="keyboard">&#xf11c; keyboard</option>
    <option value="kiss">&#xf596; kiss</option>
    <option value="kiss-beam">&#xf597; kiss-beam</option>
    <option value="kiss-wink-heart">&#xf598; kiss-wink-heart</option>
    <option value="laugh">&#xf599; laugh</option>
    <option value="laugh-beam">&#xf59a; laugh-beam</option>
    <option value="laugh-squint">&#xf59b; laugh-squint </option>
    <option value="laugh-wink">&#xf59c; laugh-wink</option>
    <option value="lemon">&#xf094; lemon</option>
    <option value="life-ring">&#xf1cd; life-ring</option>
    <option value="lightbulb">&#xf0eb; lightbulb</option>
    <option value="list-alt">&#xf022; list-alt</option>
    <option value="map">&#xf279; map</option>
    <option value="meh">&#xf11a; meh</option>
    <option value="meh-blank">&#xf5a4; meh-blank</option>
    <option value="meh-rolling-eyes">&#xf5a5; meh-rolling-eyes </option>
    <option value="minus-square">&#xf146; minus-square</option>
    <option value="money-bill-alt">&#xf3d1; money-bill-alt</option>
    <option value="moon">&#xf186; moon</option>
    <option value="newspaper">&#xf1ea; newspaper</option>
    <option value="object-group">&#xf247; object-group</option>
    <option value="object-upgroup">&#xf248; object-upgroup</option>
    <option value="paper-plane">&#xf1d8; paper-plane</option>
    <option value="pause-circle">&#xf28b; pause-circle</option>
    <option value="play-circle">&#xf144; play-circle </option>
    <option value="plus-square">&#xf0fe; plus-square</option>
    <option value="question-circle">&#xf059; question-circle</option>
    <option value="registered">&#xf25d; registered</option>
    <option value="sad-cry">&#xf5b3; sad-cry</option>
    <option value="sad-tear">&#xf5b4; sad-tear</option>
    <option value="save">&#xf0c7; save</option>
    <option value="share-square">&#xf14d; share-square</option>
    <option value="smile">&#xf118; smile</option>
    <option value="smile-beam">&#xf5b8; smile-beam </option>
    <option value="smile-wink">&#xf4da; smile-wink</option>
    <option value="snowflake">&#xf2dc; snowflake</option>
    <option value="square">&#xf0c8; square</option>
    <option value="star">&#xf005; star</option>
    <option value="star-half">&#xf089; star-half</option>
    <option value="sticky-note">&#xf249; sticky-note</option>
    <option value="stop-circle">&#xf28d; stop-circle</option>
    <option value="sun">&#xf185; sun</option>
    <option value="surprise">&#xf5c2; surprise </option>
    <option value="thumbs-down">&#xf165; thumbs-down</option>
    <option value="thumbs-up">&#xf1164; thumbs-up</option>
    <option value="times-circle">&#xf057; times-circle</option>
    <option value="tired">&#xf5c8; tired</option>
    <option value="trash-alt">&#xf2ed; trash-alt</option>
    <option value="user">&#xf007; user</option>
    <option value="user-circle">&#xf2bd; user-circle</option>
    <option value="window-close">&#xf410; window-close</option>
    <option value="window-maximize">&#xf2d0; window-maximize </option>
    <option value="window-minimize">&#xf2d1; window-minimize</option>
    <option value="window-restore">&#xf2d2; window-restore</option>
</select>

Convert Array to Object

If you can use Map or Object.assign, it's very easy.

Create an array:

const languages = ['css', 'javascript', 'php', 'html'];

The below creates an object with index as keys:

Object.assign({}, languages)

Replicate the same as above with Maps

Converts to an index based object {0 : 'css'} etc...

const indexMap = new Map(languages.map((name, i) => [i, name] ));
indexMap.get(1) // javascript

Convert to an value based object {css : 'css is great'} etc...

const valueMap = new Map(languages.map(name => [name, `${name} is great!`] ));
valueMap.get('css') // css is great

How to iterate over rows in a DataFrame in Pandas

As many answers here correctly and clearly point out, you should not generally attempt to loop in pandas, but rather should write vectorized code. But the question remains if you should EVER write loops in pandas, and if so the best way to loop in those situations.

I believe there is at least one general situation where loops are appropriate: when you need to calculate some function that depends on values in other rows in a somewhat complex manner. In this case, the looping code is often simpler, more readable, and less error prone than vectorized code. The looping code might even be faster, too.

I will attempt to show this with an example. Suppose you want to take a cumulative sum of a column, but reset it whenever some other column equals zero:

import pandas as pd
import numpy as np

df = pd.DataFrame( { 'x':[1,2,3,4,5,6], 'y':[1,1,1,0,1,1]  } )

#   x  y  desired_result
#0  1  1               1
#1  2  1               3
#2  3  1               6
#3  4  0               4
#4  5  1               9
#5  6  1              15

This is a good example where you could certainly write one line of pandas to achieve this, although it's not especially readable, especially if you aren't fairly experienced with pandas already:

df.groupby( (df.y==0).cumsum() )['x'].cumsum()

That's going to be fast enough for most situations, although you could also write faster code by avoiding the groupby, but it will likely be even less readable.

Alternatively, what if we write this as a loop? You could do something like the following with numpy:

import numba as nb     

@nb.jit(nopython=True)  # optional
def custom_sum(x,y):
    x_sum = x.copy()
    for i in range(1,len(df)):
        if y[i] > 0: x_sum[i] = x_sum[i-1] + x[i]
    return x_sum

df['desired_result'] = custom_sum( df.x.to_numpy(), df.y.to_numpy() )

Admittedly, there's a bit of overhead there required to convert DataFrame columns to numpy arrays, but the core piece of code is just one line of code that you could read even if you didn't know anything about pandas or numpy:

if y[i] > 0: x_sum[i] = x_sum[i-1] + x[i]

And this code is actually faster than the vectorized code. In some quick tests with 100,000 rows, the above is about 10x faster than the groupby approach. Note that one key to the speed there is numba, which is options. Without the "@nb.jit" line, the looping code is actually about 10x slower than the groupby approach.

Clearly this example is simple enough that you would likely prefer the one line of pandas to writing a loop with its associated overhead. However, there are more complex versions of this problem for which the readability or speed of the numpy/numba loop approach likely makes sense.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to

private SSLSocketFactory delegate;

This is my TLSSocketFactory class

public class TLSSocketFactory extends SSLSocketFactory {

private SSLSocketFactory delegate;

public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    delegate = context.getSocketFactory();
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket() throws IOException {
    return enableTLSOnSocket(delegate.createSocket());
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket enableTLSOnSocket(Socket socket) {
    if(socket != null && (socket instanceof SSLSocket)) {
        ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
    }
    return socket;
}
}

and this is how i used it with okhttp and retrofit

 OkHttpClient client=new OkHttpClient();
    try {
        client = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
                .build();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

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

It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.

How to get a list of MySQL views?

If you created any view in Mysql databases then you can simply see it as you see your all tables in your particular database.

write:

--mysql> SHOW TABLES;

you will see list of tables and views of your database.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

There isn't a great way to do it out of the box. If you want to be using your cleaner syntax on a regular basis, then you can create a utility class to help out:

public class OptionalEx {
    private boolean isPresent;

    private OptionalEx(boolean isPresent) {
        this.isPresent = isPresent;
    }

    public void orElse(Runnable runner) {
        if (!isPresent) {
            runner.run();
        }
    }

    public static <T> OptionalEx ifPresent(Optional<T> opt, Consumer<? super T> consumer) {
        if (opt.isPresent()) {
            consumer.accept(opt.get());
            return new OptionalEx(true);
        }
        return new OptionalEx(false);
    }
}

Then you can use a static import elsewhere to get syntax that is close to what you're after:

import static com.example.OptionalEx.ifPresent;

ifPresent(opt, x -> System.out.println("found " + x))
    .orElse(() -> System.out.println("NOT FOUND"));

How do I debug a stand-alone VBScript script?

Click the mse7.exe installed along with Office typically at \Program Files\Microsoft Office\OFFICE11.

This will open up the debugger, open the file and then run the debugger in the GUI mode.

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}



protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

Paste this on your command line:

export LC_CTYPE="en_US.UTF-8" 

java.lang.IllegalArgumentException: contains a path separator

You cannot use path with directory separators directly, but you will have to make a file object for every directory.

NOTE: This code makes directories, yours may not need that...

File file= context.getFilesDir();
file.mkdir();

String[] array=filePath.split("/");
for(int t=0; t< array.length -1 ;t++)
{
    file=new File(file,array[t]);
    file.mkdir();
}

File f=new File(file,array[array.length-1]);

RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append);

What is the best way to redirect a page using React Router?

You can also use react router dom library useHistory;

`
import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
`

https://reactrouter.com/web/api/Hooks/usehistory

Sort a list by multiple attributes?

There is a operator < between lists e.g.:

[12, 'tall', 'blue', 1] < [4, 'tall', 'blue', 13]

will give

False

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How to use protractor to check if an element is visible?

The correct way for checking the visibility of an element with Protractor is to call the isDisplayed method. You should be careful though since isDisplayed does not return a boolean, but rather a promise providing the evaluated visibility. I've seen lots of code examples that use this method wrongly and therefore don't evaluate its actual visibility.

Example for getting the visibility of an element:

element(by.className('your-class-name')).isDisplayed().then(function (isVisible) {
    if (isVisible) {
        // element is visible
    } else {
        // element is not visible
    }
});

However, you don't need this if you are just checking the visibility of the element (as opposed to getting it) because protractor patches Jasmine expect() so it always waits for promises to be resolved. See github.com/angular/jasminewd

So you can just do:

expect(element(by.className('your-class-name')).isDisplayed()).toBeTruthy();

Since you're using AngularJS to control the visibility of that element, you could also check its class attribute for ng-hide like this:

var spinner = element.by.css('i.icon-spin');
expect(spinner.getAttribute('class')).not.toMatch('ng-hide'); // expect element to be visible

Getting vertical gridlines to appear in line plot in matplotlib

According to matplotlib documentation, The signature of the Axes class grid() method is as follows:

Axes.grid(b=None, which='major', axis='both', **kwargs)
Turn the axes grids on or off.

which can be ‘major’ (default), ‘minor’, or ‘both’ to control whether major tick grids, minor tick grids, or both are affected.

axis can be ‘both’ (default), ‘x’, or ‘y’ to control which set of gridlines are drawn.

So in order to show grid lines for both the x axis and y axis, we can use the the following code:

ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')

This method gives us finer control over what to show for grid lines.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

The serial communication manager library has many API and features targeted for the task you want. If the device is a USB-UART its VID/PID can be used. If the device is BT-SPP than platform specific APIs can be used. Take a look at this project for serial port programming: https://github.com/RishiGupta12/serial-communication-manager

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How do you auto format code in Visual Studio?

Select the text you want to automatically indent.

Click Format Selection in Edit, Advanced, or press CTRL+K, CTRL+F. Format Selection applies the smart indenting rules for the language in which you are programming to the selected text.

Step (1) :- CTRL+A

Step (2) :- CTRL+K

Step (3) :- CTRL+F

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

Groovy / grails how to determine a data type?

Just to add another option to Dónal's answer, you can also still use the good old java.lang.Object.getClass() method.

Filter LogCat to get only the messages from My Application in Android?

Using Windows command prompt: adb logcat -d | findstr <package>.

*This was first mentioned by jj_, but it took me ages to find it in the comments...

PHP date() with timezone?

U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)

echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);

Get local IP address

This is the best code I found to get the current IP, avoiding get VMWare host or other invalid IP address.

public string GetLocalIpAddress()
{
    UnicastIPAddressInformation mostSuitableIp = null;

    var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

    foreach (var network in networkInterfaces)
    {
        if (network.OperationalStatus != OperationalStatus.Up)
            continue;

        var properties = network.GetIPProperties();

        if (properties.GatewayAddresses.Count == 0)
            continue;

        foreach (var address in properties.UnicastAddresses)
        {
            if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                continue;

            if (IPAddress.IsLoopback(address.Address))
                continue;

            if (!address.IsDnsEligible)
            {
                if (mostSuitableIp == null)
                    mostSuitableIp = address;
                continue;
            }

            // The best IP is the IP got from DHCP server
            if (address.PrefixOrigin != PrefixOrigin.Dhcp)
            {
                if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
                    mostSuitableIp = address;
                continue;
            }

            return address.Address.ToString();
        }
    }

    return mostSuitableIp != null 
        ? mostSuitableIp.Address.ToString()
        : "";
}

How to read one single line of csv data in Python?

To read only the first row of the csv file use next() on the reader object.

with open('some.csv', newline='') as f:
  reader = csv.reader(f)
  row1 = next(reader)  # gets the first line
  # now do something here 
  # if first row is the header, then you can do one more next() to get the next row:
  # row2 = next(f)

or :

with open('some.csv', newline='') as f:
  reader = csv.reader(f)
  for row in reader:
    # do something here with `row`
    break

How to center links in HTML

One solution is to put them inside <center>, like this:

<center>
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</center>

I've also created a jsfiddle for you: https://jsfiddle.net/9acgLf8e/

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

How to use null in switch

Given:

public enum PersonType {
    COOL_GUY(1),
    JERK(2);

    private final int typeId;
    private PersonType(int typeId) {
        this.typeId = typeId;
    }

    public final int getTypeId() {
        return typeId;
    }

    public static PersonType findByTypeId(int typeId) {
        for (PersonType type : values()) {
            if (type.typeId == typeId) {
                return type;
            }
        }
        return null;
    }
}

For me, this typically aligns with a look-up table in a database (for rarely-updated tables only).

However, when I try to use findByTypeId in a switch statement (from, most likely, user input)...

int userInput = 3;
PersonType personType = PersonType.findByTypeId(userInput);
switch(personType) {
case COOL_GUY:
    // Do things only a cool guy would do.
    break;
case JERK:
    // Push back. Don't enable him.
    break;
default:
    // I don't know or care what to do with this mess.
}

...as others have stated, this results in an NPE @ switch(personType) {. One work-around (i.e., "solution") I started implementing was to add an UNKNOWN(-1) type.

public enum PersonType {
    UNKNOWN(-1),
    COOL_GUY(1),
    JERK(2);
    ...
    public static PersonType findByTypeId(int id) {
        ...
        return UNKNOWN;
    }
}

Now, you don't have to do null-checking where it counts and you can choose to, or not to, handle UNKNOWN types. (NOTE: -1 is an unlikely identifier in a business scenario, but obviously choose something that makes sense for your use-case).

Align div with fixed position on the right side

make a parent div, in css make it float:right then make the child div's position fixed this will make the div stay in its position at all times and on the right

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Mount remount the /
Eg.

  1. mount -o remount,rw /dev/xyz /
  2. sed -i 's/1 1/0 0/' /etc/fstab
  3. sed -i 's/1 2/0 0/' /etc/fstab
  4. reboot

Execute CMD command from code

As mentioned by the other answers you can use:

  Process.Start("notepad somefile.txt");

However, there is another way.

You can instance a Process object and call the Start instance method:

  Process process = new Process();
  process.StartInfo.FileName = "notepad.exe";
  process.StartInfo.WorkingDirectory = "c:\temp";
  process.StartInfo.Arguments = "somefile.txt";
  process.Start();

Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.

Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.

jQuery - Sticky header that shrinks when scrolling down

I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.

 /**
 * ResizeHeaderOnScroll
 *
 * @constructor
 */
var ResizeHeaderOnScroll = function()
{
    this.protocol           = window.location.protocol;
    this.domain             = window.location.host;
};

ResizeHeaderOnScroll.prototype.init    = function()
{
    if($(document).scrollTop() > 0)
    {
        $('header').data('size','big');
    } else {
        $('header').data('size','small');
    }

    ResizeHeaderOnScroll.prototype.checkScrolling();

    $(window).scroll(function(){
        ResizeHeaderOnScroll.prototype.checkScrolling();
    });
};

ResizeHeaderOnScroll.prototype.checkScrolling    = function()
{
    if($(document).scrollTop() > 0)
    {
        if($('header').data('size') == 'big')
        {
            $('header').data('size','small');
            $('header').stop().animate({
                paddingTop:'1em',
                paddingBottom:'1em'
            },200);
        }
    }
    else
      {
        if($('header').data('size') == 'small')
        {
            $('header').data('size','big');
            $('header').stop().animate({
                paddingTop:'3em'
            },200);
        }  
      }
}

$(document).ready(function(){
    var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
    resizeHeaderOnScroll.init()
})

Doctrine and LIKE query

Actually you just need to tell doctrine who's your repository class, if you don't, doctrine uses default repo instead of yours.

@ORM\Entity(repositoryClass="Company\NameOfBundle\Repository\NameOfRepository")

Switch statement fallthrough in C#?

A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code.

-- C# switch() documentation

Passing HTML to template using Flask/Jinja2

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.

Subversion stuck due to "previous operation has not finished"?

In Eclipse;

  1. Right click on your project folder > Team > Refresh/Cleanup.
  2. In Eclipse window, select clean option under Project menu item
  3. Finally, restart Eclipse

How do I set default value of select box in angularjs

It doesn't set the default value because your model isn't bound to the id or name properties, it's bound to each version object. Try setting the versionID to one of the objects and it should work, ie $scope.item.versionID = $scope.versions[2];

If you want to set by the id property then you need to add the select as syntax:

ng-options="version.id as version.name for version in versions"

http://jsfiddle.net/LrhAQ/1/

Entity Framework Migrations renaming tables and columns

Table names and column names can be specified as part of the mapping of DbContext. Then there is no need to do it in migrations.

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Restaurant>()
            .HasMany(p => p.Cuisines)
            .WithMany(r => r.Restaurants)
            .Map(mc =>
            {
                mc.MapLeftKey("RestaurantId");
                mc.MapRightKey("CuisineId");
                mc.ToTable("RestaurantCuisines");
            });
     }
}

how to convert string to numerical values in mongodb

If you can edit all documents in aggregate :

"TimeStamp": {$toDecimal: {$toDate: "$Your Date"}}

And for the client, you set the query :

Date.parse("Your date".toISOString())

That's what makes you whole work with ISODate.

How to re-index all subarray elements of a multidimensional array?

$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';

$array = array_values($array);

through this function you can reset your array

$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';

How can I force gradle to redownload dependencies?

If you are using eclipse and if you want force eclipse to re load dependencies you could try below command

gradlew clean cleaneclipse build eclipse --refresh-dependencies

jQuery: get data attribute

1. Try this: .attr()

  $('.field').hover(function () {
    var value=$(this).attr('data-fullText');
  $(this).html(value);
});

DEMO 1: http://jsfiddle.net/hsakapandit/Jn4V3/

2. Try this: .data()

$('.field').hover(function () {
    var value=$(this).data('fulltext');
  $(this).html(value);
});

DEMO 2: http://jsfiddle.net/hsakapandit/Jn4V3/1/

SQL Server: Get data for only the past year

Look up dateadd in BOL

dateadd(yy,-1,getdate())

How to position background image in bottom right corner? (CSS)

Did you try something like:

body {background: url('[url to your image]') no-repeat right bottom;}

Initialize empty vector in structure - c++

Like this:

#include <string>
#include <vector>

struct user
{
    std::string username;
    std::vector<unsigned char> userpassword;
};

int main()
{
    user r;   // r.username is "" and r.userpassword is empty
    // ...
}

How can I style even and odd elements?

_x000D_
_x000D_
li:nth-child(1n) { color:green; }_x000D_
li:nth-child(2n) { color:red; }
_x000D_
<ul>_x000D_
  <li>list element 1</li>_x000D_
  <li>list element 2</li>_x000D_
  <li>list element 3</li>_x000D_
  <li>list element 4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

See browser support here : CSS3 :nth-child() Selector

How to access form methods and controls from a class in C#?

You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties.

Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes.

rp

How to download folder from putty using ssh client

I use both PuTTY and Bitvise SSH Client. PuTTY handles screen sessions better, but Bitvise automatically opens up a SFTP window so you can transfer files just like you would with an FTP client.

'No JUnit tests found' in Eclipse

Click 'Run'->choose your JUnit->in 'Test Runner' select the JUnit version you want to run with.

enter image description here