Programs & Examples On #Hookbox

Spark SQL: apply aggregate functions to a list of columns

Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e

f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)

Here is the way to achieve it - though I do not yet know how to add the alias in this case

See the example below - Using Maps

val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))

val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)

val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")

claimRDD2DF1.groupBy("pid").agg(exprs) show false

Is Ruby pass by reference or by value?

Yes but ....

Ruby passes a reference to an object and since everything in ruby is an object, then you could say it's pass by reference.

I don't agree with the postings here claiming it's pass by value, that seems like pedantic, symantic games to me.

However, in effect it "hides" the behaviour because most of the operations ruby provides "out of the box" - for example string operations, produce a copy of the object:

> astringobject = "lowercase"

> bstringobject = astringobject.upcase
> # bstringobject is a new object created by String.upcase

> puts astringobject
lowercase

> puts bstringobject
LOWERCASE

This means that much of the time, the original object is left unchanged giving the appearance that ruby is "pass by value".

Of course when designing your own classes, an understanding of the details of this behaviour is important for both functional behaviour, memory efficiency and performance.

Codeigniter unset session

I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session

How to parse a string in JavaScript?

Use split on string:

var array = coolVar.split(/-/);

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

How to embed a Facebook page's feed into my website

In new page-plugin you can do multiple tabs in your website. The Page plugin lets you easily embed and promote any Facebook Page on your website. Just like on Facebook, your visitors can like and share the Page without leaving your site.

  1. Include the JavaScript SDK on your page once, ideally right after the opening <body> tag.

_x000D_
_x000D_
<div id="fb-root"></div>_x000D_
<script>(function(d, s, id) {_x000D_
  var js, fjs = d.getElementsByTagName(s)[0];_x000D_
  if (d.getElementById(id)) return;_x000D_
  js = d.createElement(s); js.id = id;_x000D_
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId={APP_ID}";_x000D_
  fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));</script>
_x000D_
_x000D_
_x000D_

  1. Place the code for your plugin wherever you want the plugin to appear on your page.

_x000D_
_x000D_
<div class="fb-page" _x000D_
     data-href="https://www.facebook.com/YourPageName" _x000D_
     data-tabs="timeline" _x000D_
     data-small-header="false" _x000D_
     data-adapt-container-width="true" _x000D_
     data-hide-cover="false" _x000D_
     data-show-facepile="true">_x000D_
  <div class="fb-xfbml-parse-ignore">_x000D_
    <blockquote cite="https://www.facebook.com/facebook">_x000D_
      <a href="https://www.facebook.com/facebook">Facebook</a>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also change the following settings:

enter image description here

Also You can now have timeline, events and messages tabs with the new page plugin:

  • Timeline Tab: Will show the most recent posts of your Facebook Page timeline.
  • Events Tab: People can follow your page events and subscribe to events from the plugin.
  • Messages Tab: People can message your page directly from your website. People need to be logged in to use this feature.

_x000D_
_x000D_
<div class="fb-page" _x000D_
  data-tabs="timeline,events,messages"_x000D_
  data-href="https://www.facebook.com/YourPageName"_x000D_
  data-width="380" _x000D_
  data-hide-cover="false">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

You can not add ON DELETE CASCADE to an already existing constraint. You will have to drop and re-create the constraint. The documentation shows that the MODIFY CONSTRAINT clause can only modify the state of a constraint (i-e: ENABLED/DISABLED...).

How to avoid page refresh after button click event in asp.net

if you have some codes in your Page_Load method and you don't want that those execute after button click use if(!IsPostBack) on Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       // put codes here
    }
}

asp:Button is a server control and for send request to server and get response need page refresh. You can use JQuery and Ajax to prevent full Page refresh

AppStore - App status is ready for sale, but not in app store

I thought I will post my answer as I recently got into a similar issue (as of September 2019). The App is free for all users in all countries.

For me, after I received a confirmation email from Apple saying that my app is ready for sale (the email did not mention any 24 hours waiting period), I could not find my App in the App Store.

The link to view the App in the App Store in the iTunes Connect (under the App Information section at the bottom page) was broken.

After reading your comments in this thread, I went to the Pricing and Availability section of the App and edited the pricing plan again to be 0 GBP and start date Today and finish date No Finish Date.

Then, I unchecked the countries the App is available on and checked them all again and hit Save.

The App became immediately available in the App store. The link in the App information section was directing me to the App Store and no longer broken.

I hope this will help anyone who is having similar issues lately (getting a confirmation email that the App is ready for sale but cannot find it in the App Store).

onclick on a image to navigate to another page using Javascript

I'd set up your HTML like so:

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />

Then use the following code:

<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function(event) {
         window.location.href = this.id + '.html';
    };
}
</script>

That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

RichTextBox (WPF) does not have string property "Text"

There was a confusion between RichTextBox in System.Windows.Forms and in System.Windows.Control

I am using the one in the Control as I am using WPF. In there, there is no Text property, and in order to get a text, I should have used this line:

string myText = new TextRange(transcriberArea.Document.ContentStart, transcriberArea.Document.ContentEnd).Text; 

thanks

Euclidean distance of two vectors

As defined on Wikipedia, this should do it.

euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))

There's also the rdist function in the fields package that may be useful. See here.


EDIT: Changed ** operator to ^. Thanks, Gavin.

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

Collections.sort with multiple fields

Here is a full example comparing 2 fields in an object, one String and one int, also using Collator to sort.

public class Test {

    public static void main(String[] args) {

        Collator myCollator;
        myCollator = Collator.getInstance(Locale.US);

        List<Item> items = new ArrayList<Item>();

        items.add(new Item("costrels", 1039737, ""));
        items.add(new Item("Costs", 1570019, ""));
        items.add(new Item("costs", 310831, ""));
        items.add(new Item("costs", 310832, ""));

        Collections.sort(items, new Comparator<Item>() {
            @Override
            public int compare(final Item record1, final Item record2) {
                int c;
                //c = record1.item1.compareTo(record2.item1); //optional comparison without Collator                
                c = myCollator.compare(record1.item1, record2.item1);
                if (c == 0) 
                {
                    return record1.item2 < record2.item2 ? -1
                            :  record1.item2 > record2.item2 ? 1
                            : 0;
                }
                return c;
            }
        });     

        for (Item item : items)
        {
            System.out.println(item.item1);
            System.out.println(item.item2);
        }       

    }

    public static class Item
    {
        public String item1;
        public int item2;
        public String item3;

        public Item(String item1, int item2, String item3)
        {
            this.item1 = item1;
            this.item2 = item2;
            this.item3 = item3;
        }       
    }

}

Output:

costrels 1039737

costs 310831

costs 310832

Costs 1570019

Is it possible to pull just one file in Git?

Yes, here is the process:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status

Background Image for Select (dropdown) does not work in Chrome

select 
{
    -webkit-appearance: none;
}

If you need to you can also add an image that contains the arrow as part of the background.

JQuery window scrolling event?

Try this: http://jsbin.com/axaler/3/edit

$(function(){
  $(window).scroll(function(){
    var aTop = $('.ad').height();
    if($(this).scrollTop()>=aTop){
        alert('header just passed.');
        // instead of alert you can use to show your ad
        // something like $('#footAd').slideup();
    }
  });
});

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

How to disable Google asking permission to regularly check installed apps on my phone?

On Android 6+ follow this path: Settings -> Google -> Security -> Verify Apps Uncheck them all! Now you're good to GO!!!

Button button = findViewById(R.id.button) always resolves to null in Android Studio

R.id.button is not part of R.layout.activity_main. How should the activity find it in the content view?

The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.

Largest and smallest number in an array

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

namespace Array_Small_and_lagest {
    class Program {
        static void Main(string[] args) {
            int[] array = new int[10];
            Console.WriteLine("enter the array elements to b sorted");
            for (int i = 0; i < 10; i++) {
                array[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = array[0];
            foreach (int i in array) {
                if (i < smallest) {
                    smallest = i;    
                }
            }
            int largest = array[9];
            foreach (int i in array) {    
                if (i > largest) {
                    largest = i;    
                }
            }
            Console.WriteLine("the smallest no is {0}", smallest);
            Console.WriteLine("the largest no is {0}", largest);
            Console.Read();        
        }
    }
}

What is the preferred syntax for defining enums in JavaScript?

As of writing, October 2014 - so here is a contemporary solution. Am writing the solution as a Node Module, and have included a test using Mocha and Chai, as well as underscoreJS. You can easily ignore these, and just take the Enum code if preferred.

Seen a lot of posts with overly convoluted libraries etc. The solution to getting enum support in Javascript is so simple it really isn't needed. Here is the code:

File: enums.js

_ = require('underscore');

var _Enum = function () {

   var keys = _.map(arguments, function (value) {
      return value;
   });
   var self = {
      keys: keys
   };
   for (var i = 0; i < arguments.length; i++) {
      self[keys[i]] = i;
   }
   return self;
};

var fileFormatEnum = Object.freeze(_Enum('CSV', 'TSV'));
var encodingEnum = Object.freeze(_Enum('UTF8', 'SHIFT_JIS'));

exports.fileFormatEnum = fileFormatEnum;
exports.encodingEnum = encodingEnum;

And a test to illustrate what it gives you:

file: enumsSpec.js

var chai = require("chai"),
    assert = chai.assert,
    expect = chai.expect,
    should = chai.should(),
    enums = require('./enums'),
    _ = require('underscore');


describe('enums', function () {

    describe('fileFormatEnum', function () {
        it('should return expected fileFormat enum declarations', function () {
            var fileFormatEnum = enums.fileFormatEnum;
            should.exist(fileFormatEnum);
            assert('{"keys":["CSV","TSV"],"CSV":0,"TSV":1}' === JSON.stringify(fileFormatEnum), 'Unexpected format');
            assert('["CSV","TSV"]' === JSON.stringify(fileFormatEnum.keys), 'Unexpected keys format');
        });
    });

    describe('encodingEnum', function () {
        it('should return expected encoding enum declarations', function () {
            var encodingEnum = enums.encodingEnum;
            should.exist(encodingEnum);
            assert('{"keys":["UTF8","SHIFT_JIS"],"UTF8":0,"SHIFT_JIS":1}' === JSON.stringify(encodingEnum), 'Unexpected format');
            assert('["UTF8","SHIFT_JIS"]' === JSON.stringify(encodingEnum.keys), 'Unexpected keys format');
        });
    });

});

As you can see, you get an Enum factory, you can get all the keys simply by calling enum.keys, and you can match the keys themselves to integer constants. And you can reuse the factory with different values, and export those generated Enums using Node's modular approach.

Once again, if you are just a casual user, or in the browser etc, just take the factory part of the code, potentially removing underscore library too if you don't wish to use it in your code.

How to set 777 permission on a particular folder?

777 is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..

You said I am using windows 7. if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.

If you want permission to be set on sub-directories too then usually their is option to set permission recursively use that.

And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes and write the following command

chmod 0777 module_installation/

for recursive

chmod -R 0777 module_installation/

Hope this will help you

Does C# have extension properties?

As @Psyonity mentioned, you can use the conditionalWeakTable to add properties to existing objects. Combined with the dynamic ExpandoObject, you could implement dynamic extension properties in a few lines:

using System.Dynamic;
using System.Runtime.CompilerServices;

namespace ExtensionProperties
{
    /// <summary>
    /// Dynamically associates properies to a random object instance
    /// </summary>
    /// <example>
    /// var jan = new Person("Jan");
    ///
    /// jan.Age = 24; // regular property of the person object;
    /// jan.DynamicProperties().NumberOfDrinkingBuddies = 27; // not originally scoped to the person object;
    ///
    /// if (jan.Age &lt; jan.DynamicProperties().NumberOfDrinkingBuddies)
    /// Console.WriteLine("Jan drinks too much");
    /// </example>
    /// <remarks>
    /// If you get 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' you should reference Microsoft.CSharp
    /// </remarks>
    public static class ObjectExtensions
    {
        ///<summary>Stores extended data for objects</summary>
        private static ConditionalWeakTable<object, object> extendedData = new ConditionalWeakTable<object, object>();

