Programs & Examples On #Decidable

Decidable languages are languages such that the problem of whether a given word belongs to it or not is decidable. A decision problem, i.e., a question with a yes/no answer, is called decidable if there exists an algorithm (a Turing machine) that can and will return a Boolean true or false value (instead of looping indefinitely).

Superscript in markdown (Github flavored)?

<sup> and <sub> tags work and are your only good solution for arbitrary text. Other solutions include:

Unicode

If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.

I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:

  • ° SUPERSCRIPT ZERO (U+2070)
  • ¹ SUPERSCRIPT ONE (U+00B9)
  • ² SUPERSCRIPT TWO (U+00B2)
  • ³ SUPERSCRIPT THREE (U+00B3)
  • n SUPERSCRIPT LATIN SMALL LETTER N (U+207F)

People also often reach for <sup> and <sub> tags in an attempt to render specific symbols like these:

  • TRADE MARK SIGN (U+2122)
  • ® REGISTERED SIGN (U+00AE)
  • ? SERVICE MARK (U+2120)

Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.

Alternatively, you could use the hex values above in an HTML character escape. Eg, &#x00B2; instead of ². This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.

Images

If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:

![Alt text goes here, if you'd like](path/to/image.png) 

You can use a full path (eg. starting with https:// or http://) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.

If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.

Check if an element is present in an array

You can use the _contains function from the underscore.js library to achieve this:

if (_.contains(haystack, needle)) {
  console.log("Needle found.");
};

Pyspark: Exception: Java gateway process exited before sending the driver its port number

I use Mac OS. I fixed the problem!

Below is how I fixed it.

JDK8 seems works fine. (https://github.com/jupyter/jupyter/issues/248)

So I checked my JDK /Library/Java/JavaVirtualMachines, I only have jdk-11.jdk in this path.

I downloaded JDK8 (I followed the link). Which is:

brew tap caskroom/versions
brew cask install java8

After this, I added

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"

to ~/.bash_profile file. (you sholud check your jdk1.8 file name)

It works now! Hope this help :)

Convert java.util.Date to String

Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);

Check if value exists in dataTable?

You can use LINQ-to-DataSet with Enumerable.Any:

String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));

Another approach is to use DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
    // do something...
}

Q: what if we do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to find out but is there a better way? –

Yes, you can use this query:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

How do I create a unique constraint that also allows nulls?

this code if u make a register form with textBox and use insert and ur textBox is empty and u click on submit button .

CREATE UNIQUE NONCLUSTERED INDEX [IX_tableName_Column]
ON [dbo].[tableName]([columnName] ASC) WHERE [columnName] !=`''`;

Calculating bits required to store decimal number

let its required n bit then 2^n=(base)^digit and then take log and count no. for n

What is the best project structure for a Python application?

Check out Open Sourcing a Python Project the Right Way.

Let me excerpt the project layout part of that excellent article:

When setting up a project, the layout (or directory structure) is important to get right. A sensible layout means that potential contributors don't have to spend forever hunting for a piece of code; file locations are intuitive. Since we're dealing with an existing project, it means you'll probably need to move some stuff around.

Let's start at the top. Most projects have a number of top-level files (like setup.py, README.md, requirements.txt, etc). There are then three directories that every project should have:

  • A docs directory containing project documentation
  • A directory named with the project's name which stores the actual Python package
  • A test directory in one of two places
    • Under the package directory containing test code and resources
    • As a stand-alone top level directory To get a better sense of how your files should be organized, here's a simplified snapshot of the layout for one of my projects, sandman:
$ pwd
~/code/sandman
$ tree
.
|- LICENSE
|- README.md
|- TODO.md
|- docs
|   |-- conf.py
|   |-- generated
|   |-- index.rst
|   |-- installation.rst
|   |-- modules.rst
|   |-- quickstart.rst
|   |-- sandman.rst
|- requirements.txt
|- sandman
|   |-- __init__.py
|   |-- exception.py
|   |-- model.py
|   |-- sandman.py
|   |-- test
|       |-- models.py
|       |-- test_sandman.py
|- setup.py

As you can see, there are some top level files, a docs directory (generated is an empty directory where sphinx will put the generated documentation), a sandman directory, and a test directory under sandman.

How to rollback a specific migration?

rake db:migrate:down VERSION=your_migrations's_version_number_here

The version is the numerical prefix on the migration's file name

How to find version:

Your migration files are stored in your rails_root/db/migrate directory. Find appropriate file up to which you want to rollback and copy the prefix number.

for example

file name: 20140208031131_create_roles.rb then the version is 20140208031131

Checking if a folder exists using a .bat file

For a file:

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

Replace yourfilename with the name of your file.

For a directory:

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

Replace yourfoldername with the name of your folder.

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

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

I see that the question has already been answered a number of times, just want to put in my inputs on the same question.

Lets us go ahead and create a simplified Animal class hierarchy.

abstract class Animal {
    void eat() {
        System.out.println("animal eating");
    }
}

class Dog extends Animal {
    void bark() { }
}

class Cat extends Animal {
    void meow() { }
}

Now let us have a look at our old friend Arrays, which we know support polymorphism implicitly-

class TestAnimals {
    public static void main(String[] args) {
        Animal[] animals = {new Dog(), new Cat(), new Dog()};
        Dog[] dogs = {new Dog(), new Dog(), new Dog()};
        takeAnimals(animals);
        takeAnimals(dogs);
    }

    public void takeAnimals(Animal[] animals) {
        for(Animal a : animals) {
            System.out.println(a.eat());
        }
    }   
}

The class compiles fine and when we run the above class we get the output

animal eating
animal eating
animal eating
animal eating
animal eating
animal eating

The point to note here is that the takeAnimals() method is defined to take anything which is of type Animal, it can take an array of type Animal and it can take an array of Dog as well because Dog-is-a-Animal. So this is Polymorphism in action.

Let us now use this same approach with generics,

Now say we tweak our code a little bit and use ArrayLists instead of Arrays -

class TestAnimals {
    public static void main(String[] args) {
        ArrayList<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Dog());
        takeAnimals(animals);
    }

    public void takeAnimals(ArrayList<Animal> animals) {
        for(Animal a : animals) {
            System.out.println(a.eat());
        }
    }   
}

The class above will compile and will produce the output -

animal eating
animal eating
animal eating
animal eating
animal eating
animal eating

So we know this works, now lets tweak this class a little bit to use Animal type polymorphically -

class TestAnimals {
    public static void main(String[] args) {
        ArrayList<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Dog());

        ArrayList<Dog> dogs = new ArrayList<Dog>();
        takeAnimals(animals);
        takeAnimals(dogs);
    }

    public void takeAnimals(ArrayList<Animal> animals) {
        for(Animal a : animals) {
            System.out.println(a.eat());
        }
    }   
}

Looks like there should be no problem in compiling the above class as the takeAnimals() method is designed to take any ArrayList of type Animal and Dog-is-a-Animal so it should not be a deal breaker here.

But, unfortunately the compiler throws an error and doesn't allow us to pass a Dog ArrayList to a variable expecting Animal ArrayList.

You ask why?

Because just imagine, if JAVA were to allow the Dog ArrayList - dogs - to be put into the Animal ArrayList - animals - and then inside the takeAnimals() method somebody does something like -

animals.add(new Cat());

thinking that this should be doable because ideally it is an Animal ArrayList and you should be in a position to add any cat to it as Cat-is-also-a-Animal, but in real you passed a Dog type ArrayList to it.

So, now you must be thinking the the same should have happened with the Arrays as well. You are right in thinking so.

If somebody tries to do the same thing with Arrays then Arrays are also going to throw an error but Arrays handle this error at runtime whereas ArrayLists handle this error at compile time.

Why is there an unexplainable gap between these inline-block div elements?

The easiest fix is to just float the container. (eg. float: left;) On another note, each id should be unique, meaning you can't use the same id twice in the same HTML document. You should use classes instead, where you can use the same class for multiple elements.

.container {
    position: relative;
    background: rgb(255, 100, 0);
    margin: 0;
    width: 40%;
    height: 100px;
    float: left;
}

Applying an ellipsis to multiline text

p{
line-height: 20px;
width: 157px;
white-space: nowrap; 
overflow: hidden;
text-overflow: ellipsis;
}

or we can restrict the lines by using and height and overflow.

How long is the SHA256 hash?

Encoding options for SHA256's 256 bits:

  1. Base64: 6 bits per char = CHAR(44) including padding character
  2. Hex: 4 bits per char = CHAR(64)
  3. Binary: 8 bits per byte = BINARY(32)

Convert HTML to NSAttributedString in iOS

honoring font family, dynamic font I've concocted this abomination:

extension NSAttributedString
{
    convenience fileprivate init?(html: String, font: UIFont? = Font.dynamic(style: .subheadline))
    {
        guard let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
        var totalString = html
        /*
         https://stackoverflow.com/questions/32660748/how-to-use-apples-new-san-francisco-font-on-a-webpage
            .AppleSystemUIFont I get in font.familyName does not work
         while -apple-system does:
         */
        var ffamily = "-apple-system"
        if let font = font {
            let lLDBsucks = font.familyName
            if !lLDBsucks.hasPrefix(".appleSystem") {
                ffamily = font.familyName
            }
            totalString = "<style>\nhtml * {font-family: \(ffamily) !important;}\n            </style>\n" + html
        }
        guard let data = totalString.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
            return nil
        }
        assert(Thread.isMainThread)
        guard let attributedText = try?  NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
            return nil
        }
        let mutable = NSMutableAttributedString(attributedString: attributedText)
        if let font = font {
        do {
            var found = false
            mutable.beginEditing()
            mutable.enumerateAttribute(NSAttributedString.Key.font, in: NSMakeRange(0, attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
                    if let oldFont = value as? UIFont {
                        let newsize = oldFont.pointSize * 15 * Font.scaleHeruistic / 12
                        let newFont = oldFont.withSize(newsize)
                        mutable.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
                        found = true
                    }
                }
                if !found {
                    // No font was found - do something else?
                }

            mutable.endEditing()
            
//            mutable.addAttribute(.font, value: font, range: NSRange(location: 0, length: mutable.length))
        }
        self.init(attributedString: mutable)
    }

}

alternatively you can use the versions this was derived from and set font on UILabel after setting attributedString

this will clobber the size and boldness encapsulated in the attributestring though

kudos for reading through all the answers up to here. You are a very patient man woman or child.

How can I install a CPAN module into a local directory?

I had a similar problem, where I couldn't even install local::lib

I created an installer that installed the module somewhere relative to the .pl files

The install goes like:

perl Makefile.PL PREFIX=./modulos
make
make install

Then, in the .pl file that requires the module, which is in ./

use lib qw(./modulos/share/perl/5.8.8/); # You may need to change this path
use module::name;

The rest of the files (makefile.pl, module.pm, etc) require no changes.

You can call the .pl file with just

perl file.pl

How do I reflect over the members of dynamic object?

Requires Newtonsoft Json.Net

A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:

public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
    JObject attributesAsJObject = dynamicToGetPropertiesFor;
    Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
    List<string> toReturn = new List<string>();
    foreach (string key in values.Keys)
    {
        toReturn.Add(key);                
    }
    return toReturn;
}

Then you simply foreach like this:

foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
    dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
    // And
    dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}

Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.

How to append to the end of an empty list?

use my_list.append(...) and do not use and other list to append as list are mutable.

jQuery - Trigger event when an element is removed from the DOM

There is no built-in event for removing elements, but you can create one by fake-extending jQuery's default remove method. Note that the callback must be called before actually removing it to keep reference.

(function() {
    var ev = new $.Event('remove'),
        orig = $.fn.remove;
    $.fn.remove = function() {
        $(this).trigger(ev);
        return orig.apply(this, arguments);
    }
})();