        /// <summary>
        /// Gets a dynamic collection of properties associated with an object instance,
        /// with a lifetime scoped to the lifetime of the object
        /// </summary>
        /// <param name="obj">The object the properties are associated with</param>
        /// <returns>A dynamic collection of properties associated with an object instance.</returns>
        public static dynamic DynamicProperties(this object obj) => extendedData.GetValue(obj, _ => new ExpandoObject());
    }
}

A usage example is in the xml comments:

var jan = new Person("Jan");

jan.Age = 24; // regular property of the person object;
jan.DynamicProperties().NumberOfDrinkingBuddies = 27; // not originally scoped to the person object;

if (jan.Age < jan.DynamicProperties().NumberOfDrinkingBuddies)
{
    Console.WriteLine("Jan drinks too much");
}

jan = null; // NumberOfDrinkingBuddies will also be erased during garbage collection

How to scroll the window using JQuery $.scrollTo() function

Looks like you've got the syntax slightly wrong... I'm assuming based on your code that you're trying to scroll down 100px in 800ms, if so then this works (using scrollTo 1.4.1):

$.scrollTo('+=100px', 800, { axis:'y' });

How to set 24-hours format for date on java?

Try below code

    String dateStr = "Jul 27, 2011 8:35:29 PM";
    DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
    DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
       date = readFormat.parse( dateStr );
    } catch ( ParseException e ) {
        e.printStackTrace();
    }

    String formattedDate = "";
    if( date != null ) {
    formattedDate = writeFormat.format( date );
    }

    System.out.println(formattedDate);

Good Luck!!!

Check for various formats.

What does question mark and dot operator ?. mean in C# 6.0?

It's the null conditional operator. It basically means:

"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.

In other words, it's like this:

string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}

... except that a is only evaluated once.

Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:

FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null

How to check the multiple permission at single request in Android M?

Here i have a simple solution, - (Multiple permission checking)

String[] permissions = new String[]{
  Manifest.permission.WRITE_CALL_LOG,
  Manifest.permission.READ_CALL_LOG,
  Manifest.permission.READ_CONTACTS,
  Manifest.permission.WRITE_CONTACTS}; // Here i used multiple permission check

Then call it in Oncreate

 if (checkPermissions()) { //  permissions  granted.
    getCallDetails();
 }

Finally, copy the below code

private boolean checkPermissions() {
  int result;
  List<String> listPermissionsNeeded = new ArrayList<>();

   for (String p : permissions) {
     result = ContextCompat.checkSelfPermission(getApplicationContext(), p);
     if (result != PackageManager.PERMISSION_GRANTED) {
       listPermissionsNeeded.add(p);
     }
   }

   if (!listPermissionsNeeded.isEmpty()) {
     ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
     return false;
   }
     return true;
}


@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  switch (requestCode) {
    case MULTIPLE_PERMISSIONS: {
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {  // permissions granted.
           getCallDetails(); // Now you call here what ever you want :)
        } else {
             String perStr = "";
               for (String per : permissions) {
                   perStr += "\n" + per;
                }   // permissions list of don't granted permission
              }
            return;
          }
       }
    }

Convert String to Float in Swift

This is how I approached it. I did not want to "cross the bridge", as it has been removed from Xcode 6 beta 5 anyway, quick and dirty:

extension String {

    // converting a string to double
    func toDouble() -> Double? {

        // split the string into components
        var comps = self.componentsSeparatedByString(".")

        // we have nothing
        if comps.count == 0 {
            return nil
        }
        // if there is more than one decimal
        else if comps.count > 2 {
            return nil
        }
        else if comps[0] == "" || comps[1] == "" {
            return nil
        }

        // grab the whole portion
        var whole = 0.0
        // ensure we have a number for the whole
        if let w = comps[0].toInt() {
            whole = Double(w)
        }
        else {
            return nil
        }

        // we only got the whole
        if comps.count == 1 {

            return whole

        }

        // grab the fractional
        var fractional = 0.0
        // ensure we have a number for the fractional
        if let f = comps[1].toInt() {

            // use number of digits to get the power
            var toThePower = Double(countElements(comps[1]))

            // compute the fractional portion
            fractional = Double(f) / pow(10.0, toThePower)

        }
        else {
            return nil
        }

        // return the result
        return whole + fractional
    }

    // converting a string to float
    func toFloat() -> Float? {

        if let val = self.toDouble() {
            return Float(val)
        }
        else {
            return nil
        }

    }

}


// test it out
var str = "78.001"

if let val = str.toFloat() {
    println("Str in float: \(val)")
}
else {
    println("Unable to convert Str to float")
}

// now in double
if let val = str.toDouble() {
    println("Str in double: \(val)")
}
else {
    println("Unable to convert Str to double")
}

How to convert enum value to int?

You'd need to make the enum expose value somehow, e.g.

public enum Tax {
    NONE(0), SALES(10), IMPORT(5);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

...

public int getTaxValue() {
    Tax tax = Tax.NONE; // Or whatever
    return tax.getValue();
}

(I've changed the names to be a bit more conventional and readable, btw.)

This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.

How do I check if file exists in jQuery or pure JavaScript?

Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:

async function isUrlFound(url) {
  try {
    const response = await fetch(url, {
      method: 'HEAD',
      cache: 'no-cache'
    });

    return response.status === 200;

  } catch(error) {
    // console.log(error);
    return false;
  }
}

Then inside your other async scope, you can easily check whether url exist:

const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');

console.log(isValidUrl); // true || false

How to make an executable JAR file?

In Eclipse you can do it simply as follows :

Right click on your Java Project and select Export.

Select Java -> Runnable JAR file -> Next.

Select the Launch Configuration and choose project file as your Main class

Select the Destination folder where you would like to save it and click Finish.

Best Practice: Access form elements by HTML id or name attribute?

Just to add to everything already said, you may access the inputs either with the name or id using preferably the elements property of the Object form, because without it you may get a property of the form named "foo" rather than an HTML element. And according to @Paul D. Waite it's perfectly ok to have both name and id.

_x000D_
_x000D_
var myForm = document.getElementById("myform")_x000D_
console.log(myForm.foo.value) // hey_x000D_
console.log(myForm.foo2.value) // hey_x000D_
//preferable_x000D_
console.log(myForm.elements.foo.value) // hey_x000D_
console.log(myForm.elements.foo2.value) // hey
_x000D_
<form id="myform">_x000D_
  <input type="text" name="foo" id="foo2" value="hey">_x000D_
</form>
_x000D_
_x000D_
_x000D_

According to MDN on the HTMLFormElement.elements page

The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the element. Independently, you can obtain just the number of form controls using the length property.

You can access a particular form control in the returned collection by using either an index or the element's name or id.

How to handle Pop-up in Selenium WebDriver using Java

I found the solution for the above program, which had the goal of signing in to http://rediff.com

public class Handle_popupNAlert
{
    public static void main(String[] args ) throws InterruptedException
    {
        WebDriver driver= new FirefoxDriver(); 
        driver.get("http://www.rediff.com/");
        WebElement sign = driver.findElement(By.xpath("//html/body/div[3]/div[3]/span[4]/span/a"));
        sign.click();

        Set<String> windowId = driver.getWindowHandles();    // get  window id of current window
        Iterator<String> itererator = windowId.iterator();   

        String mainWinID = itererator.next();
        String  newAdwinID = itererator.next();

        driver.switchTo().window(newAdwinID);
        System.out.println(driver.getTitle());
        Thread.sleep(3000);
        driver.close();

        driver.switchTo().window(mainWinID);
        System.out.println(driver.getTitle());
        Thread.sleep(2000);

        WebElement email_id= driver.findElement(By.xpath("//*[@id='c_uname']"));
        email_id.sendKeys("hi");
        Thread.sleep(5000);

        driver.close();
        driver.quit();
    }  
}

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

Reason to Pass a Pointer by Reference in C++?

I have had to use code like this to provide functions to allocate memory to a pointer passed in and return its size because my company "object" to me using the STL

 int iSizeOfArray(int* &piArray) {
    piArray = new int[iNumberOfElements];
    ...
    return iNumberOfElements;
 }

It is not nice, but the pointer must be passed by reference (or use double pointer). If not, memory is allocated to a local copy of the pointer if it is passed by value which results in a memory leak.

can you add HTTPS functionality to a python flask web server?

The top-scoring answer has the right idea, but the API seems to have evolved so that it no longer works as when it was first written, in 2015.

In place of this:

from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')

I used this, with Python 3.7.5:

import ssl
context = ssl.SSLContext()
context.load_cert_chain('fullchain.pem', 'privkey.pem')

and then supplied the SSL context in the Flask.run call as it said:

app.run(…, ssl_context=context)

(My server.crt file is called fullchain.pem and my server.key is called privkey.pem. These files were supplied to me by my LetsEncrypt Certbot.)

How to list all installed packages and their versions in Python?

If you want to get information about your installed python distributions and don't want to use your cmd console or terminal for it, but rather through python code, you can use the following code (tested with python 3.4):

import pip #needed to use the pip functions
for i in pip.get_installed_distributions(local_only=True):
    print(i)

The pip.get_installed_distributions(local_only=True) function-call returns an iterable and because of the for-loop and the print function the elements contained in the iterable are printed out separated by new line characters (\n). The result will (depending on your installed distributions) look something like this:

cycler 0.9.0
decorator 4.0.4
ipykernel 4.1.0
ipython 4.0.0
ipython-genutils 0.1.0
ipywidgets 4.0.3
Jinja2 2.8
jsonschema 2.5.1
jupyter 1.0.0
jupyter-client 4.1.1
#... and so on...

How do I get unique elements in this array?

Have you looked at this page?

http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

That might save you some time?

eg db.addresses.distinct("zip-code");

Visual Studio opens the default browser instead of Internet Explorer

In the Solution Explorer, right-click any ASPX page and select "Browse With" and select IE as the default.

Note... the same steps can be used to add Google Chrome as a browser option and to optionally set it as the default browser.

How to get unique values in an array

Majority of the solutions above have a high run time complexity.

Here is the solution that uses reduce and can do the job in O(n) time.

_x000D_
_x000D_
Array.prototype.unique = Array.prototype.unique || function() {_x000D_
        var arr = [];_x000D_
 this.reduce(function (hash, num) {_x000D_
  if(typeof hash[num] === 'undefined') {_x000D_
   hash[num] = 1; _x000D_
   arr.push(num);_x000D_
  }_x000D_
  return hash;_x000D_
 }, {});_x000D_
 return arr;_x000D_
}_x000D_
    _x000D_
var myArr = [3,1,2,3,3,3];_x000D_
console.log(myArr.unique()); //[3,1,2];
_x000D_
_x000D_
_x000D_

Note:

This solution is not dependent on reduce. The idea is to create an object map and push unique ones into the array.

The requested operation cannot be performed on a file with a user-mapped section open

My issue was also solved by sifting through the Process Explorer. However, the process I had to kill was the MySQL Notifier.exe that was still running after closing all VS and SQL applications.

How to check a string for specific characters?

Quick comparison of timings in response to the post by Abbafei:

import timeit

def func1():
    phrase = 'Lucky Dog'
    return any(i in 'LD' for i in phrase)

def func2():
    phrase = 'Lucky Dog'
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__': 
    func1_time = timeit.timeit(func1, number=100000)
    func2_time = timeit.timeit(func2, number=100000)
    print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))

Output:

Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371

So the code is more compact with any, but faster with the conditional.


EDIT : TL;DR -- For long strings, if-then is still much faster than any!

I decided to compare the timing for a long random string based on some of the valid points raised in the comments:

# Tested in Python 2.7.14

import timeit
from string import ascii_letters
from random import choice

def create_random_string(length=1000):
    random_list = [choice(ascii_letters) for x in range(length)]
    return ''.join(random_list)

def function_using_any(phrase):
    return any(i in 'LD' for i in phrase)

def function_using_if_then(phrase):
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__':
    random_string = create_random_string(length=2000)
    func1_time = timeit.timeit(stmt="function_using_any(random_string)",
                               setup="from __main__ import function_using_any, random_string",
                               number=200000)
    func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
                               setup="from __main__ import function_using_if_then, random_string",
                               number=200000)
    print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))

Output:

Time for function using any: 0.1342546
Time for function using if-then: 0.0201827

If-then is almost an order of magnitude faster than any!

PHP case-insensitive in_array function

I wrote a simple function to check for a insensitive value in an array the code is below.

function:

function in_array_insensitive($needle, $haystack) {
   $needle = strtolower($needle);
   foreach($haystack as $k => $v) {
      $haystack[$k] = strtolower($v);
   }
   return in_array($needle, $haystack);
}

how to use:

$array = array('one', 'two', 'three', 'four');
var_dump(in_array_insensitive('fOUr', $array));

Command failed due to signal: Segmentation fault: 11

You can get this error when the compiler gets too confused about what's going on in your code. I noticed you have a number of what appear to be functions nested within functions. You might try commenting out some of that at a time to see if the error goes away. That way you can zero in on the problem area. You can't use breakpoints because it's a compile time error, not a run time error.

How to determine a Python variable's type?

Do you mean in Python or using ctypes?

In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.

In the second case, you can use type():

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

For more reference on ctypes, an its type, see the official documentation.

Compare two Byte Arrays? (Java)

You can use both Arrays.equals() and MessageDigest.isEqual(). These two methods have some differences though.

MessageDigest.isEqual() is a time-constant comparison method and Arrays.equals() is non time-constant and it may bring some security issues if you use it in a security application.

The details for the difference can be read at Arrays.equals() vs MessageDigest.isEqual()

How to assert greater than using JUnit Assert?

Just how you've done it. assertTrue(boolean) also has an overload assertTrue(String, boolean) where the String is the message in case of failure; you can use that if you want to print that such-and-such wasn't greater than so-and-so.

You could also add hamcrest-all as a dependency to use matchers. See https://code.google.com/p/hamcrest/wiki/Tutorial:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

assertThat("timestamp",
           Long.parseLong(previousTokenValues[1]),
           greaterThan(Long.parseLong(currentTokenValues[1])));

That gives an error like:

java.lang.AssertionError: timestamp
Expected: a value greater than <456L>
     but: <123L> was less than <456L>

Append integer to beginning of list in Python

None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

Why did my Git repo enter a detached HEAD state?

A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

git init
touch Readme.md
git add Readme.md
git commit
git checkout head

which gives

Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme

How to edit the legend entry of a chart in Excel?

Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.

check if file exists on remote host with ssh

I wanted also to check if a remote file exist but with RSH. I have tried the previous solutions but they didn't work with RSH.

Finally, I did I short function which works fine:

function existRemoteFile ()
{
REMOTE=$1
FILE=$2
RESULT=$(rsh -l user $REMOTE  "test -e $FILE && echo \"0\" || echo \"1\"")
if [ $RESULT -eq 0 ]
then
    return 0
else
    return 1
fi
}

What does "javax.naming.NoInitialContextException" mean?

Just read the docs:

This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

This exception can be thrown during any interaction with the InitialContext, not only when the InitialContext is constructed. For example, the implementation of the initial context might lazily retrieve the context only when actual methods are invoked on it. The application should not have any dependency on when the existence of an initial context is determined.

But this is explained much better in the docs for InitialContext

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

So, I was having the same issue, but trying to import Android code via the "Import..." menu. When neither of the above two solutions worked on Eclipse Juno:

  • Eclipse -> File -> Import -> General -> Existing Project Into Workspace (NOTE: NOT 'EXISTING ANDROID PROJECT')

  • (Projects should import correctly, but should have errors. We must now attach the SDK to the project)

  • Right-Click on the project, Properties->Android->Project Build Target Choose the appropriate build target (in doubt, use 4.0.3 in the project is newish, and use 2.2 if the project is oldish)

  • Click OK

Once the project rebuilds, everything should be back in order.

(This was written when Eclipse Indigo was in vogue, and there may be changes as Google updates their tools to cover corner cases.)

Moment.js - tomorrow, today and yesterday

Requirements:

  • When the date is further away, use the standard moment().fromNow() functionality.
  • When the date is closer, show "today", "yesterday", "tomorrow", etc.

Solution:

// call this function, passing-in your date
function dateToFromNowDaily( myDate ) {

    // get from-now for this date
    var fromNow = moment( myDate ).fromNow();

    // ensure the date is displayed with today and yesterday
    return moment( myDate ).calendar( null, {
        // when the date is closer, specify custom values
        lastWeek: '[Last] dddd',
        lastDay:  '[Yesterday]',
        sameDay:  '[Today]',
        nextDay:  '[Tomorrow]',
        nextWeek: 'dddd',
        // when the date is further away, use from-now functionality             
        sameElse: function () {
            return "[" + fromNow + "]";
        }
    });
}

NB: From version 2.14.0, the formats argument to the calendar function can be a callback, see http://momentjs.com/docs/#/displaying/calendar-time/.

Programmatically navigate to another view controller/scene

let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "MyCustomViewController") as! ViewController
let navController = UINavigationController(rootViewController: VC1)
self.present(navController, animated:true, completion: nil)

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

after a few days of wondering, my solution was that I forgot to use @Test annotation before the @BeforeEach

Extracting time from POSIXct

The time_t value for midnight GMT is always divisible by 86400 (24 * 3600). The value for seconds-since-midnight GMT is thus time %% 86400.

The hour in GMT is (time %% 86400) / 3600 and this can be used as the x-axis of the plot:

plot((as.numeric(times) %% 86400)/3600, val)

enter image description here

To adjust for a time zone, adjust the time before taking the modulus, by adding the number of seconds that your time zone is ahead of GMT. For example, US central daylight saving time (CDT) is 5 hours behind GMT. To plot against the time in CDT, the following expression is used:

plot(((as.numeric(times) - 5*3600) %% 86400)/3600, val)

Twitter Bootstrap 3.0 how do I "badge badge-important" now

When using the LESS version you can import mixins.less and create your own classes for colored badges:

.badge-warning {
    .label-variant(@label-warning-bg);
}

Same for the other colors; just replace warning with danger, success, etc.

How to list all properties of a PowerShell object

I like

 Get-WmiObject Win32_computersystem | format-custom *

That seems to expand everything.

There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).

Although most often I use

Get-WmiObject Win32_computersystem | fl *

It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.

Using current time in UTC as default value in PostgreSQL

A function is not even needed. Just put parentheses around the default expression:

create temporary table test(
    id int, 
    ts timestamp without time zone default (now() at time zone 'utc')
);

Checking if object is empty, works with ng-show but not from controller?

Or you could keep it simple by doing something like this:

alert(angular.equals({}, $scope.items));

printf formatting (%d versus %u)

The difference is simple: they cause different warning messages to be emitted when compiling:

1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %d\n", &a); // prints "memory add=-12"
                               ^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %u\n", &a); // prints "memory add=65456"
                               ^

If you pass your pointer as a void* and use %p as the conversion specifier, then you get no error message:

#include <stdio.h>

int main()
{
    int a = 5;
    // check the memory address
    printf("memory address = %d\n", &a); /* wrong */
    printf("memory address = %u\n", &a); /* wrong */
    printf("memory address = %p\n", (void*)&a); /* right */
}

A CSS selector to get last visible div

in other way, you can do it with javascript , in Jquery you can use something like:

$('div:visible').last()

*reedited

How to make the HTML link activated by clicking on the <li>?

I found a easy solution: make the tag " li "be inside the tag " a ":

<a href="#"><li>Something1</li></a>

Displaying the build date

In 2018 some of the above solutions do not work anymore or do not work with .NET Core.

I use the following approach which is simple and works for my .NET Core 2.0 project.

Add the following to your .csproj inside the PropertyGroup :

    <Today>$([System.DateTime]::Now)</Today>

This defines a PropertyFunction which you can access in your pre build command.

Your pre-build looks like this

echo $(today) > $(ProjectDir)BuildTimeStamp.txt

Set the property of the BuildTimeStamp.txt to Embedded resource.

Now you can read the time stamp like this