$('#some-element').bind('remove', function() {
    console.log('removed!');
    // do pre-mortem stuff here
    // 'this' is still a reference to the element, before removing it
});

// some other js code here [...]

$('#some-element').remove();

Note: some problems with this answer have been outlined by other posters.

  1. This won't work when the node is removed via html() replace() or other jQuery methods
  2. This event bubbles up
  3. jQuery UI overrides remove as well

The most elegant solution to this problem seems to be: https://stackoverflow.com/a/10172676/216941

How to set cursor to input box in Javascript?

Sometimes you do get focus but no cursor in a text field. In this case you would do this:

document.getElementById(frmObj.id).select();

How can I get the current page's full URL on a Windows/IIS server?

Use this class to get the URL works.

class VirtualDirectory
{
    var $protocol;
    var $site;
    var $thisfile;
    var $real_directories;
    var $num_of_real_directories;
    var $virtual_directories = array();
    var $num_of_virtual_directories = array();
    var $baseURL;
    var $thisURL;

    function VirtualDirectory()
    {
        $this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
        $this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];
        $this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);
        $this->real_directories = $this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['PHP_SELF'])));
        $this->num_of_real_directories = count($this->real_directories);
        $this->virtual_directories = array_diff($this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['REQUEST_URI']))),$this->real_directories);
        $this->num_of_virtual_directories = count($this->virtual_directories);
        $this->baseURL = $this->site . "/" . implode("/", $this->real_directories) . "/";
        $this->thisURL = $this->baseURL . implode("/", $this->virtual_directories) . "/";
    }

    function cleanUp($array)
    {
        $cleaned_array = array();
        foreach($array as $key => $value)
        {
            $qpos = strpos($value, "?");
            if($qpos !== false)
            {
                break;
            }
            if($key != "" && $value != "")
            {
                $cleaned_array[] = $value;
            }
        }
        return $cleaned_array;
    }
}

$virdir = new VirtualDirectory();
echo $virdir->thisURL;

Split Java String by New Line

Maybe this would work:

Remove the double backslashes from the parameter of the split method:

split = docStr.split("\n");

How can I clear or empty a StringBuilder?

You should use sb.delete(0, sb.length()) or sb.setLength(0) and NOT create a new StringBuilder().

See this related post for performance: Is it better to reuse a StringBuilder in a loop?

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

Java generating Strings with placeholders

You won't need a library; if you are using a recent version of Java, have a look at String.format:

String.format("Hello %s!", "world");

How to maintain state after a page refresh in React.js?

You can "persist" the state using local storage as Omar Suggest, but it should be done once the state has been set. For that you need to pass a callback to the setState function and you need to serialize and deserialize the objects put into local storage.

constructor(props) {
  super(props);
  this.state = {
    allProjects: JSON.parse(localStorage.getItem('allProjects')) || []
  }
}


addProject = (newProject) => {
  ...

  this.setState({
    allProjects: this.state.allProjects.concat(newProject)
  },() => {
    localStorage.setItem('allProjects', JSON.stringify(this.state.allProjects))
  });
}

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.

Good summary - Conceito: Entity-Control-Boundary Pattern

OOAD

Android MediaPlayer Stop and Play

You should use only one mediaplayer object

    public class PlayaudioActivity extends Activity {

        private MediaPlayer mp;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button b = (Button) findViewById(R.id.button1);
            Button b2 = (Button) findViewById(R.id.button2);
            final TextView t = (TextView) findViewById(R.id.textView1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
                    mp.start();
                }

            });

            b2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
                    mp.start();
                }
            });
        }

        private void stopPlaying() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
           }
        }
    }

Calculating powers of integers

Use the below logic to calculate the n power of a.

Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n) Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).

public  int calculatePower1(int a, int b) {
    if (b == 0) {
        return 1;
    }

    int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;

    int temp = 1;
    for (int i = 1; i <= val; i++) {
        temp *= a;
    }

    if (b % 2 == 0) {
        return temp * temp;
    } else {
        return a * temp * temp;
    }
}

Split large string in n-size chunks in JavaScript

You can do something like this:

"1234567890".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "90"]

The method will still work with strings whose size is not an exact multiple of the chunk-size:

"123456789".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "9"]

In general, for any string out of which you want to extract at-most n-sized substrings, you would do:

str.match(/.{1,n}/g); // Replace n with the size of the substring

If your string can contain newlines or carriage returns, you would do:

str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring

As far as performance, I tried this out with approximately 10k characters and it took a little over a second on Chrome. YMMV.

This can also be used in a reusable function:

function chunkString(str, length) {
  return str.match(new RegExp('.{1,' + length + '}', 'g'));
}

Route [login] not defined

In app\Exceptions\Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('auth.login'));
}

How to have jQuery restrict file types on upload?

function validateFileExtensions(){
        var validFileExtensions = ["jpg", "jpeg", "gif", "png"];
        var fileErrors = new Array();

        $( "input:file").each(function(){
            var file = $(this).value;
            var ext = file.split('.').pop();
            if( $.inArray( ext, validFileExtensions ) == -1) {
                fileErrors.push(file);
            }
        });

        if( fileErrors.length > 0 ){
            var errorContainer = $("#validation-errors");
            for(var i=0; i < fileErrors.length; i++){
                errorContainer.append('<label for="title" class="error">* File:'+ file +' do not have a valid format!</label>');
            }
            return false;
        }
        return true;
    }

Objective-C and Swift URL encoding

It's called URL encoding. More here.

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
           (CFStringRef)self,
           NULL,
           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
           CFStringConvertNSStringEncodingToEncoding(encoding));
}

How to break out from a ruby block?

I wanted to just be able to break out of a block - sort of like a forward goto, not really related to a loop. In fact, I want to break of of a block that is in a loop without terminating the loop. To do that, I made the block a one-iteration loop:

for b in 1..2 do
    puts b
    begin
        puts 'want this to run'
        break
        puts 'but not this'
    end while false
    puts 'also want this to run'
end

Hope this helps the next googler that lands here based on the subject line.

Windows 7 - Add Path

Try this in cmd:

cd address_of_sumatrapdf.exe_file && sumatrapdf.exe

Where you should put the address of your .exe file instead of adress_of_sumatrapdf.exe_file.

Error handling in AngularJS http get then construct

You can make this bit more cleaner by using:

$http.get(url)
    .then(function (response) {
        console.log('get',response)
    })
    .catch(function (data) {
        // Handle error here
    });

Similar to @this.lau_ answer, different approach.

Log all requests from the python-requests module

I'm using a logger_config.yaml file to configure my logging, and to get those logs to show up, all I had to do was to add a disable_existing_loggers: False to the end of it.

My logging setup is rather extensive and confusing, so I don't even know a good way to explain it here, but if someone's also using a YAML file to configure their logging, this might help.

https://docs.python.org/3/howto/logging.html#configuring-logging

Bootstrap datetimepicker is not a function

The problem is that you have not included bootstrap.min.css. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>                       
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

DEMO

ps command doesn't work in docker container

If you're running a CentOS container, you can install ps using this command:

yum install -y procps

Running this command on Dockerfile:

RUN yum install -y procps

How do I get textual contents from BLOB in Oracle SQL

You can use below SQL to read the BLOB Fields from table.

SELECT DBMS_LOB.SUBSTR(BLOB_FIELD_NAME) FROM TABLE_NAME;

Error type 3 Error: Activity class {} does not exist

Faced this problem in android studio 3.5.1 Took me a day to solve this problem,Tried everything including cleaning cache,restart and renaming package name as well. So if any of above did't work than try this.

Just go to gradle > Tasks > Install > UninstallAll

Here is the link: Error type 3: Activity Class {...} does not exist

Setting the correct encoding when piping stdout in Python

export PYTHONIOENCODING=utf-8

do the job, but can't set it on python itself ...

what we can do is verify if isn't setting and tell the user to set it before call script with :

if __name__ == '__main__':
    if (sys.stdout.encoding is None):
        print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout."
        exit(1)

Update to reply to the comment: the problem just exist when piping to stdout . I tested in Fedora 25 Python 2.7.13

python --version
Python 2.7.13

cat b.py

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys

print sys.stdout.encoding

running ./b.py

UTF-8

running ./b.py | less

None

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

What is the difference between URI, URL and URN?

URL -- Uniform Resource Locator

Contains information about how to fetch a resource from its location. For example:

  • http://example.com/mypage.html
  • ftp://example.com/download.zip
  • mailto:[email protected]
  • file:///home/user/file.txt
  • http://example.com/resource?foo=bar#fragment
  • /other/link.html (A relative URL, only useful in the context of another URL)

URLs always start with a protocol (http) and usually contain information such as the network host name (example.com) and often a document path (/foo/mypage.html). URLs may have query parameters and fragment identifiers.

URN -- Uniform Resource Name

Identifies a resource by name. It always starts with the prefix urn: For example:

  • urn:isbn:0451450523 to identify a book by its ISBN number.
  • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66 a globally unique identifier
  • urn:publishing:book - An XML namespace that identifies the document as a type of book.

URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a "resolver". The document can then be downloaded from the URL.

URI -- Uniform Resource Identifier

URIs encompasses both URLs, URNs, and other ways to indicate a resource.

An example of a URI that is neither a URL nor a URN would be a data URI such as data:,Hello%20World. It is not a URL or URN because the URI contains the data. It neither names it, nor tells you how to locate it over the network.

There are also uniform resource citations (URCs) that point to meta data about a document rather than to the document itself. An example of a URC would be an indicator for viewing the source code of a web page: view-source:http://example.com/. A URC is another type of URI that is neither URL nor URN.

Frequently Asked Questions

I've heard that I shouldn't say URL anymore, why?

The w3 spec for HTML says that the href of an anchor tag can contain a URI, not just a URL. You should be able to put in a URN such as <a href="urn:isbn:0451450523">. Your browser would then resolve that URN to a URL and download the book for you.

Do any browsers actually know how to fetch documents by URN?

Not that I know of, but modern web browser do implement the data URI scheme.

Can a URI be both a URL and a URN?

Good question. I've seen lots of places on the web that state this is true. I haven't been able to find any examples of something that is both a URL and a URN. I don't see how it is possible because a URN starts with urn: which is not a valid network protocol.

Does the difference between URL and URI have anything to do with whether it is relative or absolute?

No. Both relative and absolute URLs are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has query parameters?

No. Both URLs with and without query parameters are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has a fragment identifier?

No. Both URLs with and without fragment identifiers are URLs (and URIs.)

Is a tel: URI a URL or a URN?

For example tel:1-800-555-5555. It doesn't start with urn: and it has a protocol for reaching a resource over a network. It must be a URL.

But doesn't the w3C now say that URLs and URIs are the same thing?

Yes. The W3C realized that there is a ton of confusion about this. They issued a URI clarification document that says that it is now OK to use URL and URI interchangeably. It is no longer useful to strictly segment URIs into different types such as URL, URN, and URC.

How to force cp to overwrite without confirmation

Another way to call the command without the alias is to use the command builtin in bash.

command cp -rf /zzz/zzz/*

random.seed(): What does it do?

Imho, it is used to generate same random course result when you use random.seed(samedigit) again.

In [47]: random.randint(7,10)

Out[47]: 9


In [48]: random.randint(7,10)

Out[48]: 9


In [49]: random.randint(7,10)

Out[49]: 7


In [50]: random.randint(7,10)

Out[50]: 10


In [51]: random.seed(5)


In [52]: random.randint(7,10)

Out[52]: 9


In [53]: random.seed(5)


In [54]: random.randint(7,10)

Out[54]: 9

How to generate auto increment field in select query

In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone

select 
    ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1, 
    period_next_id, period_name_long
from 
(
  select distinct col1, period_name_long, 'X' as num
  from {TABLE} 
) as x

Visual Studio keyboard shortcut to display IntelliSense

In Visual Studio 2015 this shortcut opens a preview of the definition which even works through typedefs and #defines.

Ctrl + , (comma)

Enter image description here

How to tell if a connection is dead in python

Short answer:

use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.

Long answer:

The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.

TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.

Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.

Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.

So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.

Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().

Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.

I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".

In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.

What you can do is:

  • set the socket to non-blocking mode, but than you get a system-depended error to indicate the receive buffer is empty, or the send buffer is full
  • stick to blocking mode but set a very short socket timeout. This will allow you to "ping" or "check" the socket with recv(), pretty much what you want to do
  • use select() call or asyncore module with a very short timeout. Error reporting is still system-specific.

For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.

I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:

  • receive a proper response on the same socket for the exact message that you sent. Basically you are using the higher level protocol to provide confirmation.
  • perform a successful shutdow() and close() on the socket

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)

Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.

How to insert an item into an array at a specific index (JavaScript)?

Taking profit of reduce method as following:

function insert(arr, val, index) {
    return index >= arr.length 
        ? arr.concat(val)
        : arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}

So at this way we can return a new array (will be a cool functional way - more much better than use push or splice) with the element inserted at index, and if the index is greater than the length of the array it will be inserted at the end.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.

theoretically one server can only run as many requests concurrently as number of cores on it..

It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?

also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking

If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler

OpenCV - Saving images to a particular folder of choice

The solution provided by ebeneditos works perfectly.

But if you have cv2.imwrite() in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite() individually.

As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()

import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)

Now if you want to modify the path, you just have to change the path variable.

Edited based on solution provided by Kallz

I want to align the text in a <td> to the top

https://developer.mozilla.org/en/CSS/vertical-align

<table style="height: 275px; width: 188px">
    <tr>
        <td style="width: 259px; vertical-align:top">
            main page
        </td>
    </tr>
</table>

?

Why is the time complexity of both DFS and BFS O( V + E )

I think every edge has been considered twice and every node has been visited once, so the total time complexity should be O(2E+V).

Interview Question: Merge two sorted singly linked lists without creating new nodes

First of all understand the mean of "without creating any new extra nodes", As I understand it does not mean that I can not have pointer(s) which points to an existing node(s).

You can not achieve it without talking pointers to existing nodes, even if you use recursion to achieve the same, system will create pointers for you as call stacks. It is just like telling system to add pointers which you have avoided in your code.

Simple function to achieve the same with taking extra pointers:

typedef struct _LLNode{
    int             value;
    struct _LLNode* next;
}LLNode;


LLNode* CombineSortedLists(LLNode* a,LLNode* b){
    if(NULL == a){
        return b;
    }
    if(NULL == b){
        return a;
    }
    LLNode* root  = NULL;
    if(a->value < b->value){
        root = a;
        a = a->next;
    }
    else{
        root = b;
        b    = b->next;
    }
    LLNode* curr  = root;
    while(1){
        if(a->value < b->value){
            curr->next = a;
            curr = a;
            a=a->next;
            if(NULL == a){
                curr->next = b;
                break;
            }
        }
        else{
            curr->next = b;
            curr = b;
            b=b->next;
            if(NULL == b){
                curr->next = a;
                break;
            }
        }
    }
    return root;
}

Make page to tell browser not to cache/preserve input values

Are you explicitly setting the values as blank? For example:

<input type="text" name="textfield" value="">

That should stop browsers putting data in where it shouldn't. Alternatively, you can add the autocomplete attribute to the form tag:

<form autocomplete="off" ...></form>

Google Chrome display JSON AJAX response as tree and not as a plain text

To see a tree view in recent versions of Chrome:

Navigate to Developer Tools > Network > the given response > Preview

Gradle error: could not execute build using gradle distribution

I updated to 0.3.0 and had the same issue. I had to end up changing my Gradle version to classpath 'com.android.tools.build:gradle:0.6.1+' and in build.gradle and also changing the distributionUrl to distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-bin.zip in the gradle-wrapper.properties file. Then I did a local import of the Gradle file. That worked for me.

ASP.NET Custom Validator Client side & Server Side validation not firing

Did you verify that the control causing the post back has CausesValidation set to tru and that it does not have a validation group assigned to it?

I'm not sure what else might cause this behavior.

Save ArrayList to SharedPreferences

this should work:

public void setSections (Context c,  List<Section> sectionList){
    this.sectionList = sectionList;

    Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
    String sectionListString = new Gson().toJson(sectionList,sectionListType);

    SharedPreferences.Editor editor = getSharedPreferences(c).edit().putString(PREFS_KEY_SECTIONS, sectionListString);
    editor.apply();
}

them, to catch it just:

public List<Section> getSections(Context c){

    if(this.sectionList == null){
        String sSections = getSharedPreferences(c).getString(PREFS_KEY_SECTIONS, null);

        if(sSections == null){
            return new ArrayList<>();
        }

        Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
        try {

            this.sectionList = new Gson().fromJson(sSections, sectionListType);

            if(this.sectionList == null){
                return new ArrayList<>();
            }
        }catch (JsonSyntaxException ex){

            return new ArrayList<>();

        }catch (JsonParseException exc){

            return new ArrayList<>();
        }
    }
    return this.sectionList;
}

it works for me.

How to use bitmask?

Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45

unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));

The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.

Insert multiple lines into a file after specified pattern using shell script

Here is a more generic solution based on @rindeal solution which does not work on MacOS/BSD (/r expects a file):

cat << DOC > input.txt
abc
cdef
line
DOC
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF

# outputs:
abc
cdef
line 1
line 2
line

This can be used to pipe anything into the file at the given position:

$ date | sed '/^cdef$/ r /dev/stdin' input.txt

# outputs
abc
cdef
Tue Mar 17 10:50:15 CET 2020
line

Also, you could add multiple commands which allows deleting the marker line cdef:

$ date | sed '/^cdef$/ {
  r /dev/stdin
  d
}' input.txt

# outputs
abc
Tue Mar 17 10:53:53 CET 2020
line

Update Item to Revision vs Revert to Revision

@BaltoStar update to revision syntax:

http://svnbook.red-bean.com/en/1.6/svn.ref.svn.c.update.html

svn update -r30

Where 30 is revision number. Hope this help!

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

Selenium -- How to wait until page is completely loaded

yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again

understand it with a dummy code

// clicking on view details 
driver.findElement(By.id("")).click();
// closing the pop up 
driver.findElement(By.id("")).click();


// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost 
// so to overcome this you have to re identify the locator strategy for add item 
// Please note : this is one of the way to overcome stale element exception 

// Step 1 please add a universal wait in your script like below 
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser

XSLT counting elements with a given value

This XPath:

count(//Property[long = '11007'])

returns the same value as:

count(//Property/long[text() = '11007'])

...except that the first counts Property nodes that match the criterion and the second counts long child nodes that match the criterion.

As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:

count(//Property[@Name = 'Alive'][long = '11007'])

because it means the same thing as:

count(//Property[@Name = 'Alive' and long = '11007'])

Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.

EDIT (after question edit)


You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!

Here you go:

count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])

Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long element.

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Just add autofocus in first input or textarea.

<input type="text" name="name" id="xax" autofocus="autofocus" />

Overcoming "Display forbidden by X-Frame-Options"

Use this line given below instead of header() function.

echo "<script>window.top.location = 'https://apps.facebook.com/yourappnamespace/';</script>";

What is the alternative for ~ (user's home directory) on Windows command prompt?

You can use %systemdrive%%homepath% environment variable to accomplish this.

The two command variables when concatenated gives you the desired user's home directory path as below:

  1. Running echo %systemdrive% on command prompt gives:

    C:
    
  2. Running echo %homepath% on command prompt gives:

    \Users\<CurrentUserName>
    

When used together it becomes:

C:\Users\<CurrentUserName>

Tkinter: "Python may not be configured for Tk"

Under Arch/Manjaro just install the package tk:

sudo pacman -S tk

Collapse all methods in Visual Studio Code

You should add user settings:

{
    "editor.showFoldingControls": "always",
    "editor.folding": true,
    "editor.foldingStrategy": "indentation", 
}

How to get the nth occurrence in a string?

Shorter way and I think easier, without creating unnecessary strings.

const findNthOccurence = (string, nth, char) => {
  let index = 0
  for (let i = 0; i < nth; i += 1) {
    if (index !== -1) index = string.indexOf(char, index + 1)
  }
  return index
}

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

H.264 file size for 1 hr of HD video

It would be a couple of gigs per hour.

MPEG-4 (of which H.264 is a sub-part) define high quality as around 4Mbps. which would be 1.8GB per hour.

This can vary depending on the type of video and the type of compression used.

u'\ufeff' in Python string

That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.

Use of document.getElementById in JavaScript

It is just a selector that helps you select specific tag <p id = 'demo'></p> elements which help you change the behavior, in any event (either mouse or keyboard).

Rollback to an old Git commit in a public repo

Let's say you work on a project and after a day or so. You notice one feature is still giving you errors. But you do not know what change you made that caused the error. So you have to fish previous working commits. To revert to a specific commit:

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 .

Ok, so that commit works for you. No more error. You pinpointed the issue. Now you can go back to latest commit:

git checkout 792d9294f652d753514dc2033a04d742decb82a5 .

And checkout a specific file before it caused the error (in my case I use example Gemfile.lock):

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 -- /projects/myproject/Gemfile.lock

And this is one way to handle errors you created in commits without realizing the errors until later.

How to get just one file from another branch

git checkout master               -go to the master branch first
git checkout <your-branch> -- <your-file> --copy your file data from your branch.

git show <your-branch>:path/to/<your-file> 

Hope this will help you. Please let me know If you have any query.

How can I remove a key from a Python dictionary?

It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I'll add this as an answer to save others googling time:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

Documentation

How to get build time stamp from Jenkins build variables?

BUILD_ID used to provide this information but they changed it to provide the Build Number since Jenkins 1.597. Refer this for more information.

You can achieve this using the Build Time Stamp plugin as pointed out in the other answers.

However, if you are not allowed or not willing to use a plugin, follow the below method:

def BUILD_TIMESTAMP = null
withCredentials([usernamePassword(credentialsId: 'JenkinsCredentials', passwordVariable: 'JENKINS_PASSWORD', usernameVariable: 'JENKINS_USERNAME')]) {
   sh(script: "curl https://${JENKINS_USERNAME}:${JENKINS_PASSWORD}@<JENKINS_URL>/job/<JOB_NAME>/lastBuild/buildTimestamp", returnStdout: true).trim();
}
println BUILD_TIMESTAMP

This might seem a bit of overkill but manages to get the job done.

The credentials for accessing your Jenkins should be added and the id needs to be passed in the withCredentials statement, in place of 'JenkinsCredentials'. Feel free to omit that step if your Jenkins doesn't use authentication.

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

Pandas column of lists, create a row for each list element

Trying to work through Roman Pekar's solution step-by-step to understand it better, I came up with my own solution, which uses melt to avoid some of the confusing stacking and index resetting. I can't say that it's obviously a clearer solution though:

items_as_cols = df.apply(lambda x: pd.Series(x['samples']), axis=1)
# Keep original df index as a column so it's retained after melt
items_as_cols['orig_index'] = items_as_cols.index

melted_items = pd.melt(items_as_cols, id_vars='orig_index', 
                       var_name='sample_num', value_name='sample')
melted_items.set_index('orig_index', inplace=True)

df.merge(melted_items, left_index=True, right_index=True)

Output (obviously we can drop the original samples column now):

                 samples  subject  trial_num sample_num  sample
0    [1.84, 1.05, -0.66]        1          1          0    1.84
0    [1.84, 1.05, -0.66]        1          1          1    1.05
0    [1.84, 1.05, -0.66]        1          1          2   -0.66
1    [-0.24, -0.9, 0.65]        1          2          0   -0.24
1    [-0.24, -0.9, 0.65]        1          2          1   -0.90
1    [-0.24, -0.9, 0.65]        1          2          2    0.65
2    [1.15, -0.87, -1.1]        1          3          0    1.15
2    [1.15, -0.87, -1.1]        1          3          1   -0.87
2    [1.15, -0.87, -1.1]        1          3          2   -1.10
3   [-0.8, -0.62, -0.68]        2          1          0   -0.80
3   [-0.8, -0.62, -0.68]        2          1          1   -0.62
3   [-0.8, -0.62, -0.68]        2          1          2   -0.68
4    [0.91, -0.47, 1.43]        2          2          0    0.91
4    [0.91, -0.47, 1.43]        2          2          1   -0.47
4    [0.91, -0.47, 1.43]        2          2          2    1.43
5  [-1.14, -0.24, -0.91]        2          3          0   -1.14
5  [-1.14, -0.24, -0.91]        2          3          1   -0.24
5  [-1.14, -0.24, -0.91]        2          3          2   -0.91

Trust Anchor not found for Android SSL Connection

The error message I was getting was similar but the reason was that the self signed certificate had expired. When the openssl client was attempted, it gave me the reason which was overlooked when I was checking the certificate dialog from firefox.

So in general, if the certificate is there in the keystore and its "VALID", this error will go off.

Convert String array to ArrayList

in most cases the List<String> should be enough. No need to create an ArrayList

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

...

String[] words={"ace","boom","crew","dog","eon"};
List<String> l = Arrays.<String>asList(words);

// if List<String> isnt specific enough:
ArrayList<String> al = new ArrayList<String>(l);

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

If the 2nd company is happy for you to access their content in an IFrame then they need to take the restriction off - they can do this fairly easily in the IIS config.

There's nothing you can do to circumvent it and anything that does work should get patched quickly in a security hotfix. You can't tell the browser to just render the frame if the source content header says not allowed in frames. That would make it easier for session hijacking.

If the content is GET only you don't post data back then you could get the page server side and proxy the content without the header, but then any post back should get invalidated.

Find package name for Android apps to use Intent to launch Market app from web

  1. Go to setting app.
  2. Click Storage & USB.
  3. Click Phone Card.
  4. Click Android.
  5. Click Data.

Now you can find the package names of all the apps that are installed in your phone.

enter image description here

Choosing the default value of an Enum type without having to change values

The default for an enum (in fact, any value type) is 0 -- even if that is not a valid value for that enum. It cannot be changed.

How to Count Duplicates in List with LINQ

You can use "group by" + "orderby". See LINQ 101 for details

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
        group x by x into g
        let count = g.Count()
        orderby count descending
        select new {Value = g.Key, Count = count};
foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

In response to this post (now deleted):

If you have a list of some custom objects then you need to use custom comparer or group by specific property.

Also query can't display result. Show us complete code to get a better help.

Based on your latest update:

You have this line of code:

group xx by xx into g

Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:

Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.

There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.

//Using extension methods
var q = list.GroupBy(x => x.Name)
            .Select(x => new {Count = x.Count(), 
                              Name = x.Key, 
                              ID = x.First().ID})
            .OrderByDescending(x => x.Count);

//Using LINQ
var q = from x in list
        group x by x.Name into g
        let count = g.Count()
        orderby count descending
        select new {Name = g.Key, Count = count, ID = g.First().ID};

foreach (var x in q)
{
    Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}

matching query does not exist Error in Django

try:
    user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
    user = None

I also see you're storing your passwords in plaintext (a big security no-no!). Consider using the built-in auth system instead.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I had a similar problem when opening a dialog with a partial layout in asp.net MVC. I was loading the jquery library on the partial page as well as the main page which was causing this error to come up.

How to pick a new color for each plotted line within a figure in matplotlib?

matplotlib 1.5+

You can use axes.set_prop_cycle (example).

matplotlib 1.0-1.4

You can use axes.set_color_cycle (example).

matplotlib 0.x

You can use Axes.set_default_color_cycle.

Virtualenv Command Not Found

Follow these basic steps to setup the virtual env

sudo pip install virtualenv virtualenvwrapper
sudo rm -rf ~/get-pip.py ~/.cache/pip

we need to update our ~/.bashrc

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

The ~/.bashrc file is simply a shell script that Bash runs whenever you launch a new terminal. You normally use this file to set various configurations. In this case, we are setting an environment variable called WORKON_HOME to point to the directory where our Python virtual environments live. We then load any necessary configurations from virtualenvwrapper .

To update your ~/.bashrc file simply use a standard text editor, nano is likely the easiest to operate. A more simple solution is to use the cat command and avoid editors entirely:

echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.bashrc
echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.bashrc
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc

After editing our ~/.bashrc file, we need to reload the changes:

source ~/.bashrc

Now that we have installed virtualenv and virtualenvwrapper , the next step is to actually create the Python virtual environment — we do this using the mkvirtualenv command.

mkvirtualenv YOURENV

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
metadata:
  name: service-y
  namespace: namespace-a
spec:
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  ports:
  - port: 80

How to compute the sum and average of elements in an array?

There seem to be an endless number of solutions for this but I found this to be concise and elegant.

const numbers = [1,2,3,4];
const count = numbers.length;
const reducer = (adder, value) => (adder + value);
const average = numbers.map(x => x/count).reduce(reducer);
console.log(average); // 2.5

Or more consisely:

const numbers = [1,2,3,4];
const average = numbers.map(x => x/numbers.length).reduce((adder, value) => (adder + value));
console.log(average); // 2.5

Depending on your browser you may need to do explicit function calls because arrow functions are not supported:

const r = function (adder, value) {
        return adder + value;
};
const m = function (x) {
        return x/count;
};
const average = numbers.map(m).reduce(r);
console.log(average); // 2.5

Or:

const average1 = numbers
    .map(function (x) {
        return x/count;
     })
    .reduce(function (adder, value) {
        return adder + value;
});
console.log(average1);

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.


In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

Android file chooser

I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:

My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.

private void startCreation(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.setDataAndType(startDir,
            "vnd.android.cursor.dir/lysesoft.andexplorer.file");
    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_title_background_color",
            getText(R.string.browser_title_background_color));
    intent.putExtra("browser_title_foreground_color",
            getText(R.string.browser_title_foreground_color));
    intent.putExtra("browser_list_background_color",
            getText(R.string.browser_list_background_color));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

    try{
         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
        showInstallResultMessage(R.string.error_install_andexplorer);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }
}

This methos is just pick up a dialog and if user wants install the external application from market

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setMessage(getText(msg_id));
    dialog.setButton(getText(R.string.button_ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    dialog.setButton2(getText(R.string.button_install),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
                    startActivity(intent);
                    finish();
                }
            });
    dialog.show();
}

Remove Primary Key in MySQL

ALTER TABLE `user_customer_permission` MODIFY `id` INT;
ALTER TABLE `user_customer_permission` DROP PRIMARY KEY;

How to use radio on change event?

Simple ES6 (javascript only) solution.

_x000D_
_x000D_
document.forms.demo.bedStatus.forEach(radio => {_x000D_
  radio.addEventListener('change', () => {_x000D_
    alert(`${document.forms.demo.bedStatus.value} Thai Gayo`);_x000D_
  })_x000D_
});
_x000D_
<form name="demo">_x000D_
  <input type="radio" name="bedStatus" value="Allot" checked>Allot_x000D_
  <input type="radio" name="bedStatus" value="Transfer">Transfer_x000D_
</form>
_x000D_
_x000D_
_x000D_

No line-break after a hyphen

IE8/9 render the non-breaking hyphen mentioned in CanSpice's answer longer than a typical hyphen. It is the length of an en-dash instead of a typical hyphen. This display difference was a deal breaker for me.

As I could not use the CSS answer specified by Deb I instead opted to use no break tags.

<nobr>e-mail</nobr>

In addition I found a specific scenario that caused IE8/9 to break on a hyphen.

  • A string contains words separated by non-breaking spaces - &nbsp;
  • Width is limited
  • Contains a dash

IE renders it like this.

Example of hyphen breaking in IE8/9

The following code reproduces the problem pictured above. I had to use a meta tag to force rendering to IE9 as IE10 has fixed the issue. No fiddle because it does not support meta tags.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=9" />
        <meta charset="utf-8"/>
        <style>
            body { padding: 20px; }
            div { width: 300px; border: 1px solid gray; }
        </style>
    </head>
    <body>
        <div>      
            <p>If&nbsp;there&nbsp;is&nbsp;a&nbsp;-&nbsp;and&nbsp;words&nbsp;are&nbsp;separated&nbsp;by&nbsp;the&nbsp;whitespace&nbsp;code&nbsp;&amp;nbsp;&nbsp;then&nbsp;IE&nbsp;will&nbsp;wrap&nbsp;on&nbsp;the&nbsp;dash.</p>
        </div>
    </body>
</html>

How to install and run Typescript locally in npm?

As of npm 5.2.0, once you've installed locally via

npm i typescript --save-dev

...you no longer need an entry in the scripts section of package.json -- you can now run the compiler with npx:

npx tsc

Now you don't have to update your package.json file every time you want to compile with different arguments.

Docker remove <none> TAG images

docker system prune will do the trick, it removes

- all stopped containers
- all networks not used by at least one container
- all dangling images
- all dangling build cache

But use it, with the caution!

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

Here is the solution.

When you are receiving array from your database. and you are storing array data inside a variable but the variable defined as object. This time you will get the error.

I am receiving array from database and I'm stroing that array inside a variable 'bannersliders'. 'bannersliders' type is now 'any' but if you write 'bannersliders' is an object. Like bannersliders:any={}. So this time you are storing array data inside object type variable. So you find that error.

So you have to write variable like 'bannersliders:any;' or 'bannersliders:any=[]'.

Here I am giving an example.

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
bannersliders:any;
  getallbanner(){
    this.bannerService.getallbanner().subscribe(data=>{
      this.bannersliders =data;
   })
  }
_x000D_
_x000D_
_x000D_

How to reload a page after the OK click on the Alert Page

Try this code..

IN PHP Code

echo "<script type='text/javascript'>".
      "alert('Success to add the task to a project.');
       location.reload;".
     "</script>";

IN Javascript

function refresh()
{
    alert("click ok to refresh  page");
    location.reload();
}

Nested Git repositories?

Place your third party libraries in a separate repository and use submodules to associate them with the main project. Here is a walk-through:

http://git-scm.com/book/en/Git-Tools-Submodules

In deciding how to segment a repo I would usually decide based on how often I would modify them. If it is a third-party library and only changes you are making to it is upgrading to a newer version then you should definitely separate it from the main project.

How to "set a breakpoint in malloc_error_break to debug"

In your screenshot, you didn't specify any module: try setting "libsystem_c.dylib"

enter image description here

I did that, and it works : breakpoint stops here (although the stacktrace often rise from some obscure system lib...)

Are querystring parameters secure in HTTPS (HTTP + SSL)?

remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.

http://en.wikipedia.org/wiki/File:IP_stack_connections.svg

that's the long way of saying, "Yes!"

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

How to create string with multiple spaces in JavaScript

You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.

Ex:

var a = '<pre>something        something</pre>';
document.body.innerHTML = a;

Printing all variables value from a class

When accessing the field value, pass the instance rather than null.

Why not use code generation here? Eclipse, for example, will generate a reasoble toString implementation for you.

Efficient evaluation of a function at every cell of a NumPy array

I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.

One can write his own customised ufunc in C, which surely is more efficient, or by invoking np.frompyfunc, which is built-in factory method. After testing, this is more efficient than np.vectorize:

f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post

Where can I find WcfTestClient.exe (part of Visual Studio)

VS 2019 Professional:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\WcfTestClient.exe

VS 2019 Community:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\WcfTestClient.exe

VS 2019 Enterprise:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\WcfTestClient.exe

VS 2017 Community:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\WcfTestClient.exe

VS 2017 Professional:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\WcfTestClient.exe

VS 2017 Enterprise:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\WcfTestClient.exe

VS 2015:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\WcfTestClient.exe

VS 2013:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\WcfTestClient.exe

VS 2012:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WcfTestClient.exe

Default argument values in JavaScript functions

You have to check if the argument is undefined:

function func(a, b) {
    if (a === undefined) a = "default value";
    if (b === undefined) b = "default value";
}

Also note that this question has been answered before.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }
}

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  Statuses,
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  },
  complete: {
    iconType: "check",
    iconColor: "green"
  };

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

Reading the selected value from asp:RadioButtonList using jQuery

I found a simple solution, try this:

var Ocasiao = "";    
$('#ctl00_rdlOcasioesMarcas input').each(function() { if (this.checked) { Ocasiao = this.value } });

Django - what is the difference between render(), render_to_response() and direct_to_template()?

From django docs:

render() is the same as a call to render_to_response() with a context_instance argument that that forces the use of a RequestContext.

direct_to_template is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py. Docs here

How to 'grep' a continuous stream?

you certainly won't succeed with

tail -f /var/log/foo.log |grep --line-buffered string2search

when you use "colortail" as an alias for tail, eg. in bash

alias tail='colortail -n 30'

you can check by type alias if this outputs something like tail isan alias of colortail -n 30. then you have your culprit :)

Solution:

remove the alias with

unalias tail

ensure that you're using the 'real' tail binary by this command

type tail

which should output something like:

tail is /usr/bin/tail

and then you can run your command

tail -f foo.log |grep --line-buffered something

Good luck.

How to remove specific object from ArrayList in Java?

You can use Collections.binarySearch to find the element, then call remove on the returned index.

See the documentation for Collections.binarySearch here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29

This would require the ArrayTest object to have .equals implemented though. You would also need to call Collections.sort to sort the list. Finally, ArrayTest would have to implement the Comparable interface, so that binarySearch would run correctly.

This is the "proper" way to do it in Java. If you are just looking to solve the problem in a quick and dirty fashion, then you can just iterate over the elements and remove the one with the attribute you are looking for.

Batch Files - Error Handling

Python Unittest, Bat process Error Codes:

if __name__ == "__main__":
   test_suite = unittest.TestSuite()
   test_suite.addTest(RunTestCases("test_aggregationCount_001"))
   runner = unittest.TextTestRunner()
   result = runner.run(test_suite)
   # result = unittest.TextTestRunner().run(test_suite)
   if result.wasSuccessful():
       print("############### Test Successful! ###############")
       sys.exit(1)
   else:
       print("############### Test Failed! ###############")
       sys.exit()

Bat codes:

@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
  echo Error found. Waiting here...
  pause
) || (
  echo This time of test is ok.
)
)

What is the perfect counterpart in Python for "while not EOF"

You can use below code snippet to read line by line, till end of file

line = obj.readline()
while(line != ''):

    # Do Something

    line = obj.readline()

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

Java 8 NullPointerException in Collectors.toMap

I have slightly modified Emmanuel Touzery's implementation.

This version;

  • Allows null keys
  • Allows null values
  • Detects duplicate keys (even if they are null) and throws IllegalStateException as in the original JDK implementation.
  • Detects duplicate keys also when the key already mapped to the null value. In other words, separates a mapping with null-value from no-mapping.
public static <T, K, U> Collector<T, ?, Map<K, U>> toMapOfNullables(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
    return Collectors.collectingAndThen(
        Collectors.toList(),
        list -> {
            Map<K, U> map = new LinkedHashMap<>();
            list.forEach(item -> {
                K key = keyMapper.apply(item);
                if (map.containsKey(key)) {
                    throw new IllegalStateException(String.format("Duplicate key %s", key));
                }
                map.put(key, valueMapper.apply(item));
            });
            return map;
        }
    );
}

Unit tests:

@Test
public void toMapOfNullables_WhenHasNullKey() {
    assertEquals(singletonMap(null, "value"),
        Stream.of("ignored").collect(Utils.toMapOfNullables(i -> null, i -> "value"))
    );
}

@Test
public void toMapOfNullables_WhenHasNullValue() {
    assertEquals(singletonMap("key", null),
        Stream.of("ignored").collect(Utils.toMapOfNullables(i -> "key", i -> null))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateNullKeys() {
    assertThrows(new IllegalStateException("Duplicate key null"),
        () -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> null, i -> i))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateKeys_NoneHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateKeys_OneHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(1, null, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateKeys_AllHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(null, null, null).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
    );
}

How to remove the focus from a TextBox in WinForms?

I've found a good alternative! It works best for me, without setting the focus on something else.

Try that:

private void richTextBox_KeyDown(object sender, KeyEventArgs e)
{    
    e.SuppressKeyPress = true;
}

Two div blocks on same line

I think now, the best practice is use display: inline-block;

look like this demo: https://jsfiddle.net/vjLw1z7w/

EDIT (02/2021):

Best practice now may be to using display: flex; flex-wrap: wrap; on div container and flex-basis: XX%; on div

look like this demo: https://jsfiddle.net/42L1emus/1/

Invalid use side-effecting operator Insert within a function

There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

Determining if Swift dictionary contains key and obtaining any of its values

The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.

If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).

if dict.keys.contains(key) {
  // contains key
} else { 
  // does not contain key
}

Confused about UPDLOCK, HOLDLOCK

UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.

Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.

You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.

You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.

Elegant Python function to convert CamelCase to snake_case?

Lightely adapted from https://stackoverflow.com/users/267781/matth who use generators.

def uncamelize(s):
    buff, l = '', []
    for ltr in s:
        if ltr.isupper():
            if buff:
                l.append(buff)
                buff = ''
        buff += ltr
    l.append(buff)
    return '_'.join(l).lower()

Render Content Dynamically from an array map function in React Native

Don't forget to return the mapped array , like:

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })

}

Reference for the map() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

I was able to solve the problem by simply adding <AllowedMethod>HEAD</AllowedMethod> to the CORS policy of the S3 Bucket.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

How to convert a byte array to a hex string in Java?

public static String toHexString(byte[] bytes) {

    StringBuilder sb = new StringBuilder();

    if (bytes != null) 
        for (byte b:bytes) {

            final String hexString = Integer.toHexString(b & 0xff);

            if(hexString.length()==1)
                sb.append('0');

            sb.append(hexString);//.append(' ');
        }

      return sb.toString();//.toUpperCase();
}

How to display a list of images in a ListView in Android?

I'd start with something like this (and if there is something wrong with my code, I'd of course appreciate any comment):

public class ItemsList extends ListActivity {

private ItemsAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.items_list);

    this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
    setListAdapter(this.adapter);
}

private class ItemsAdapter extends ArrayAdapter<Item> {

    private Item[] items;

    public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.items_list_item, null);
        }

        Item it = items[position];
        if (it != null) {
            ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
            if (iv != null) {
                iv.setImageDrawable(it.getImage());
            }
        }

        return v;
    }
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    this.adapter.getItem(position).click(this.getApplicationContext());
}
}

E.g. extending ArrayAdapter with own type of Items (holding information about your pictures) and overriden getView() method, that prepares view for items within list. There is also method add() on ArrayAdapter to add items to the end of the list.

R.layout.items_list is simple layout with ListView

R.layout.items_list_item is layout representing one item in list

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE my SET OFFLINE;

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'
);

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'
);

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;

ALTER DATABASE my SET MULTI_USER;

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

Change header text of columns in a GridView

protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            #region Dynamically Show gridView header From data base
            getAllheaderName();/*To get all Allowences master headerName*/

            TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
            txt_Days.Text = hidMonthsDays.Value;
            #endregion
        }
    }