public static class BuildTimeStamp
    {
        public static string GetTimestamp()
        {
            var assembly = Assembly.GetEntryAssembly(); 

            var stream = assembly.GetManifestResourceStream("NamespaceGoesHere.BuildTimeStamp.txt");

            using (var reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
    }

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

how to get docker-compose to use the latest image from repository

Since 2020-05-07, the docker-compose spec also defines the "pull_policy" property for a service:

version: '3.7'

services:
  my-service:
    image: someimage/somewhere
    pull_policy: always

The docker-compose spec says:

pull_policy defines the decisions Compose implementations will make when it starts to pull images.

Possible values are (tl;dr, check spec for more details):

  • always: always pull
  • never: don't pull (breaks if the image can not be found)
  • missing: pulls if the image is not cached
  • build: always build or rebuild

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

Check last modified date of file in C#

Just use File.GetLastWriteTime. There's a sample on that page showing how to use it.

no module named zlib

For the case I met, I found there are missing modules after make. So I did the following:

  1. install zlib-devel
  2. make and install python again.

How to center and crop an image to always appear in square shape with CSS?

With the caveat of it not working in IE and some older mobile browsers, a simple object-fit: cover; is often the best option.

.cropper {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
}
.cropper img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Without the object-fit: cover support, the image will be stretched oddly to fit the box so, if support for IE is needed, I'd recommend using one of the other answers' approach with -100% top, left, right and bottom values as a fallback.

http://caniuse.com/#feat=object-fit

PHP function ssh2_connect is not working

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road

CSS word-wrapping in div

I'm a little surprised it doesn't just do that. Could there another element inside the div that has a width set to something greater than 250?

Multidimensional Lists in C#

You should use List<Person> or a HashSet<Person>.

Difference between dict.clear() and assigning {} in Python

In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:

python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop

python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

ASP.NET postback with JavaScript

Per Phairoh: Use this in the Page/Component just in case the panel name changes

<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
     </script>

Strings as Primary Keys in SQL Database

Yes, but unless you expect to have millions of rows, not using a string-based key because it's slower is usually "premature optimization." After all, strings are stored as big numbers while numeric keys are usually stored as smaller numbers.

One thing to watch out for, though, is if you have clustered indices on a any key and are doing large numbers of inserts that are non-sequential in the index. Every line written will cause the index to re-write. if you're doing batch inserts, this can really slow the process down.

How do I get a YouTube video thumbnail from the YouTube API?

YouTube is owned by Google and Google likes to have a reasonable number of images for different screen sizes, hence its images are stored in different sizes. Here is an example of how your thumbnail will be like:

Low quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg

Medium quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg

High quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg

Maximum quality thumbnail:

http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I had mistyped the IP address by one digit, which meant it was going to one of my other servers. Very confusing as you get a .NET error page but from the wrong machine!

What is the iOS 5.0 user agent string?

fixed my agent string evaluation by scrubbing the string for LOWERCASE "iphone os 5_0" as opposed to "iPhone OS 5_0." now i am properly assigning iOS 5 specific classes to my html, when the uppercase scrub failed.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I know that I have this problem over and over when I deploy my application on a new server because I'm using this driver to connect to a Excel file. So here it is what I'm doing lately.

There's a Windows Server 2008 R2, I install the Access drivers for a x64 bit machine and I get rid of this message, which makes me very happy just to bump into another.

This one here below works splendidly on my dev machine but on server gives me an error even after installing the latest ODBC drivers, which I think this is the problem, but this is how I solved it.

private const string OledbProviderString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\OlsonWindows.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";

I replace with the new provider like this below:

private const string OledbProviderString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OlsonWindows.xlsx;Extended Properties='Excel 12.0;HDR=YES;';";

But as I do this, there's one thing you should notice. Using the .xlsx file extension and Excel version is 12.0.

After I get into this error message Error: "Could Not Find Installable ISAM", I decide to change the things a little bit like below:

private const string OledbProviderString =      @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OlsonWindows.xls;Extended Properties='Excel 8.0;HDR=YES;';"; 

and yes, I'm done with that nasty thing, but here I got another message The Microsoft Access database engine cannot open or write to the file 'time_zone'. It is already opened exclusively by another user, or you need permission to view and write its data. which tells me I'm not far away from solving it.

Maybe there's another process that opened the file meanwhile and all that I have to do is a restart and all will take start smoothly running as expected.

Using $setValidity inside a Controller

This line:

myForm.file.$setValidity("myForm.file.$error.size", false);

Should be

$scope.myForm.file.$setValidity("size", false);

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

For future reference:

 yyyy => 4 digit year
 MM   => 2 digit month (you must type MM in ALL CAPS)
 dd   => 2 digit "day of the month"

 HH   => 2-digit "hour in day" (0 to 23)
 mm   => 2-digit minute (you must type mm in lowercase)
 ss   => 2-digit seconds
 SSS  => milliseconds

So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"

But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"

The so-called examples at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html show only output. They do not tell you what formats to use!

How can I add numbers in a Bash script?

#!/bin/bash

num=0
metab=0

for ((i=1; i<=2; i++)); do      
    for j in `ls output-$i-*`; do
        echo "$j"

        metab=$(cat $j|grep EndBuffer|awk '{sum+=$2} END { print sum/120}') (line15)
        let num=num+metab (line 16)
    done
    echo "$num"
done

How to check if BigDecimal variable == 0 in java?

Use compareTo(BigDecimal.ZERO) instead of equals():

if (price.compareTo(BigDecimal.ZERO) == 0) // see below

Comparing with the BigDecimal constant BigDecimal.ZERO avoids having to construct a new BigDecimal(0) every execution.

FYI, BigDecimal also has constants BigDecimal.ONE and BigDecimal.TEN for your convenience.


Note!

The reason you can't use BigDecimal#equals() is that it takes scale into consideration:

new BigDecimal("0").equals(BigDecimal.ZERO) // true
new BigDecimal("0.00").equals(BigDecimal.ZERO) // false!

so it's unsuitable for a purely numeric comparison. However, BigDecimal.compareTo() doesn't consider scale when comparing:

new BigDecimal("0").compareTo(BigDecimal.ZERO) == 0 // true
new BigDecimal("0.00").compareTo(BigDecimal.ZERO) == 0 // true

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

For Eclipse users...

Click Run —> Run configuration —> are —> set Alternate JRE for 1.6 or 1.7

How do I create a ListView with rounded corners in Android?

to make border u have to make another xml file with property of solid and corners in the drawable folder and calls it in background

How to declare a type as nullable in TypeScript?

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

sklearn plot confusion matrix with labels

I found a function that can plot the confusion matrix which generated from sklearn.

import numpy as np


def plot_confusion_matrix(cm,
                          target_names,
                          title='Confusion matrix',
                          cmap=None,
                          normalize=True):
    """
    given a sklearn confusion matrix (cm), make a nice plot

    Arguments
    ---------
    cm:           confusion matrix from sklearn.metrics.confusion_matrix

    target_names: given classification classes such as [0, 1, 2]
                  the class names, for example: ['high', 'medium', 'low']

    title:        the text to display at the top of the matrix

    cmap:         the gradient of the values displayed from matplotlib.pyplot.cm
                  see http://matplotlib.org/examples/color/colormaps_reference.html
                  plt.get_cmap('jet') or plt.cm.Blues

    normalize:    If False, plot the raw numbers
                  If True, plot the proportions

    Usage
    -----
    plot_confusion_matrix(cm           = cm,                  # confusion matrix created by
                                                              # sklearn.metrics.confusion_matrix
                          normalize    = True,                # show proportions
                          target_names = y_labels_vals,       # list of names of the classes
                          title        = best_estimator_name) # title of graph

    Citiation
    ---------
    http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html

    """
    import matplotlib.pyplot as plt
    import numpy as np
    import itertools

    accuracy = np.trace(cm) / np.sum(cm).astype('float')
    misclass = 1 - accuracy

    if cmap is None:
        cmap = plt.get_cmap('Blues')

    plt.figure(figsize=(8, 6))
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()

    if target_names is not None:
        tick_marks = np.arange(len(target_names))
        plt.xticks(tick_marks, target_names, rotation=45)
        plt.yticks(tick_marks, target_names)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]


    thresh = cm.max() / 1.5 if normalize else cm.max() / 2
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        if normalize:
            plt.text(j, i, "{:0.4f}".format(cm[i, j]),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")
        else:
            plt.text(j, i, "{:,}".format(cm[i, j]),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")


    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
    plt.show()

It will look like this enter image description here

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Cannot find java. Please use the --jdkhome switch

What worked for me is:

  • make sure java path is available:
$ which java
/usr/bin/java
  • then in etc/netbeans.conf make sure netbeans_jdkhome is commented out
  • in Finder go to /bin/ click on netbeans (terminal icon)

You would expect ./netbeans --jdkhome=/usr/bin/java to work, but it doesn't for some reason.

How do I navigate to a parent route from a child route?

add Location to your constructor from @angular/common

constructor(private _location: Location) {}

add the back function:

back() {
  this._location.back();
}

and then in your view:

<button class="btn" (click)="back()">Back</button>

Application_Start not firing?

If you are using the System.Diagnostics.Debugger.Break(); workaround (which I think is just fine for temporary use) and it's "just not working" on your Windows 8 Machine. The reason is a bug in Visual Studio's "Just in time debugging".

The fix is as follows is to fix the key for the "Visual Studio Just-In-Time Debugger"

Open regedit and go to HKEY_CLASSES_ROOT\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347} for the ‘AppIDFlags’ registry value, set the flag to 0x8

More info here: http://connect.microsoft.com/VisualStudio/feedback/details/770786/just-in-time-debugging-operation-attempted-is-not-supported

Why doesn't Mockito mock static methods?

If you need to mock a static method, it is a strong indicator for a bad design. Usually, you mock the dependency of your class-under-test. If your class-under-test refers to a static method - like java.util.Math#sin for example - it means the class-under-test needs exactly this implementation (of accuracy vs. speed for example). If you want to abstract from a concrete sinus implementation you probably need an Interface (you see where this is going to)?

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

Floating point comparison functions for C#

Here is a much-expanded version of Simon Hewitt's class:

/// <summary>
/// Safely converts a <see cref="float"/> to an <see cref="int"/> for floating-point comparisons.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct FloatToInt : IEquatable<FloatToInt>, IEquatable<float>, IEquatable<int>, IComparable<FloatToInt>, IComparable<float>, IComparable<int>
{
    /// <summary>
    /// Initializes a new instance of the <see cref="FloatToInt"/> class.
    /// </summary>
    /// <param name="floatValue">The <see cref="float"/> value to be converted to an <see cref="int"/>.</param>
    public FloatToInt(float floatValue)
        : this()
    {
        FloatValue = floatValue;
    }

    /// <summary>
    /// Gets the floating-point value as an integer.
    /// </summary>
    [FieldOffset(0)]
    public readonly int IntValue;

    /// <summary>
    /// Gets the floating-point value.
    /// </summary>
    [FieldOffset(0)]
    public readonly float FloatValue;

    /// <summary>
    /// Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <returns>
    /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public bool Equals(FloatToInt other)
    {
        return other.IntValue == IntValue;
    }

    /// <summary>
    /// Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <returns>
    /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public bool Equals(float other)
    {
        return IntValue == new FloatToInt(other).IntValue;
    }

    /// <summary>
    /// Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <returns>
    /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public bool Equals(int other)
    {
        return IntValue == other;
    }

    /// <summary>
    /// Compares the current object with another object of the same type.
    /// </summary>
    /// <returns>
    /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. 
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public int CompareTo(FloatToInt other)
    {
        return IntValue.CompareTo(other.IntValue);
    }

    /// <summary>
    /// Compares the current object with another object of the same type.
    /// </summary>
    /// <returns>
    /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. 
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public int CompareTo(float other)
    {
        return IntValue.CompareTo(new FloatToInt(other).IntValue);
    }

    /// <summary>
    /// Compares the current object with another object of the same type.
    /// </summary>
    /// <returns>
    /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. 
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public int CompareTo(int other)
    {
        return IntValue.CompareTo(other);
    }

    /// <summary>
    /// Indicates whether this instance and a specified object are equal.
    /// </summary>
    /// <returns>
    /// true if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
    /// </returns>
    /// <param name="obj">Another object to compare to. </param><filterpriority>2</filterpriority>
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
        {
            return false;
        }
        if (obj.GetType() != typeof(FloatToInt))
        {
            return false;
        }
        return Equals((FloatToInt)obj);
    }

    /// <summary>
    /// Returns the hash code for this instance.
    /// </summary>
    /// <returns>
    /// A 32-bit signed integer that is the hash code for this instance.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public override int GetHashCode()
    {
        return IntValue;
    }

    /// <summary>
    /// Implicitly converts from a <see cref="FloatToInt"/> to an <see cref="int"/>.
    /// </summary>
    /// <param name="value">A <see cref="FloatToInt"/>.</param>
    /// <returns>An integer representation of the floating-point value.</returns>
    public static implicit operator int(FloatToInt value)
    {
        return value.IntValue;
    }

    /// <summary>
    /// Implicitly converts from a <see cref="FloatToInt"/> to a <see cref="float"/>.
    /// </summary>
    /// <param name="value">A <see cref="FloatToInt"/>.</param>
    /// <returns>The floating-point value.</returns>
    public static implicit operator float(FloatToInt value)
    {
        return value.FloatValue;
    }

    /// <summary>
    /// Determines if two <see cref="FloatToInt"/> instances have the same integer representation.
    /// </summary>
    /// <param name="left">A <see cref="FloatToInt"/>.</param>
    /// <param name="right">A <see cref="FloatToInt"/>.</param>
    /// <returns>true if the two <see cref="FloatToInt"/> have the same integer representation; otherwise, false.</returns>
    public static bool operator ==(FloatToInt left, FloatToInt right)
    {
        return left.IntValue == right.IntValue;
    }

    /// <summary>
    /// Determines if two <see cref="FloatToInt"/> instances have different integer representations.
    /// </summary>
    /// <param name="left">A <see cref="FloatToInt"/>.</param>
    /// <param name="right">A <see cref="FloatToInt"/>.</param>
    /// <returns>true if the two <see cref="FloatToInt"/> have different integer representations; otherwise, false.</returns>
    public static bool operator !=(FloatToInt left, FloatToInt right)
    {
        return !(left == right);
    }
}

TypeError: 'float' object is not subscriptable

You are not selecting multiple indexes with PriceList[0][1][2][3][4][5][6] , instead each [] is going into a sub index.

Try this

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
PriceList[0:7]=[PizzaChange]*7  
PriceList[7:11]=[PizzaChange+3]*4

How to generate .angular-cli.json file in Angular Cli?

You are just outside the directory which you are working. Enter into the directory which your project is there and run command ng g c name.

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

How to print an exception in Python 3?

These are the changes since python 2:

    try:
        1 / 0
    except Exception as e: # (as opposed to except Exception, e:)
                           # ^ that will just look for two classes, Exception and e
        # for the repr
        print(repr(e))
        # for just the message, or str(e), since print calls str under the hood
        print(e)
        # the arguments that the exception has been called with. 
        # the first one is usually the message. (OSError is different, though)
        print(e.args)

You can look into the standard library module traceback for fancier stuff.

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

Adding processData: false to the $.ajax options will fix this issue.

How do I line up 3 divs on the same row?

This is easier and gives purpose to the never used unordered/ordered list tags.

In your CSS add:

    li{float: left;}  //Sets float left property globally for all li tags.

Then add in your HTML:

    <ul>
         <li>1</li>
         <li>2</li>
         <li>3</li>        
    </ul>

Now watch it all line up perfectly! No more arguing over tables vs divs!

How to find if a given key exists in a C++ std::map

If you want to compare pair of map you can use this method:

typedef map<double, double> TestMap;
TestMap testMap;
pair<map<double,double>::iterator,bool> controlMapValues;

controlMapValues= testMap.insert(std::pair<double,double>(x,y));
if (controlMapValues.second == false )
{
    TestMap::iterator it;
    it = testMap.find(x);

    if (it->second == y)
    {
        cout<<"Given value is already exist in Map"<<endl;
    }
}

This is a useful technique.

Remove trailing spaces automatically or with a shortcut

Menu FilePreferenceSettings

Enter image description here

Check the "Trim Trailing Whitespace" option - "When enabled, will trim trailing whitespace when saving a file".

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Use addHeader Instead of using setHeader method,

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains.


For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

Check this blog post.

Java 8 - Difference between Optional.flatMap and Optional.map

Okay. You only need to use 'flatMap' when you're facing nested Optionals. Here's the example.

public class Person {

    private Optional<Car> optionalCar;

    public Optional<Car> getOptionalCar() {
        return optionalCar;
    }
}

public class Car {

    private Optional<Insurance> optionalInsurance;

    public Optional<Insurance> getOptionalInsurance() {
        return optionalInsurance;
    }
}

public class Insurance {

    private String name;

    public String getName() {
        return name;
    }

}

public class Test {

    // map cannot deal with nested Optionals
    public Optional<String> getCarInsuranceName(Person person) {
        return person.getOptionalCar()
                .map(Car::getOptionalInsurance) // ? leads to a Optional<Optional<Insurance>
                .map(Insurance::getName);       // ?
    }

}

Like Stream, Optional#map will return a value wrapped by a Optional. That's why we get a nested Optional -- Optional<Optional<Insurance>. And at ?, we want to map it as an Insurance instance, that's how the tragedy happened. The root is nested Optionals. If we can get the core value regardless the shells, we'll get it done. That's what flatMap does.

public Optional<String> getCarInsuranceName(Person person) {
    return person.getOptionalCar()
                 .flatMap(Car::getOptionalInsurance)
                 .map(Insurance::getName);
}

In the end, I stronly recommed the Java 8 In Action to you if you'd like to study Java8 Systematicly.

How to delete parent element using jQuery

I have stumbled upon this problem for one hour. After an hour, I tried debugging and this helped:

$('.list').on('click', 'span', (e) => {
  $(e.target).parent().remove();
});

HTML:

<ul class="list">
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
</ul>

IntelliJ: Error:java: error: release version 5 not supported

See https://stackoverflow.com/a/12900859/104891.

First of all, set the language level/release versions in pom.xml like that:

<properties>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Maven sets the default to 1.5 otherwise. You will also need to include the maven-compiler-plugin if you haven't already:

<dependency>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.8.1</version>
</dependency>

Also, try to change the Java version in each of these places:

File -> Project structure -> Project -> Project SDK -> 11.

File -> Project structure -> Project -> Project language level -> 11.

File -> Project structure -> Project -> Modules -> -> Sources --> 11

In project -> ctrl + alt + s -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Project bytecode version -> 11

In project -> ctrl + alt + s -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Module -> 1.11.

How to suppress "unused parameter" warnings in C?

In gcc, you can label the parameter with the unused attribute.

This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.

In practice this is accomplished by putting __attribute__ ((unused)) just before the parameter. For example:

void foo(workerid_t workerId) { }

becomes

void foo(__attribute__((unused)) workerid_t workerId) { }

Android: How to enable/disable option menu item on button click?

  @Override
        public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {

                case R.id.item_id:

                       //Your Code....

                        item.setEnabled(false);
                        break;
              }
            return super.onOptionsItemSelected(item);
     }