React Native: Getting the position of an element

You can use onLayout to get the width, height, and relative-to-parent position of a component at the earliest moment that they're available:

<View
  onLayout={event => {
    const layout = event.nativeEvent.layout;
    console.log('height:', layout.height);
    console.log('width:', layout.width);
    console.log('x:', layout.x);
    console.log('y:', layout.y);
  }}
>

Compared to using .measure() as shown in the accepted answer, this has the advantage that you'll never have to fiddle around deferring your .measure() calls with setTimeout to make sure that the measurements are available, but the disadvantage that it doesn't give you offsets relative to the entire page, only ones relative to the element's parent.

How to update cursor limit for ORA-01000: maximum open cursors exceed

RUn the following query to find if you are running spfile or not:

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type" 
       FROM sys.v_$parameter WHERE name = 'spfile';

If the result is "SPFILE", then use the following command:

alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor

if the result is "PFILE", then use the following command:

alter system set open_cursors = 1000 ;

You can read about SPFILE vs PFILE here,

http://www.orafaq.com/node/5

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

Fastest way

public static byte[] GetBytes(string text)
{
    return System.Text.ASCIIEncoding.UTF8.GetBytes(text);
}

EDIT as Makotosan commented this is now the best way:

Encoding.UTF8.GetBytes(text)

Encode String to UTF-8

Use byte[] ptext = String.getBytes("UTF-8"); instead of getBytes(). getBytes() uses so-called "default encoding", which may not be UTF-8.

How to set selected value on select using selectpicker plugin from bootstrap

use this and it's gonna work:

 $('select[name=selValue]').selectpicker('val', 1);

Most efficient way to find smallest of 3 numbers Java?

Let me first repeat what others already said, by quoting from the article "Structured Programming with go to Statements" by Donald Knuth:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.

(emphasis by me)

So if you have identified that a seemingly trivial operation like the computation of the minimum of three numbers is the actual bottleneck (that is, the "critical 3%") in your application, then you may consider optimizing it.

And in this case, this is actually possible: The Math#min(double,double) method in Java has very special semantics:

Returns the smaller of two double values. That is, the result is the value closer to negative infinity. If the arguments have the same value, the result is that same value. If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero.

One can have a look at the implementation, and see that it's actually rather complex:

public static double min(double a, double b) {
    if (a != a)
        return a;   // a is NaN
    if ((a == 0.0d) &&
        (b == 0.0d) &&
        (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) {
        // Raw conversion ok since NaN can't map to -0.0.
        return b;
    }
    return (a <= b) ? a : b;
}

Now, it may be important to point out that this behavior is different from a simple comparison. This can easily be examined with the following example:

public class MinExample
{
    public static void main(String[] args)
    {
        test(0.0, 1.0);
        test(1.0, 0.0);
        test(-0.0, 0.0);
        test(Double.NaN, 1.0);
        test(1.0, Double.NaN);
    }

    private static void test(double a, double b)
    {
        double minA = Math.min(a, b);
        double minB = a < b ? a : b;
        System.out.println("a: "+a);
        System.out.println("b: "+b);
        System.out.println("minA "+minA);
        System.out.println("minB "+minB);
        if (Double.doubleToRawLongBits(minA) !=
            Double.doubleToRawLongBits(minB))
        {
            System.out.println(" -> Different results!");
        }
        System.out.println();
    }
}

However: If the treatment of NaN and positive/negative zero is not relevant for your application, you can replace the solution that is based on Math.min with a solution that is based on a simple comparison, and see whether it makes a difference.

This will, of course, be application dependent. Here is a simple, artificial microbenchmark (to be taken with a grain of salt!)

import java.util.Random;

public class MinPerformance
{
    public static void main(String[] args)
    {
        bench();
    }

    private static void bench()
    {
        int runs = 1000;
        for (int size=10000; size<=100000; size+=10000)
        {
            Random random = new Random(0);
            double data[] = new double[size];
            for (int i=0; i<size; i++)
            {
                data[i] = random.nextDouble();
            }
            benchA(data, runs);
            benchB(data, runs);
        }
    }

    private static void benchA(double data[], int runs)
    {
        long before = System.nanoTime();
        double sum = 0;
        for (int r=0; r<runs; r++)
        {
            for (int i=0; i<data.length-3; i++)
            {
                sum += minA(data[i], data[i+1], data[i+2]);
            }
        }
        long after = System.nanoTime();
        System.out.println("A: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
    }

    private static void benchB(double data[], int runs)
    {
        long before = System.nanoTime();
        double sum = 0;
        for (int r=0; r<runs; r++)
        {
            for (int i=0; i<data.length-3; i++)
            {
                sum += minB(data[i], data[i+1], data[i+2]);
            }
        }
        long after = System.nanoTime();
        System.out.println("B: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
    }

    private static double minA(double a, double b, double c)
    {
        return Math.min(a, Math.min(b, c));
    }

    private static double minB(double a, double b, double c)
    {
        if (a < b)
        {
            if (a < c)
            {
                return a;
            }
            return c;
        }
        if (b < c)
        {
            return b;
        }
        return c;
    }
}

(Disclaimer: Microbenchmarking in Java is an art, and for more reliable results, one should consider using JMH or Caliper).

Running this with JRE 1.8.0_31 may result in something like

....
A: length 90000, time 545.929078, result 2.247805342620906E7
B: length 90000, time 441.999193, result 2.247805342620906E7
A: length 100000, time 608.046928, result 2.5032781001456387E7
B: length 100000, time 493.747898, result 2.5032781001456387E7

This at least suggests that it might be possible to squeeze out a few percent here (again, in a very artifical example).


Analyzing this further, by looking at the hotspot disassembly output created with

java -server -XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation -XX:+PrintAssembly MinPerformance

one can see the optimized versions of both methods, minA and minB.

First, the output for the method that uses Math.min:

Decoding compiled method 0x0000000002992310:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000001c010910} &apos;minA&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;
  # parm0:    xmm0:xmm0   = double
  # parm1:    xmm1:xmm1   = double
  # parm2:    xmm2:xmm2   = double
  #           [sp+0x60]  (sp of caller)
  0x0000000002992480: mov    %eax,-0x6000(%rsp)
  0x0000000002992487: push   %rbp
  0x0000000002992488: sub    $0x50,%rsp
  0x000000000299248c: movabs $0x1c010cd0,%rsi
  0x0000000002992496: mov    0x8(%rsi),%edi
  0x0000000002992499: add    $0x8,%edi
  0x000000000299249c: mov    %edi,0x8(%rsi)
  0x000000000299249f: movabs $0x1c010908,%rsi   ; {metadata({method} {0x000000001c010910} &apos;minA&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;)}
  0x00000000029924a9: and    $0x3ff8,%edi
  0x00000000029924af: cmp    $0x0,%edi
  0x00000000029924b2: je     0x00000000029924e8  ;*dload_0
                        ; - MinPerformance::minA@0 (line 58)

  0x00000000029924b8: vmovsd %xmm0,0x38(%rsp)
  0x00000000029924be: vmovapd %xmm1,%xmm0
  0x00000000029924c2: vmovapd %xmm2,%xmm1       ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)

  0x00000000029924c6: nop
  0x00000000029924c7: callq  0x00000000028c6360  ; OopMap{off=76}
                        ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)
                        ;   {static_call}
  0x00000000029924cc: vmovapd %xmm0,%xmm1       ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)

  0x00000000029924d0: vmovsd 0x38(%rsp),%xmm0   ;*invokestatic min
                        ; - MinPerformance::minA@7 (line 58)

  0x00000000029924d6: nop
  0x00000000029924d7: callq  0x00000000028c6360  ; OopMap{off=92}
                        ;*invokestatic min
                        ; - MinPerformance::minA@7 (line 58)
                        ;   {static_call}
  0x00000000029924dc: add    $0x50,%rsp
  0x00000000029924e0: pop    %rbp
  0x00000000029924e1: test   %eax,-0x27623e7(%rip)        # 0x0000000000230100
                        ;   {poll_return}
  0x00000000029924e7: retq
  0x00000000029924e8: mov    %rsi,0x8(%rsp)
  0x00000000029924ed: movq   $0xffffffffffffffff,(%rsp)
  0x00000000029924f5: callq  0x000000000297e260  ; OopMap{off=122}
                        ;*synchronization entry
                        ; - MinPerformance::minA@-1 (line 58)
                        ;   {runtime_call}
  0x00000000029924fa: jmp    0x00000000029924b8
  0x00000000029924fc: nop
  0x00000000029924fd: nop
  0x00000000029924fe: mov    0x298(%r15),%rax
  0x0000000002992505: movabs $0x0,%r10
  0x000000000299250f: mov    %r10,0x298(%r15)
  0x0000000002992516: movabs $0x0,%r10
  0x0000000002992520: mov    %r10,0x2a0(%r15)
  0x0000000002992527: add    $0x50,%rsp
  0x000000000299252b: pop    %rbp
  0x000000000299252c: jmpq   0x00000000028ec620  ; {runtime_call}
  0x0000000002992531: hlt
  0x0000000002992532: hlt
  0x0000000002992533: hlt
  0x0000000002992534: hlt
  0x0000000002992535: hlt
  0x0000000002992536: hlt
  0x0000000002992537: hlt
  0x0000000002992538: hlt
  0x0000000002992539: hlt
  0x000000000299253a: hlt
  0x000000000299253b: hlt
  0x000000000299253c: hlt
  0x000000000299253d: hlt
  0x000000000299253e: hlt
  0x000000000299253f: hlt