How to stop the Timer in android?

     CountDownTimer waitTimer;
     waitTimer = new CountDownTimer(60000, 300) {

       public void onTick(long millisUntilFinished) {
          //called every 300 milliseconds, which could be used to
          //send messages or some other action
       }

       public void onFinish() {
          //After 60000 milliseconds (60 sec) finish current 
          //if you would like to execute something when time finishes          
       }
     }.start();

to stop the timer early:

     if(waitTimer != null) {
         waitTimer.cancel();
         waitTimer = null;
     }

jQuery + client-side template = "Syntax error, unrecognized expression"

EugeneXa mentioned it in a comment, but it deserves to be an answer:

var template = $("#modal_template").html().trim();

This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:

var markup = Mustache.render(template, data);
$(markup).appendTo(container);

How to add new line into txt file

Why not do it with one method call:

File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });

which will do the newline for you, and allow you to insert multiple lines at once if you want.

What can be the reasons of connection refused errors?

If you try to open a TCP connection to another host and see the error "Connection refused," it means that

  1. You sent a TCP SYN packet to the other host.
  2. Then you received a TCP RST packet in reply.

RST is a bit on the TCP packet which indicates that the connection should be reset. Usually it means that the other host has received your connection attempt and is actively refusing your TCP connection, but sometimes an intervening firewall may block your TCP SYN packet and send a TCP RST back to you.

See https://tools.ietf.org/html/rfc793 page 69:

SYN-RECEIVED STATE

If the RST bit is set

If this connection was initiated with a passive OPEN (i.e., came from the LISTEN state), then return this connection to LISTEN state and return. The user need not be informed. If this connection was initiated with an active OPEN (i.e., came from SYN-SENT state) then the connection was refused, signal the user "connection refused". In either case, all segments on the retransmission queue should be removed. And in the active OPEN case, enter the CLOSED state and delete the TCB, and return.

Getting each individual digit from a whole integer

//this can be easily understandable for beginners     
int score=12344534;
int div;
for (div = 1; div <= score; div *= 10)
{

}
/*for (div = 1; div <= score; div *= 10); for loop with semicolon or empty body is same*/
while(score>0)
{
    div /= 10;
    printf("%d\n`enter code here`", score / div);
    score %= div;
}

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

In my case when I comment out mirrorlist the error got away but the repo was also not working so I manually point the right baseurl in /etc/yum.repos.d/epel.repo as below

[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://iad.mirror.rackspace.com/epel/7Server/x86_64/
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=http://iad.mirror.rackspace.com/epel/7Server/x86_64/debug/
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=http://iad.mirror.rackspace.com/epel/7Server/SRPMS/
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-source-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

Formatting DataBinder.Eval data

Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.

Mark Up:-

<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>

Code behind:-

Public Function fLabel(ByVal tval) As String
   fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

How can I switch my git repository to a particular commit

To create a new branch (locally):

  • With the commit hash (or part of it)

    git checkout -b new_branch 6e559cb
    
  • or to go back 4 commits from HEAD

    git checkout -b new_branch HEAD~4
    

Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch


For discarding the last three commits, see Lunaryorn's answer below.


For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.

Image comparison - fast algorithm

As cartman pointed out, you can use any kind of hash value for finding exact duplicates.

One starting point for finding close images could be here. This is a tool used by CG companies to check if revamped images are still showing essentially the same scene.

How do I make an asynchronous GET request in PHP?

This is how to make Marquis' answer work with both POST and GET requests:

  // $type must equal 'GET' or 'POST'
  function curl_request_async($url, $params, $type='POST')
  {
      foreach ($params as $key => &$val) {
        if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);
      }
      $post_string = implode('&', $post_params);

      $parts=parse_url($url);

      $fp = fsockopen($parts['host'],
          isset($parts['port'])?$parts['port']:80,
          $errno, $errstr, 30);

      // Data goes in the path for a GET request
      if('GET' == $type) $parts['path'] .= '?'.$post_string;

      $out = "$type ".$parts['path']." HTTP/1.1\r\n";
      $out.= "Host: ".$parts['host']."\r\n";
      $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
      $out.= "Content-Length: ".strlen($post_string)."\r\n";
      $out.= "Connection: Close\r\n\r\n";
      // Data goes in the request body for a POST request
      if ('POST' == $type && isset($post_string)) $out.= $post_string;

      fwrite($fp, $out);
      fclose($fp);
  }

How can I pad an int with leading zeros when using cout << operator?

Another example to output date and time using zero as a fill character on instances of single digit values: 2017-06-04 18:13:02

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int main()
{
    time_t t = time(0);   // Get time now
    struct tm * now = localtime(&t);
    cout.fill('0');
    cout << (now->tm_year + 1900) << '-'
        << setw(2) << (now->tm_mon + 1) << '-'
        << setw(2) << now->tm_mday << ' '
        << setw(2) << now->tm_hour << ':'
        << setw(2) << now->tm_min << ':'
        << setw(2) << now->tm_sec
        << endl;
    return 0;
}

iterrows pandas get next rows value

There is a pairwise() function example in the itertools document:

from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])

for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
    print i1, i2, row1["value"], row2["value"]

Here is the output:

0 1 AA BB
1 2 BB CC

But, I think iter rows in a DataFrame is slow, if you can explain what's the problem you want to solve, maybe I can suggest some better method.

Initialize Array of Objects using NSArray

This way you can Create NSArray, NSMutableArray.

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

How to implement my very own URI scheme on Android

Complementing the @DanielLew answer, to get the values of the parameteres you have to do this:

URI example: myapp://path/to/what/i/want?keyOne=valueOne&keyTwo=valueTwo

in your activity:

Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  Uri uri = intent.getData();
  String valueOne = uri.getQueryParameter("keyOne");
  String valueTwo = uri.getQueryParameter("keyTwo");
}

How to access the contents of a vector from a pointer to the vector in C++?

vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};

ptr = &numbers;

for(auto num: *ptr){
 cout << num << endl;
}


cout << (*ptr).at(2) << endl; // 20

cout << "-------" << endl;

cout << ptr -> at(2) << endl; // 20

How to run composer from anywhere?

Just move it to /usr/local/bin folder and remove the extension

sudo mv composer.phar /usr/local/bin/composer

Graph implementation C++

Here is a basic implementation of a graph. Note: I use vertex which is chained to next vertex. And each vertex has a list pointing to adjacent nodes.

#include <iostream>
using namespace std;


// 1 ->2 
// 1->4
// 2 ->3
// 4->3
// 4 -> 5
// Adjacency list
// 1->2->3-null
// 2->3->null
//4->5->null;

// Structure of a vertex
struct vertex {
   int i;
   struct node *list;
   struct vertex *next;
};
typedef struct vertex * VPTR;

// Struct of adjacency list
struct node {
    struct vertex * n;
    struct node *next;
};

typedef struct node * NODEPTR;

class Graph {
    public:
        // list of nodes chained together
        VPTR V;
        Graph() {
            V = NULL;
        }
        void addEdge(int, int);
        VPTR  addVertex(int);
        VPTR existVertex(int i);
        void listVertex();
};

// If vertex exist, it returns its pointer else returns NULL
VPTR Graph::existVertex(int i) {
    VPTR temp  = V;
    while(temp != NULL) {
        if(temp->i == i) {
            return temp;
        }
        temp = temp->next;
    }
   return NULL;
}
// Add a new vertex to the end of the vertex list
VPTR Graph::addVertex(int i) {
    VPTR temp = new(struct vertex);
    temp->list = NULL;
    temp->i = i;
    temp->next = NULL;

    VPTR *curr = &V;
    while(*curr) {
        curr = &(*curr)->next;
    }
    *curr = temp;
    return temp;
}

// Add a node from vertex i to j. 
// first check if i and j exists. If not first add the vertex
// and then add entry of j into adjacency list of i
void Graph::addEdge(int i, int j) {

    VPTR v_i = existVertex(i);   
    VPTR v_j = existVertex(j);   
    if(v_i == NULL) {
        v_i = addVertex(i);
    }
    if(v_j == NULL) {
        v_j = addVertex(j);
    }

    NODEPTR *temp = &(v_i->list);
    while(*temp) {
        temp = &(*temp)->next;
    }
    *temp = new(struct node);
    (*temp)->n = v_j;
    (*temp)->next = NULL;
}
// List all the vertex.
void Graph::listVertex() {
    VPTR temp = V;
    while(temp) {
        cout <<temp->i <<" ";
        temp = temp->next;
    }
    cout <<"\n";

}

// Client program
int main() {
    Graph G;
    G.addEdge(1, 2);
    G.listVertex();

}

With the above code, you can expand to do DFS/BFS etc.

How do I change the text of a span element using JavaScript?

In addition to the pure javascript answers above, You can use jQuery text method as following:

$('#myspan').text('newtext');

If you need to extend the answer to get/change html content of a span or div elements, you can do this:

$('#mydiv').html('<strong>new text</strong>');

References:

.text(): http://api.jquery.com/text/

.html(): http://api.jquery.com/html/

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

How to reverse a singly linked list using only two pointers?

#include <stdio.h>
#include <malloc.h>

tydef struct node
{
    int info;
    struct node *link;
} *start;

void main()
{
    rev();
}

void rev()
{
    struct node *p = start, *q = NULL, *r;
    while (p != NULL)
    {
        r = q;
        q = p;
        p = p->link;
        q->link = r;
    }

    start = q;
}

SQL Server Regular expressions in T-SQL

There is some basic pattern matching available through using LIKE, where % matches any number and combination of characters, _ matches any one character, and [abc] could match a, b, or c... There is more info on the MSDN site.

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I don't think the problem is the dependencies. I guess you are getting that error on your IDE. Then just refresh it. If it's eclipse, try running Maven->Update Dependencies

SCRIPT438: Object doesn't support property or method IE

I forgot to use var on my item variable

Incorrect code:

var itemCreateInfo = new SP.ListItemCreationInformation();
item = list.addItem(itemCreateInfo); 
item.set_item('Title', 'Haytham - Oil Eng'); 

Correct code:

var itemCreateInfo = new SP.ListItemCreationInformation();
var item = list.addItem(itemCreateInfo);  
item.set_item('Title', 'Haytham - Oil Eng');

Android Bitmap to Base64 String

The problem with jeet's answer is that you load all bytes of the image into a byte array, which will likely crash the app in low-end devices. Instead, I would first write the image to a file and read it using Apache's Base64InputStream class. Then you can create the Base64 string directly from the InputStream of that file. It will look like this:

//Don't forget the manifest permission to write files
final FileOutputStream fos = new FileOutputStream(yourFileHere); 
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

fos.close();

final InputStream is = new Base64InputStream( new FileInputStream(yourFileHere) );

//Now that we have the InputStream, we can read it and put it into the String
final StringWriter writer = new StringWriter();
IOUtils.copy(is , writer, encoding);
final String yourBase64String = writer.toString();

As you can see, the above solution works directly with streams instead, avoiding the need to load all the bytes into a variable, therefore making the memory footprint much lower and less likely to crash in low-end devices. There is still the problem that putting the Base64 string itself into a String variable is not a good idea, because, again, it might cause OutOfMemory errors. But at least we have cut the memory consumption by half by eliminating the byte array.

If you want to skip the write-to-a-file step, you have to convert the OutputStream to an InputStream, which is not so straightforward to do (you must use PipedInputStream but that is a little more complex as the two streams must always be in different threads).

How to merge every two lines into one from the command line?

Another solutions using vim (just for reference).

Solution 1:

Open file in vim vim filename, then execute command :% normal Jj

This command is very easy to understand:

  • % : for all the lines,
  • normal : execute normal command
  • Jj : execute Join command, then jump to below line

After that, save the file and exit with :wq

Solution 2:

Execute the command in shell, vim -c ":% normal Jj" filename, then save the file and exit with :wq.

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Android emulator shows nothing except black screen and adb devices shows "device offline"

The Problems associated with the Black window of the emulator:

Happens when a new windows is installed. Problem associated with graphics of the windows is on the CD of windows .You have to Update windows and follow the following steps.

If Emulated Performance Graphics is (Software GLES then select it to-->Automatic)

Or If Emulated Performance Graphics is (Automatic then select it to-->Software GLES)

this alternation can solve this problem.

php.ini & SMTP= - how do you pass username & password

PHP does have authentication on the mail-command!

The following is working for me on WAMPSERVER (windows, php 5.2.17)

php.ini

[mail function]
; For Win32 only.
SMTP = mail.yourserver.com
smtp_port = 25
auth_username = smtp-username
auth_password = smtp-password
sendmail_from = [email protected]

Total Number of Row Resultset getRow Method

The getRow() method retrieves the current row number, not the number of rows. So before starting to iterate over the ResultSet, getRow() returns 0.

To get the actual number of rows returned after executing your query, there is no free method: you are supposed to iterate over it.

Yet, if you really need to retrieve the total number of rows before processing them, you can:

  1. ResultSet.last()
  2. ResultSet.getRow() to get the total number of rows
  3. ResultSet.beforeFirst()
  4. Process the ResultSet normally

How can I see the size of files and directories in linux?

I'm a Ubuntu 16.04 user myself and I find that the ll command is by far the easiest way to see a directory's contents. I've noticed that not all Linux distributions support this command, but there's probably a workaround/install for each distro out there.

Example:

user@user-XPS-15-9560:/$ ll
total 188
drwxr-xr-x  27 root root  4096 Jan 26 09:13 ./
drwxr-xr-x  27 root root  4096 Jan 26 09:13 ../
drwxr-xr-x   2 root root  4096 Jan 22 15:13 bin/
drwxr-xr-x   4 root root 12288 Jan 29 11:35 boot/
drwxr-xr-x   2 root root  4096 Sep  3 18:14 cdrom/
drwxr-xr-x  20 root root  4440 Feb  5 08:43 dev/
drwxr-xr-x 153 root root 12288 Feb  2 15:17 etc/
drwxr-xr-x   4 root root  4096 Sep  3 18:15 home/
...

The biggest advantage for me is that it's quick and really intuitive to use.

UPDATE: what I didn't know was that on Ubuntu it's a pre-configured alias. You can easily set it yourself by executing alias ll="ls -la" on the command line, or by adding this entry in your .bashrc config file:

sudo nano ~/.bashrc
...add line described above and save file by pressing Ctrl+X and Y...
source ~/.bashrc

Accessing Google Spreadsheets with C# using Google Data API

I wrote a simple wrapper around Google's .Net client library, it exposes a simpler database-like interface, with strongly-typed record types. Here's some sample code:

public class Entity {
    public int IntProp { get; set; }
    public string StringProp { get; set; }
}

var e1 = new Entity { IntProp = 2 };
var e2 = new Entity { StringProp = "hello" };
var client = new DatabaseClient("[email protected]", "password");
const string dbName = "IntegrationTests";
Console.WriteLine("Opening or creating database");
db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName); // databases are spreadsheets
const string tableName = "IntegrationTests";
Console.WriteLine("Opening or creating table");
table = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName); // tables are worksheets
table.DeleteAll();
table.Add(e1);
table.Add(e2);
var r1 = table.Get(1);

There's also a LINQ provider that translates to google's structured query operators:

var q = from r in table.AsQueryable()
        where r.IntProp > -1000 && r.StringProp == "hello"
        orderby r.IntProp
        select r;

How to find which columns contain any NaN value in Pandas dataframe

df.isna() return True values for NaN, False for the rest. So, doing:

df.isna().any()

will return True for any column having a NaN, False for the rest

Avoid web.config inheritance in child web application using inheritInChildApplications

If (as I understand) you're trying to completely block inheritance in the web config of your child application, I suggest you to avoid using the tag in web.config. Instead create a new apppool and edit the applicationHost.config file (located in %WINDIR%\System32\inetsrv\Config and %WINDIR%\SysWOW64\inetsrv\config). You just have to find the entry for your apppool and add the attribute enableConfigurationOverride="false" like in the following example:

<add name="MyAppPool" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" enableConfigurationOverride="false">
    <processModel identityType="NetworkService" />
</add>

This will avoid configuration inheritance in the applications served by MyAppPool.

Matteo

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

Groovy method with optional parameters

You can use arguments with default values.

def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".

Find duplicate characters in a String and count the number of occurances using Java

public static void main(String[] args) {
        char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
        char[][] countArr = new char[array.length][2];
        int lastIndex = 0;
        for (char c : array) {
            int foundIndex = -1;
            for (int i = 0; i < lastIndex; i++) {
                if (countArr[i][0] == c) {
                    foundIndex = i;
                    break;
                }
            }
            if (foundIndex >= 0) {
                int a = countArr[foundIndex][1];
                countArr[foundIndex][1] = (char) ++a;
            } else {
                countArr[lastIndex][0] = c;
                countArr[lastIndex][1] = '1';
                lastIndex++;
            }
        }
        for (int i = 0; i < lastIndex; i++) {
            System.out.println(countArr[i][0] + " " + countArr[i][1]);
        }
    }

How to name Dockerfiles

Dockerfile (custom name and folder):

   docker/app.Dockerfile
   docker/nginx.Dockerfile

Build:

   docker build  -f ./docker/app.Dockerfile .
   docker build  -f ./docker/nginx.Dockerfile .

Root user/sudo equivalent in Cygwin?

Use this to get an admin window with either bash or cmd running, from any directories context menue. Just right click on a directory name, and select the entry or hit the highlited button.

This is based on the chere tool and the unfortunately not working answer (for me) from link_boy. It works fine for me using Windows 8,

A side effect is the different color in the admin cmd window. To use this on bash, you can change the .bashrc file of the admin user.

I coudln't get the "background" version (right click into an open directory) to run. Feel free to add it.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash]
@="&Bash Prompt Here"
"Icon"="C:\\cygwin\\Cygwin.ico"

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash\command]
@="C:\\cygwin\\bin\\bash -c \"/bin/xhere /bin/bash.exe '%L'\""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash_root]
@="&Root Bash Prompt Here"
"Icon"="C:\\cygwin\\Cygwin.ico"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash_root\command]
@="runas /savecred /user:administrator \"C:\\cygwin\\bin\\bash -c \\\"/bin/xhere /bin/bash.exe '%L'\\\"\""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd]
@="&Command Prompt Here"

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd\command]
@="cmd.exe /k cd %L"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd_root]
@="Roo&t Command Prompt Here"
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\Directory\shell\cygwin_cmd_root\command]
@="runas /savecred /user:administrator \"cmd.exe /t:1E /k cd %L\""

Python Matplotlib Y-Axis ticks on Right Side of Plot

Use ax.yaxis.tick_right()

for example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

enter image description here

Convert utf8-characters to iso-88591 and back in PHP

function parseUtf8ToIso88591(&$string){
     if(!is_null($string)){
            $iso88591_1 = utf8_decode($string);
            $iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $string);
            $string = mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8');       
     }
}

Eclipse "Invalid Project Description" when creating new project from existing source

I have struggled with this issue myself for a while and I think the reason it happens is because (for Android) there are two ways to import projects into the workspace

1) File>Import>General>Existing Project into Workspace
2) File>Import>Android>Existing Code into Workspace

The errors described here are related to method 2).

For method 1) there will be no overlap problems as long as you uncheck the "Copy Projects into Workspace" box if the project is already in the workspace.

Edit: There is a third method that wasn't in my original post.

3) File >New>Other>Android>Existing Android Project into Workspace

MySQL Multiple Joins in one query?

Multi joins in SQL work by progressively creating derived tables one after the other. See this link explaining the process:

https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

Check if a number is odd or even in python

Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:

if x & 1:
    return 'odd'
else:
    return 'even'

Using Bitwise AND operator

  • The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
  • If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.

Vim for Windows - What do I type to save and exit from a file?

  • Press i or a to get into insert mode, and type the message of choice

  • Press ESC several times to get out of insert mode, or any other mode you might have run into by accident

    • to save, :wq, :x or ZZ

    • to exit without saving, :q! or ZQ

To reload a file and undo all changes you have made...:

Press several times ESC and then enter :e!.

Index (zero based) must be greater than or equal to zero

String.Format must start with zero index "{0}" like this:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Ruby value of a hash key?

As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch instead of []. For fetch not to throw an exception when the key is not found, pass it a default value.

puts "ok" if hash.fetch('key', nil) == 'X'

Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .

How to parse a CSV in a Bash script?

A sed or awk solution would probably be shorter, but here's one for Perl:

perl -F/,/ -ane 'print if $F[<INDEX>] eq "<VALUE>"`

where <INDEX> is 0-based (0 for first column, 1 for 2nd column, etc.)

Comparing results with today's date?

You can try this sql code;

   SELECT [column_1], [column_1], ...    
    FROM (your_table)
     where date_format(record_date, '%e%c%Y') = date_format(now(), '%e%c%Y') 

Adobe Reader Command Line Reference

Call this after the print job has returned:

oShell.AppActivate "Adobe Reader"
oShell.SendKeys "%FX"

Xcode 6.1 Missing required architecture X86_64 in file

If you are building a universal library and need to support the Simulator (x86_64) then build the framework for all platforms by setting Build Active Architecture Only to No. enter image description here

Installing Oracle Instant Client

The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?

1) Download instantclient (http://www.oracle.com/technetwork/topics/winsoft-085727.html)

2) Unzip the ZIP file (eg c:\oracle\instantclient).

3) Include the above path in the PATH. Set PATH in Windows

4) Create the registry key:

  • Windows 32bit: [HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE]
  • Windows 64bit: [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]

5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:

  • Windows 32bit: [HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_INSTANTCLIENT]
  • Windows 64bit: [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE\KEY_INSTANTCLIENT]

6) Now create at least three string values ??in the above key:

registry keys for Oracle Home

For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":

Displays the message "Home is valid." in Quest Toad (or SQL Navigator)

The registry keys are now displayed for selecting the oracle client:

selecting the oracle client in Quest SQL Navigator

Round up double to 2 decimal places

@Rounded, A swift 5.1 property wrapper Example :

struct GameResult {
    @Rounded(rule: NSDecimalNumber.RoundingMode.up,scale: 4)
    var score: Decimal
}

var result = GameResult()
result.score = 3.14159265358979
print(result.score) // 3.1416

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

SQL Server: Is it possible to insert into two tables at the same time?

//if you want to insert the same as first table

$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";

$result = @mysql_query($qry);

$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";

$result = @mysql_query($qry2);

//or if you want to insert certain parts of table one

 $qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";


  $result = @mysql_query($qry);

 $qry2 = "INSERT INTO table2 (two) VALUES('$two')";

 $result = @mysql_query($qry2);

//i know it looks too good to be right, but it works and you can keep adding query's just change the

    "$qry"-number and number in @mysql_query($qry"")

I have 17 tables this has worked in.

git: Your branch is ahead by X commits

Then when I do a git status it tells me that my branch is ahead by X commits (presumably the same number of commits that I have made).

My experience is in a team environment with many branches. We work in our own feature branches (in local clones) and it was one of those that git status showed I was 11 commits ahead. My working assumption, like the question's author, was that +11 was from commits of my own.

It turned out that I had pulled in changes from the common develop branch into my feature branch many weeks earlier -- but forgot! When I revisited my local feature branch today and did a git pull origin develop the number jumped to +41 commits ahead. Much work had been done in develop and so my local feature branch was even further ahead of the feature branch on the origin repository.

So, if you get this message, think back to any pulls/merges you might have done from other branches (of your own, or others) you have access to. The message just signals you need to git push those pulled changes back to the origin repo ('tracking branch') from your local repo to get things sync'd up.

SQL query to find third highest salary in company

for oracle it goes like this:

select salary from employee where rownnum<=3 order by salary desc
minus
select salary from employee where rownnum<=2 order by salary desc;

Optional Parameters in Web Api Attribute Routing

Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:

[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]

The ? character is put always before the last } character

For more information see: Optional URI Parameters and Default Values

Can you 'exit' a loop in PHP?

As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.

For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.

$person = "Rasmus Lerdorf";
$found = false;