[Stub Code]
  0x0000000002992540: nop                       ;   {no_reloc}
  0x0000000002992541: nop
  0x0000000002992542: nop
  0x0000000002992543: nop
  0x0000000002992544: nop
  0x0000000002992545: movabs $0x0,%rbx          ; {static_stub}
  0x000000000299254f: jmpq   0x000000000299254f  ; {runtime_call}
  0x0000000002992554: nop
  0x0000000002992555: movabs $0x0,%rbx          ; {static_stub}
  0x000000000299255f: jmpq   0x000000000299255f  ; {runtime_call}
[Exception Handler]
  0x0000000002992564: callq  0x000000000297b9e0  ; {runtime_call}
  0x0000000002992569: mov    %rsp,-0x28(%rsp)
  0x000000000299256e: sub    $0x80,%rsp
  0x0000000002992575: mov    %rax,0x78(%rsp)
  0x000000000299257a: mov    %rcx,0x70(%rsp)
  0x000000000299257f: mov    %rdx,0x68(%rsp)
  0x0000000002992584: mov    %rbx,0x60(%rsp)
  0x0000000002992589: mov    %rbp,0x50(%rsp)
  0x000000000299258e: mov    %rsi,0x48(%rsp)
  0x0000000002992593: mov    %rdi,0x40(%rsp)
  0x0000000002992598: mov    %r8,0x38(%rsp)
  0x000000000299259d: mov    %r9,0x30(%rsp)
  0x00000000029925a2: mov    %r10,0x28(%rsp)
  0x00000000029925a7: mov    %r11,0x20(%rsp)
  0x00000000029925ac: mov    %r12,0x18(%rsp)
  0x00000000029925b1: mov    %r13,0x10(%rsp)
  0x00000000029925b6: mov    %r14,0x8(%rsp)
  0x00000000029925bb: mov    %r15,(%rsp)
  0x00000000029925bf: movabs $0x515db148,%rcx   ; {external_word}
  0x00000000029925c9: movabs $0x2992569,%rdx    ; {internal_word}
  0x00000000029925d3: mov    %rsp,%r8
  0x00000000029925d6: and    $0xfffffffffffffff0,%rsp
  0x00000000029925da: callq  0x00000000512a9020  ; {runtime_call}
  0x00000000029925df: hlt
[Deopt Handler Code]
  0x00000000029925e0: movabs $0x29925e0,%r10    ; {section_word}
  0x00000000029925ea: push   %r10
  0x00000000029925ec: jmpq   0x00000000028c7340  ; {runtime_call}
  0x00000000029925f1: hlt
  0x00000000029925f2: hlt
  0x00000000029925f3: hlt
  0x00000000029925f4: hlt
  0x00000000029925f5: hlt
  0x00000000029925f6: hlt
  0x00000000029925f7: hlt

One can see that the treatment of special cases involves some effort - compared to the output that uses simple comparisons, which is rather straightforward:

Decoding compiled method 0x0000000002998790:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000001c0109c0} &apos;minB&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;
  # parm0:    xmm0:xmm0   = double
  # parm1:    xmm1:xmm1   = double
  # parm2:    xmm2:xmm2   = double
  #           [sp+0x20]  (sp of caller)
  0x00000000029988c0: sub    $0x18,%rsp
  0x00000000029988c7: mov    %rbp,0x10(%rsp) ;*synchronization entry
                        ; - MinPerformance::minB@-1 (line 63)

  0x00000000029988cc: vucomisd %xmm0,%xmm1
  0x00000000029988d0: ja     0x00000000029988ee  ;*ifge
                        ; - MinPerformance::minB@3 (line 63)

  0x00000000029988d2: vucomisd %xmm1,%xmm2
  0x00000000029988d6: ja     0x00000000029988de  ;*ifge
                        ; - MinPerformance::minB@22 (line 71)

  0x00000000029988d8: vmovapd %xmm2,%xmm0
  0x00000000029988dc: jmp    0x00000000029988e2
  0x00000000029988de: vmovapd %xmm1,%xmm0 ;*synchronization entry
                        ; - MinPerformance::minB@-1 (line 63)

  0x00000000029988e2: add    $0x10,%rsp
  0x00000000029988e6: pop    %rbp
  0x00000000029988e7: test   %eax,-0x27688ed(%rip)        # 0x0000000000230000
                        ;   {poll_return}
  0x00000000029988ed: retq
  0x00000000029988ee: vucomisd %xmm0,%xmm2
  0x00000000029988f2: ja     0x00000000029988e2  ;*ifge
                        ; - MinPerformance::minB@10 (line 65)

  0x00000000029988f4: vmovapd %xmm2,%xmm0
  0x00000000029988f8: jmp    0x00000000029988e2
  0x00000000029988fa: hlt
  0x00000000029988fb: hlt
  0x00000000029988fc: hlt
  0x00000000029988fd: hlt
  0x00000000029988fe: hlt
  0x00000000029988ff: hlt
[Exception Handler]
[Stub Code]
  0x0000000002998900: jmpq   0x00000000028ec920  ;   {no_reloc}
[Deopt Handler Code]
  0x0000000002998905: callq  0x000000000299890a
  0x000000000299890a: subq   $0x5,(%rsp)
  0x000000000299890f: jmpq   0x00000000028c7340  ; {runtime_call}
  0x0000000002998914: hlt
  0x0000000002998915: hlt
  0x0000000002998916: hlt
  0x0000000002998917: hlt

Whether or not there are cases where such an optimization really makes a difference in an application is hard to tell. But at least, the bottom line is:

  • The Math#min(double,double) method is not the same as a simple comparison, and the treatment of the special cases does not come for free
  • There are cases where the special case treatment that is done by Math#min is not necessary, and then a comparison-based approach may be more efficient
  • As already pointed out in other answers: In most cases, the performance difference will not matter. However, for this particular example, one should probably create a utility method min(double,double,double) anyhow, for better convenience and readability, and then it would be easy to do two runs with the different implementations, and see whether it really affects the performance.

(Side note: The integer type methods, like Math.min(int,int) actually are a simple comparison - so I would expect no difference for these).

How do I set the selected item in a comboBox to match my string using C#?

Please try this way, it works for me:

Combobox1.items[Combobox1.selectedIndex] = "replaced text";

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to use below code when launching the new activity.

startActivity(new Intent(this, newactivity.class));
finish();

JQuery - Set Attribute value

You can add different classes to select, or select by type like this:

$('input[type="checkbox"]').removeAttr("disabled");