foreach($organization as $oKey=>$department)
{
   foreach($department as $dKey=>$group)
   {
      foreach($group as $gKey=>$employee)
      {
         if ($employee['fullname'] == $person)
         {
            $found = true;
            break 3;
         }
      } // group
   } // department
} // organization

How to call loading function with React useEffect only once

function useOnceCall(cb, condition = true) {
  const isCalledRef = React.useRef(false);

  React.useEffect(() => {
    if (condition && !isCalledRef.current) {
      isCalledRef.current = true;
      cb();
    }
  }, [cb, condition]);
}

and use it.

useOnceCall(()=>{
  console.log('called');
})

or

useOnceCall(()=>{
  console.log('isLoading');
},isLoading);

How do I add a linker or compile flag in a CMake file?

The preferred way to specify toolchain-specific options is using CMake's toolchain facility. This ensures that there is a clean division between:

  • instructions on how to organise source files into targets -- expressed in CMakeLists.txt files, entirely toolchain-agnostic; and
  • details of how certain toolchains should be configured -- separated into CMake script files, extensible by future users of your project, scalable.

Ideally, there should be no compiler/linker flags in your CMakeLists.txt files -- even within if/endif blocks. And your program should build for the native platform with the default toolchain (e.g. GCC on GNU/Linux or MSVC on Windows) without any additional flags.

Steps to add a toolchain:

  1. Create a file, e.g. arm-linux-androideadi-gcc.cmake with global toolchain settings:

    set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
    set(CMAKE_CXX_FLAGS_INIT "-fexceptions")
    

    (You can find an example Linux cross-compiling toolchain file here.)

  2. When you want to generate a build system with this toolchain, specify the CMAKE_TOOLCHAIN_FILE parameter on the command line:

    mkdir android-arm-build && cd android-arm-build
    cmake -DCMAKE_TOOLCHAIN_FILE=$(pwd)/../arm-linux-androideadi-gcc.cmake ..
    

    (Note: you cannot use a relative path.)

  3. Build as normal:

    cmake --build .
    

Toolchain files make cross-compilation easier, but they have other uses:

  • Hardened diagnostics for your unit tests.

    set(CMAKE_CXX_FLAGS_INIT "-Werror -Wall -Wextra -Wpedantic")
    
  • Tricky-to-configure development tools.

    # toolchain file for use with gcov
    set(CMAKE_CXX_FLAGS_INIT "--coverage -fno-exceptions -g")
    
  • Enhanced safety checks.

    # toolchain file for use with gdb
    set(CMAKE_CXX_FLAGS_DEBUG_INIT "-fsanitize=address,undefined -fsanitize-undefined-trap-on-error")
    set(CMAKE_EXE_LINKER_FLAGS_INIT "-fsanitize=address,undefined -static-libasan")
    

Forward X11 failed: Network error: Connection refused

The D-Bus error can be fixed with dbus-launch :

dbus-launch command

Is it possible to clone html element objects in JavaScript / JQuery?

Try this:

$('#foo1').html($('#foo2').children().clone());

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

Changing the resolution of a VNC session in linux

Perhaps the most ignorant answer I've posted but here goes: Use TigerVNC client/viewer and check 'Resize remote session to local window' under Screen tab of options.

I don't know what the $%#@ TigerVNC client tells remote vncserver or xrandr or Xvnc or gnome or ... but it resizes when I change the TigerVNC Client window.

My setup:

  • Tiger VNC Server running on CentOS 6. Hosting GNOME desktop. (Works with RHEL 6.6 too)
  • Windows some version with Tiger VNC Client.

With this the resolution changes to fit the size of the client window no matter what it is, and it's not zooming, it's actual resolution change (I can see the new resolution in xrandr output).

I tried all I could to add a new resolution to the xrandr, but to no avail, always end up with 'xrandr: Failed to get size of gamma for output default' error.

Versions with which it works for me right now (although I've not had issues with ANY versions in the past, I just install the latest using yum install gnome-* tigervnc-server and works fine):

OS: RHEL 6.6 (Santiago)
VNC Server:
Name        : tigervnc-server
Arch        : x86_64
Version     : 1.1.0
Release     : 16.el6

# May be this is relevant..
$ xrandr --version
xrandr program version       1.4.0
Server reports RandR version 1.4
$ 

# I start the server using vncserver -geometry 800x600
# Xvnc is started by vncserver with following args:
/usr/bin/Xvnc :1 -desktop plabb13.sgdcelab.sabre.com:1 (sg219898) -auth /login/sg219898/.Xauthority 
-geometry 800x600 -rfbwait 30000 -rfbauth /login/sg219898/.vnc/passwd -rfbport 5901 -fp catalogue:/e
tc/X11/fontpath.d -pn


# I'm running GNOME (installed using sudo yum install gnome-*)
Name        : gnome-desktop
Arch        : x86_64
Version     : 2.28.2
Release     : 11.el6

Name        : gnome-session
Arch        : x86_64
Version     : 2.28.0
Release     : 22.el6

Connect using Tiger 32-bit VNC Client v1.3.1 on Windows 7.

ActionBar text color

A lot of answers are deprecated so I'll update the thread and show how to change text color and backgroundcolor on ActionBar (Toolbar) and in ActionBar pop up menu.

The latest approach in Android (as of May 2018) in working with Action bar (Toolbar) is to use Theme with NoActionBar and use Toolbar instead.

so here is what you need:

  1. In Activity (which extends AppCompatActivity) declare Toolbar:

    Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(myToolbar);
    
  2. Add Toolbar in the Activity's layout xml. Here we will set our custom (overwritten themes), note android:theme="@style/ThemeOverlay.AppTheme.ActionBar" and app:popupTheme="@style/ThemeOverlay.AppTheme.PopupMenu", they will do the trick.

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppTheme.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppTheme.PopupMenu"
    app:layout_constraintTop_toTopOf="parent" />
    
  3. In your styles.xml you will have to overwrite those two styles to set custom colors:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionBarTheme">@style/ThemeOverlay.AppTheme.ActionBar</item>
    <item name="actionBarPopupTheme">@style/ThemeOverlay.AppTheme.PopupMenu</item>
    </style>
    
    <style name="ThemeOverlay.AppTheme.ActionBar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:textColorPrimary">@color/action_bar_text_color</item>
    <item name="android:background">@color/action_bar_bg_color</item>
    </style>
    
    <style name="ThemeOverlay.AppTheme.PopupMenu" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">@color/popup_bg_color</item>
    <item name="android:textColorPrimary">@color/popup_text_color</item>
    </style>
    

That's it folks

p.s. if you ask me I would say: YES, this whole Theme thing is a hell of a mess.

Disable Transaction Log

There is a third recovery mode not mentioned above. The recovery mode ultimately determines how large the LDF files become and how ofter they are written to. In cases where you are going to be doing any type of bulk inserts, you should set the DB to be in "BULK/LOGGED". This makes bulk inserts move speedily along and can be changed on the fly.

To do so,

USE master ;
ALTER DATABASE model SET RECOVERY BULK_LOGGED ;

To change it back:

USE master ;
ALTER DATABASE model SET RECOVERY FULL ;

In the spirit of adding to the conversation about why someone would not want an LDF, I add this: We do multi-dimensional modelling. Essentially we use the DB as a large store of variables that are processed in bulk using external programs. We do not EVER require rollbacks. If we could get a performance boost by turning of ALL logging, we'd take it in a heart beat.

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

Can You Get A Users Local LAN IP Address Via JavaScript?

As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com

This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).

Mobile Redirect using htaccess

I tested bits and pieces of the following, but not the complete rule set in its entirety, so if you run into trouble with it let me know and I'll dig around a bit more. However, assuming I got everything correct, you could try something like the following:

RewriteEngine On

# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)noredirect=true(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]

# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
#  had to check, but I believe most mobile devices should send at
#  least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile}       !^$
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie}        !\smredir=0(;|$)
# Now redirect to the mobile site
RewriteRule ^ http://m.example.org%{REQUEST_URI} [R,L]

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

I had a similar problem:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"sh\": executable file not found in $PATH": unknown.

In my case, I know the image works in other places, then was a corrupted local image. I solved the issue removing the image (docker rmi <imagename>) and pulling it again(docker pull <imagename>).

I did a docker system prune too, but I think it's not mandatory.

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I also faced the same issue you just need to add the library , Junit Library is already provided along with Eclipse so you just need to follow below

Build Path > Configure Build Path > library > Add library > JUnit > Next > finish

It works for me

how to call an ASP.NET c# method using javascript

The Jayrock RPC library is a great tool for doing this in a nice familliar way for C# developers. It allows you to create a .NET class with the methods you require, and add this class as a script (in a roundabout way) to your page. You can then create a js object of your type and call methods as you would any other object.

It essentially hides away ajax implementation and presents RPC in a familliar format. Mind you the best option really is to use ASP.NET MVC and use jQuery ajax calls to action methods - much more concise and less messing about!

MySQL ORDER BY rand(), name ASC

Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.

SELECT COUNT(id) FROM users; #id is the primary key

Then, get a random twenty rows.

$start_row = mt_rand(0, $total_rows - 20);

The final query:

SELECT * FROM users ORDER BY name ASC LIMIT $start_row, 20;

Select first 4 rows of a data.frame in R

In case someone is interested in dplyr solution, it's very intuitive:

dt <- dt %>%
  slice(1:4)

JPanel Padding in Java

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

Why is volatile needed in C?

Volatile tells the compiler not to optimize anything that has to do with the volatile variable.

There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there's another thread running that also uses the variable; or when there's a signal handler that might change the value of the variable.

Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:

typedef struct
{
  int command;
  int data;
  int isbusy;
} MyHardwareGadget;

Now you want to send some command:

void SendCommand (MyHardwareGadget * gadget, int command, int data)
{
  // wait while the gadget is busy:
  while (gadget->isbusy)
  {
    // do nothing here.
  }
  // set data first:
  gadget->data    = data;
  // writing the command starts the action:
  gadget->command = command;
}

Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of isbusy just once and then go into an infinite loop. That's not what you want.

The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either:

This is the correct version:

   void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
    {
      // wait while the gadget is busy:
      while (gadget->isbusy)
      {
        // do nothing here.
      }
      // set data first:
      gadget->data    = data;
      // writing the command starts the action:
      gadget->command = command;
    }

Pandas dataframe groupby plot

Similar to Julien's answer above, I had success with the following:

fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
    ax.plot(grp['Date'], grp['adj_close'], label=key)

ax.legend()
plt.show()

This solution might be more relevant if you want more control in matlab.

Solution inspired by: https://stackoverflow.com/a/52526454/10521959

jquery: get value of custom attribute

You can also do this by passing function with onclick event

<a onclick="getColor(this);" color="red">

<script type="text/javascript">

function getColor(el)
{
     color = $(el).attr('color');
     alert(color);
}

</script> 

Split string based on regex

I suggest

l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)

Check this demo.

PHP: if !empty & empty

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}