How to redirect both stdout and stderr to a file

The simplest syntax to redirect both is:

command &> logfile

If you want to append to the file instead of overwrite:

command &>> logfile

jquery : focus to div is not working

Focus doesn't work on divs by default. But, according to this, you can make it work:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

http://api.jquery.com/focus/

Combine Multiple child rows into one row MYSQL

Here is how you would construct your query for this type of requirement.

select ID,Item_Name,max(Flavor) as Flavor,max(Extra_Cheese) as Extra_Cheese
    from (select i.*,
                    case when o.Option_Number=43 then o.value else null end as Flavor,
                    case when o.Option_Number=44 then o.value else null end as Extra_Cheese
                from Ordered_Item i,Ordered_Options o) a
    group by ID,Item_Name;

You basically "case out" each column using case when, then select the max() for each of those columns using group by for each intended item.

Converting BigDecimal to Integer

Well, you could call BigDecimal.intValue():

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

You can then either explicitly call Integer.valueOf(int) or let auto-boxing do it for you if you're using a sufficiently recent version of Java.

How to remove any URL within a string in Python

import re
s = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/'''
g = re.findall(r'(text\d+)',s)
print ('list',g)
for i in g:
    print (i)

Out

list ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
text1
text2
text3
text4
text5
text6    ?

How to hide reference counts in VS2013?

In VSCode for Mac (0.10.6) I opened "Preferences -> User Settings" and placed the following code in the settings.json file

enter image description here

"editor.referenceInfos": false

enter image description here

User and Workspace Settings

Which port(s) does XMPP use?

According to Wikipedia:

5222 TCP     XMPP client connection (RFC 6120)        Official  
5223 TCP     XMPP client connection over SSL          Unofficial
5269 TCP     XMPP server connection (RFC 6120)        Official
5298 TCP UDP XMPP JEP-0174: Link-Local Messaging /    Official
             XEP-0174: Serverless Messaging
8010 TCP     XMPP File transfers                      Unofficial    

The port numbers are defined in RFC 6120 § 14.7.

Removing double quotes from variables in batch file creates problems with CMD environment

The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files

SET xyz=%~1

Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).

But, This simple tilde syntax will not work for other variables that were not passed in as parameters

For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.

@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows

@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%

Using arrays or std::vectors in C++, what's the performance gap?

If you do not need to dynamically adjust the size, you have the memory overhead of saving the capacity (one pointer/size_t). That's it.

Unable to install pyodbc on Linux

I faced with same issue. For python3.6.8 and ubuntu 16.04 none of above did not help me.

sudo apt-get install python3.6-dev

This solved my problem.

How to run python script on terminal (ubuntu)?

This error:

python: can't open file 'test.py': [Errno 2] No such file or directory

Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)

I must save the file in any specific folder to make it run on terminal?

No, it can be where ever you want. However, if you just say, "test.py", you'll need to be in the directory containing test.py.

Your terminal (actually, the shell in the terminal) has a concept of "Current working directory", which is what directory (folder) it is currently "in".

Thus, if you type something like:

python test.py

test.py needs to be in the current working directory. In Linux, you can change the current working directory with cd. You might want a tutorial if you're new. (Note that the first hit on that search for me is this YouTube video. The author in the video is using a Mac, but both Mac and Linux use bash for a shell, so it should apply to you.)

How do I start/stop IIS Express Server?

to stop IIS manually:

  1. go to start menu
  2. type in IIS

you get a search result for the manager (Internet Information Services (IIS) manager, on the right side of it there are restart/stop/start buttons.

If you don't want IIS to start on startup because its really annoying..:

  1. go to start menu.
  2. click control panel.
  3. click programs.
  4. turn windows features on or off
  5. wait until the list is loaded
  6. search for Internet Information Services (IIS).
  7. uncheck the box.
  8. Wait until it's done with the changes.
  9. restart computer, but then again the info box will tell you to do that anyways (you can leave this for later if you want to).

oh and IIS and xampp basically do the same thing just in a bit different way. ANd if you have Xampp for your projects then its not really all that nessecary to leave it on if you don't ever use it anyways.

line breaks in a textarea

The simple way:

  1. Use this to insert into mysql:

    $msg = $_GET['msgtextarea']; //or POST and my msg field format: text
    $msg = htmlspecialchars($msg, ENT_QUOTES);

  2. And use this for output:

    echo nl2br($br['msg']);

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

This happened with me as well and I believe this has become a common error not only for Django developers but also for Flask as well, so the way I solved this issue was using brew.

  1. brew install mysql
  2. sudo pip install mysql-python

This way every single issue was solved and both frameworks work absolutely fine.

P.S.: For those who use macports (such as myself), this can be an issue as brew works in a different level, my advice is to use brew instead of macports

I hope I could be helpful.

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

How about a workaround? In my case I took the value of the textarea in a jQuery variable, and changed all "<p>&nbsp" to <p class="clear"> and clear class to have certain height and margin, as the following example:

jQuery

tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p>&nbsp/g, '<p class="clear">');

the val is then saved to the database with the new val.

CSS

p.clear{height: 2px; margin-bottom: 3px;}

You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.

Hope that helps!

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

How to change the background colour's opacity in CSS

Use RGBA like this: background-color: rgba(255, 0, 0, .5)

What is the purpose of the "final" keyword in C++11 for functions?

final adds an explicit intent to not have your function overridden, and will cause a compiler error should this be violated:

struct A {
    virtual int foo(); // #1
};
struct B : A {
    int foo();
};

As the code stands, it compiles, and B::foo overrides A::foo. B::foo is also virtual, by the way. However, if we change #1 to virtual int foo() final, then this is a compiler error, and we are not allowed to override A::foo any further in derived classes.

Note that this does not allow us to "reopen" a new hierarchy, i.e. there's no way to make B::foo a new, unrelated function that can be independently at the head of a new virtual hierarchy. Once a function is final, it can never be declared again in any derived class.

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

While I don't know myself, I would certainly hope that #2 is incorrect...I'd like to think that Windows isn't going to AUTOMATICALLY give out my login information (least of all my password!) to any machine, let alone one that isn't part of my trust.

Regardless, have you explored the impersonation architecture? Your code is going to look similar to this:

using (System.Security.Principal.WindowsImpersonationContext context = System.Security.Principal.WindowsIdentity.Impersonate(token))
{
    // Do network operations here

    context.Undo();
}

In this case, the token variable is an IntPtr. In order to get a value for this variable, you'll have to call the unmanaged LogonUser Windows API function. A quick trip to pinvoke.net gives us the following signature:

[System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
    string lpszUsername,
    string lpszDomain,
    string lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    out IntPtr phToken
);

Username, domain, and password should seem fairly obvious. Have a look at the various values that can be passed to dwLogonType and dwLogonProvider to determine the one that best suits your needs.

This code hasn't been tested, as I don't have a second domain here where I can verify, but this should hopefully put you on the right track.

How to search a Git repository by commit message?

To search across all the branches

git log --all --grep='Build 0051'

Once you know which commit you want to get to

git checkout <the commit hash>

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

Store select query's output in one array in postgres

I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)

Set output of a command as a variable (with pipes)

In a batch file I usually create a file in the temp directory and append output from a program, then I call it with a variable-name to set that variable. Like this:

:: Create a set_var.cmd file containing: set %1=
set /p="set %%1="<nul>"%temp%\set_var.cmd"

:: Append output from a command
ipconfig | find "IPv4" >> "%temp%\set_var.cmd"
call "%temp%\set_var.cmd" IPAddress
echo %IPAddress%

Remove the legend on a matplotlib figure

If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df2 = pd.DataFrame(np.random.randn(10, 5))
df2.plot(legend=None)
plt.show()

Callback to a Fragment from a DialogFragment

Kotlin guys here we go!

So the problem we have is that we created an activity, MainActivity, on that activity we created a fragment, FragmentA and now we want to create a dialog fragment on top of FragmentA call it FragmentB. How do we get the results from FragmentB back to FragmentA without going through MainActivity?

Note:

  1. FragmentA is a child fragment of MainActivity. To manage fragments created in FragmentA we will use childFragmentManager which does that!
  2. FragmentA is a parent fragment of FragmentB, to access FragmentA from inside FragmentB we will use parenFragment.

Having said that, inside FragmentA,

class FragmentA : Fragment(), UpdateNameListener {
    override fun onSave(name: String) {
        toast("Running save with $name")
    }

    // call this function somewhere in a clickListener perhaps
    private fun startUpdateNameDialog() {
        FragmentB().show(childFragmentManager, "started name dialog")
    }
}

Here is the dialog fragment FragmentB.

class FragmentB : DialogFragment() {

    private lateinit var listener: UpdateNameListener

    override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            listener = parentFragment as UpdateNameListener
        } catch (e: ClassCastException) {
            throw ClassCastException("$context must implement UpdateNameListener")
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(it)
            val binding = UpdateNameDialogFragmentBinding.inflate(LayoutInflater.from(context))
            binding.btnSave.setOnClickListener {
                val name = binding.name.text.toString()
                listener.onSave(name)
                dismiss()
            }
            builder.setView(binding.root)
            return builder.create()
        } ?: throw IllegalStateException("Activity can not be null")
    }
}

Here is the interface linking the two.

interface UpdateNameListener {
    fun onSave(name: String)
}

That's it.

How can I produce an effect similar to the iOS 7 blur view?

iOS8 answered these questions.

UIVisualEffect

- (instancetype)initWithEffect:(UIVisualEffect *)effect

or Swift:

init(effect effect: UIVisualEffect)

DataGridView AutoFit and Fill

Just change Property from property of control: AutoSizeColumnsMode:Fill

OR By code

dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.Fill;

Callback when CSS3 transition finishes

The accepted answer currently fires twice for animations in Chrome. Presumably this is because it recognizes webkitAnimationEnd as well as animationEnd. The following will definitely only fires once:

/* From Modernizr */
function whichTransitionEvent(){

    var el = document.createElement('fakeelement');
    var transitions = {
        'animation':'animationend',
        'OAnimation':'oAnimationEnd',
        'MSAnimation':'MSAnimationEnd',
        'WebkitAnimation':'webkitAnimationEnd'
    };

    for(var t in transitions){
        if( transitions.hasOwnProperty(t) && el.style[t] !== undefined ){
            return transitions[t];
        }
    }
}

$("#elementToListenTo")
    .on(whichTransitionEvent(),
        function(e){
            console.log('Transition complete!  This is the callback!');
            $(this).off(e);
        });

How to duplicate a git repository? (without forking)

If you are copying to GitHub, you may use the GitHub Importer to do that for you. The original repo can even be from other version control systems.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

It's a table-valued function, but you're using it as a scalar function.

Try:

where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)

But... also consider changing your function into an inline TVF, as it'll perform better.

How to close form

for example, if you want to close a windows form when an action is performed there are two methods to do it

1.To close it directly

Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();

2.We can also hide form without closing it

 private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        Form2 f2 = new Form2();
        int flag = 0;
        string u, p;
        u = textBox1.Text;
        p = textBox2.Text;
        if(u=="username" && p=="pasword")
        {
            flag = 1;
        }
        else
        {
          MessageBox.Show("enter correct details");
        }
        if(flag==1)
        {
            f2.Show();
            this.Hide();
        }

    }

Mapping US zip code to time zone

This will download a yaml file that will map all timezones to an array of their zipcodes:

curl https://gist.githubusercontent.com/anonymous/01bf19b21da3424f6418/raw/0d69a384f55c6f68244ddaa07e0c2272b44cb1de/timezones_to_zipcodes.yml > timezones_to_zipcodes.yml

e.g.

"Eastern Time (US & Canada)" => ["00100", "00101", "00102", "00103", "00104", ...]
"Central Time (US & Canada)" => ["35000", "35001", "35002", "35003", "35004", ...]
etc...

If you prefer the shortened timezones, you can run this one:

curl https://gist.githubusercontent.com/anonymous/4e04970131ca82945080/raw/e85876daf39a823e54d17a79258b170d0a33dac0/timezones_to_zipcodes_short.yml > timezones_to_zipcodes.yml

e.g.

"EDT" => ["00100", "00101", "00102", "00103", "00104", ...]
"CDT" => ["35000", "35001", "35002", "35003", "35004", ...]
etc...

In Jinja2, how do you test if a variable is undefined?

You could also define a variable in a jinja2 template like this:

{% if step is not defined %}
{% set step = 1 %}
{% endif %}

And then You can use it like this:

{% if step == 1 %}
<div class="col-xs-3 bs-wizard-step active">
{% elif step > 1 %}
<div class="col-xs-3 bs-wizard-step complete">
{% else %}
<div class="col-xs-3 bs-wizard-step disabled">
{% endif %}

Otherwise (if You wouldn't use {% set step = 1 %}) the upper code would throw:

UndefinedError: 'step' is undefined

Read file line by line using ifstream in C++

Reading a file line by line in C++ can be done in some different ways.

[Fast] Loop with std::getline()

The simplest approach is to open an std::ifstream and loop using std::getline() calls. The code is clean and easy to understand.

#include <fstream>

std::ifstream file(FILENAME);
if (file.is_open()) {
    std::string line;
    while (std::getline(file, line)) {
        // using printf() in all tests for consistency
        printf("%s", line.c_str());
    }
    file.close();
}

[Fast] Use Boost's file_description_source

Another possibility is to use the Boost library, but the code gets a bit more verbose. The performance is quite similar to the code above (Loop with std::getline()).

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <fcntl.h>

namespace io = boost::iostreams;

void readLineByLineBoost() {
    int fdr = open(FILENAME, O_RDONLY);
    if (fdr >= 0) {
        io::file_descriptor_source fdDevice(fdr, io::file_descriptor_flags::close_handle);
        io::stream <io::file_descriptor_source> in(fdDevice);
        if (fdDevice.is_open()) {
            std::string line;
            while (std::getline(in, line)) {
                // using printf() in all tests for consistency
                printf("%s", line.c_str());
            }
            fdDevice.close();
        }
    }
}

[Fastest] Use C code

If performance is critical for your software, you may consider using the C language. This code can be 4-5 times faster than the C++ versions above, see benchmark below

FILE* fp = fopen(FILENAME, "r");
if (fp == NULL)
    exit(EXIT_FAILURE);

char* line = NULL;
size_t len = 0;
while ((getline(&line, &len, fp)) != -1) {
    // using printf() in all tests for consistency
    printf("%s", line);
}
fclose(fp);
if (line)
    free(line);

Benchmark -- Which one is faster?

I have done some performance benchmarks with the code above and the results are interesting. I have tested the code with ASCII files that contain 100,000 lines, 1,000,000 lines and 10,000,000 lines of text. Each line of text contains 10 words in average. The program is compiled with -O3 optimization and its output is forwarded to /dev/null in order to remove the logging time variable from the measurement. Last, but not least, each piece of code logs each line with the printf() function for consistency.

The results show the time (in ms) that each piece of code took to read the files.

The performance difference between the two C++ approaches is minimal and shouldn't make any difference in practice. The performance of the C code is what makes the benchmark impressive and can be a game changer in terms of speed.

                             10K lines     100K lines     1000K lines
Loop with std::getline()         105ms          894ms          9773ms
Boost code                       106ms          968ms          9561ms
C code                            23ms          243ms          2397ms

enter image description here

How to generate JAXB classes from XSD?

In intellij click .xsd file -> WebServices ->Generate Java code from Xml Schema JAXB then give package path and package name ->ok

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

Facebook Architecture

Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like

  1. Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.

  2. Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.

  3. Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.

  4. HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.

If we go into more detail, then answer to this question go longer. We can understand more from following posts:

  1. How Does Facebook Work?
  2. Data Management, Facebook-style
  3. Facebook database design?
  4. Facebook wall's database structure
  5. Facebook "like" data structure

How to change the background color of a UIButton while it's highlighted?

Try this if you have an image:

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;

or see if showsTouchWhenHighlighted is enough for you.

Python: Continuing to next iteration in outer loop

I think you could do something like this:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

Using getopts to process long and short command line options

The built-in getopts can't do this. There is an external getopt(1) program that can do this, but you only get it on Linux from the util-linux package. It comes with an example script getopt-parse.bash.

There is also a getopts_long written as a shell function.

Cannot lower case button text in android studio

You could set like this

button.setAllCaps(false);

programmatically

How to index into a dictionary?

If you need an ordered dictionary, you can use odict.

How to create timer in angular2

With rxjs 6.2.2 and Angular 6.1.7, I was getting an:

Observable.timer is not a function

error. This was resolved by replacing Observable.timer with timer:

import { timer, Subscription } from 'rxjs';

private myTimerSub: Subscription;    

ngOnInit(){    
    const ti = timer(2000,1000);    
    this.myTimerSub = ti.subscribe(t => {    
        console.log("Tick");    
    });    
}    

ngOnDestroy() {    
    this.myTimerSub.unsubscribe();    
}

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

Pass Method as Parameter using C#

class PersonDB
{
  string[] list = { "John", "Sam", "Dave" };
  public void Process(ProcessPersonDelegate f)
  {
    foreach(string s in list) f(s);
  }
}

The second class is Client, which will use the storage class. It has a Main method that creates an instance of PersonDB, and it calls that object’s Process method with a method that is defined in the Client class.

class Client
{
  static void Main()
  {
    PersonDB p = new PersonDB();
    p.Process(PrintName);
  }
  static void PrintName(string name)
  {
    System.Console.WriteLine(name);
  }
}

Simple way to transpose columns and rows in SQL?

There are several ways that you can transform this data. In your original post, you stated that PIVOT seems too complex for this scenario, but it can be applied very easily using both the UNPIVOT and PIVOT functions in SQL Server.

However, if you do not have access to those functions this can be replicated using UNION ALL to UNPIVOT and then an aggregate function with a CASE statement to PIVOT:

Create Table:

CREATE TABLE yourTable([color] varchar(5), [Paul] int, [John] int, [Tim] int, [Eric] int);

INSERT INTO yourTable
    ([color], [Paul], [John], [Tim], [Eric])
VALUES
    ('Red', 1, 5, 1, 3),
    ('Green', 8, 4, 3, 5),
    ('Blue', 2, 2, 9, 1);

Union All, Aggregate and CASE Version:

select name,
  sum(case when color = 'Red' then value else 0 end) Red,
  sum(case when color = 'Green' then value else 0 end) Green,
  sum(case when color = 'Blue' then value else 0 end) Blue
from
(
  select color, Paul value, 'Paul' name
  from yourTable
  union all
  select color, John value, 'John' name
  from yourTable
  union all
  select color, Tim value, 'Tim' name
  from yourTable
  union all
  select color, Eric value, 'Eric' name
  from yourTable
) src
group by name

See SQL Fiddle with Demo

The UNION ALL performs the UNPIVOT of the data by transforming the columns Paul, John, Tim, Eric into separate rows. Then you apply the aggregate function sum() with the case statement to get the new columns for each color.

Unpivot and Pivot Static Version:

Both the UNPIVOT and PIVOT functions in SQL server make this transformation much easier. If you know all of the values that you want to transform, you can hard-code them into a static version to get the result:

select name, [Red], [Green], [Blue]
from
(
  select color, name, value
  from yourtable
  unpivot
  (
    value for name in (Paul, John, Tim, Eric)
  ) unpiv
) src
pivot
(
  sum(value)
  for color in ([Red], [Green], [Blue])
) piv

See SQL Fiddle with Demo

The inner query with the UNPIVOT performs the same function as the UNION ALL. It takes the list of columns and turns it into rows, the PIVOT then performs the final transformation into columns.

Dynamic Pivot Version:

If you have an unknown number of columns (Paul, John, Tim, Eric in your example) and then an unknown number of colors to transform you can use dynamic sql to generate the list to UNPIVOT and then PIVOT:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('yourtable') and
               C.name <> 'color'
         for xml path('')), 1, 1, '')

select @colsPivot = STUFF((SELECT  ',' 
                      + quotename(color)
                    from yourtable t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query 
  = 'select name, '+@colsPivot+'
      from
      (
        select color, name, value
        from yourtable
        unpivot
        (
          value for name in ('+@colsUnpivot+')
        ) unpiv
      ) src
      pivot
      (
        sum(value)
        for color in ('+@colsPivot+')
      ) piv'

exec(@query)

See SQL Fiddle with Demo

The dynamic version queries both yourtable and then the sys.columns table to generate the list of items to UNPIVOT and PIVOT. This is then added to a query string to be executed. The plus of the dynamic version is if you have a changing list of colors and/or names this will generate the list at run-time.

All three queries will produce the same result:

| NAME | RED | GREEN | BLUE |
-----------------------------
| Eric |   3 |     5 |    1 |
| John |   5 |     4 |    2 |
| Paul |   1 |     8 |    2 |
|  Tim |   1 |     3 |    9 |

MySQL Workbench Dark Theme

Quoting Yoga...

For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/

I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...

/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml

...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.

How to redirect a URL path in IIS?

Here's the config for ISAPI_Rewrite 3:

RewriteBase /

RewriteCond %{HTTP_HOST} ^mysite.org.uk$ [NC]

RewriteRule ^stuff/(.+)$ http://stuff.mysite.org.uk/$1 [NC,R=301,L]

Is it possible to return empty in react render function?

Returning falsy value in the render() function will render nothing. So you can just do

 render() {
    let finalClasses = "" + (this.state.classes || "");
    return !isTimeout && <div>{this.props.children}</div>;
  }

SQL Server add auto increment primary key to existing table

Create a new Table With Different name and same columns, Primary Key and Foreign Key association and link this in your Insert statement of code. For E.g : For EMPLOYEE, replace with EMPLOYEES.

CREATE TABLE EMPLOYEES(

    EmpId        INT NOT NULL IDENTITY(1,1), 
    F_Name       VARCHAR(20) ,
    L_Name       VARCHAR(20) ,
    DOB          DATE ,
    DOJ          DATE ,
    PRIMARY KEY (EmpId),
    DeptId int FOREIGN KEY REFERENCES DEPARTMENT(DeptId),
    DesgId int FOREIGN KEY REFERENCES DESIGNATION(DesgId),
    AddId int FOREIGN KEY REFERENCES ADDRESS(AddId)   
) 

However, you have to either delete the existing EMPLOYEE Table or do some adjustment according to your requirement.

Multiple distinct pages in one HTML file

Twine is an open-source tool for telling interactive, nonlinear stories. It generates a single html with multiples pages. Maybe it is not the right tool for you but it could be useful for someone else looking for something similar.

How do I remove objects from a JavaScript associative array?

While the accepted answer is correct, it is missing the explanation why it works.

First of all, your code should reflect the fact that this is not an array:

var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;

Note that all objects (including Arrays) can be used this way. However, do not expect for standard JavaScript array functions (pop, push, etc.) to work on objects!

As said in accepted answer, you can then use delete to remove the entries from objects:

delete myObject["lastname"]

You should decide which route you wish to take - either use objects (associative arrays / dictionaries) or use arrays (maps). Never mix the two of them.

Get free disk space

Here is a refactored and simplified version of the @sasha_gud answer:

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
        out ulong lpFreeBytesAvailable,
        out ulong lpTotalNumberOfBytes,
        out ulong lpTotalNumberOfFreeBytes);

    public static ulong GetDiskFreeSpace(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            throw new ArgumentNullException("path");
        }

        ulong dummy = 0;

        if (!GetDiskFreeSpaceEx(path, out ulong freeSpace, out dummy, out dummy))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        return freeSpace;
    }