Programs & Examples On #Basic msi

Basic MSI is the Windows Installer-based project type in InstallShield

get string value from HashMap depending on key name

Your question isn't at all clear I'm afraid. A key doesn't have a "name"; it's not "called" anything as far as the map is concerned - it's just a key, and will be compared with other keys. If you have lots of different kinds of keys, I strongly suggest you put them in different maps for the sake of sanity.

If this doesn't help, please clarify the question - preferrably with some code to show what you mean.

python time + timedelta equivalent

You can change time() to now() for it to work

from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)

Improve INSERT-per-second performance of SQLite

The answer to your question is that the newer SQLite 3 has improved performance, use that.

This answer Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly? by SqlAlchemy Orm Author has 100k inserts in 0.5 sec, and I have seen similar results with python-sqlite and SqlAlchemy. Which leads me to believe that performance has improved with SQLite 3.

How to fix Python Numpy/Pandas installation?

If you're like me and you don't like the idea of deleting things that were part of the standard system installation (which others have suggested) then you might like the solution I ended up using:

  1. Get Homebrew - it's a one-line shell script to install!
  2. Edit your .profile, or whatever is appropriate, and put /usr/local/bin at the start of your PATH so that Homebrew binaries are found before system binaries
  3. brew install python - this installs a newer version of python in /usr/local
  4. pip install pandas

This worked for me in OS X 10.8.2, and I can't see any reason it shouldn't work in 10.6.8.

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Disable html5 video autoplay

I'd remove the autoplay attribute, since if the browser encounters it, it autoplays!

autoplay is a HTML boolean attribute, but be aware that the values true and false are not allowed. To represent a false value, you must omit the attribute.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

Also, the type goes inside the source, like this:

<video width="640" height="480" controls preload="none">
   <source src="http://example.com/mytestfile.mp4" type="video/mp4">
   Your browser does not support the video tag.
</video>

References:

Load and execution sequence of a web page?

AFAIK, the browser (at least Firefox) requests every resource as soon as it parses it. If it encounters an img tag it will request that image as soon as the img tag has been parsed. And that can be even before it has received the totality of the HTML document... that is it could still be downloading the HTML document when that happens.

For Firefox, there are browser queues that apply, depending on how they are set in about:config. For example it will not attempt to download more then 8 files at once from the same server... the additional requests will be queued. I think there are per-domain limits, per proxy limits, and other stuff, which are documented on the Mozilla website and can be set in about:config. I read somewhere that IE has no such limits.

The jQuery ready event is fired as soon as the main HTML document has been downloaded and it's DOM parsed. Then the load event is fired once all linked resources (CSS, images, etc.) have been downloaded and parsed as well. It is made clear in the jQuery documentation.

If you want to control the order in which all that is loaded, I believe the most reliable way to do it is through JavaScript.

What is the difference between SQL and MySQL?

SQL is Structured Query Language

MySQL is a relational database management system. You can submit SQL queries to the MySQL database to store, retrieve, modify or delete data.

Insertion sort vs Bubble Sort Algorithms

Bubble sort is almost useless under all circumstances. In use cases when insertion sort may have too many swaps, selection sort can be used because it guarantees less than N times of swap. Because selection sort is better than bubble sort, bubble sort has no use cases.

Convert long/lat to pixel x/y on a given picture

If each pixel is assumed to be of the same area then the following article about converting distances to longitude/latitude co-ordinates may be of some help to you:

http://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/

How to get all options in a drop-down list by Selenium WebDriver using C#?

You can try using the WebDriver.Support SelectElement found in OpenQA.Selenium.Support.UI.Selected namespace to access the option list of a select list:

IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));

SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;

You can then access each option as an IWebElement, such as:

IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");

Display current time in 12 hour format with AM/PM

Easiest way to get it by using date pattern - h:mm a, where

  • h - Hour in am/pm (1-12)
  • m - Minute in hour
  • a - Am/pm marker

Code snippet :

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Read more on documentation - SimpleDateFormat java 7

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

My problem was the wrong port number for mongoDB server.

I had:

DATABASE_URL= "mongodb://localhost:3000/node-express-mongodb-server"

in my .env file (my environmental variables), but I had written it before running mongoDB server. So when I ran the mongoDB server, it wrote a different port number and I had to change it. I changed it to the right port number (which was written on my cmd window by mongoDB):

DATABASE_URL= "mongodb://localhost:27017/node-express-mongodb-server"

and now it works fine.

How should I print types like off_t and size_t?

To print off_t:

printf("%jd\n", (intmax_t)x);

To print size_t:

printf("%zu\n", x);

To print ssize_t:

printf("%zd\n", x);

See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:

http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html

If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.

For example if your compiler has long long and your standard library supports %lld, you can confidently expect that will serve in place of intmax_t. But if it doesn't, you'll have to fall back to long, which would fail on some other implementations because it's too small.

Laravel view not found exception

As @deanchiu said it may happen when you move the whole project to another path or server.

But in my case I had no access to command line on server and running following commands BEFORE I upload my project helped me.

> php artisan route:clear
> php artisan config:clear

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

Build error: You must add a reference to System.Runtime

Adding a reference to this System.Runtime.dll assembly fixed the issue:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Runtime.dll

Though that file in that explicit path doesn't exist on the build server.

I will post back with more information once I've found some documentation on PCL and these Facades.

Update

Yeah pretty much nothing on facade assemblies on the whole internet.

Google:

(Facades OR Facade) Portable Library site:microsoft.com

If Radio Button is selected, perform validation on Checkboxes

You need to use == or === for comparison. = assigns a new value.

Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

How can I check if some text exist or not in the page using Selenium?

Python:

driver.get(url)
content=driver.page_source
if content.find("text_to_search"): 
    print("text is present in the webpage")

Download the html page and use find()

How do I create delegates in Objective-C?

The approved answer is great, but if you're looking for a 1 minute answer try this:

MyClass.h file should look like this (add delegate lines with comments!)

#import <BlaClass/BlaClass.h>

@class MyClass;             //define class, so protocol can see MyClass
@protocol MyClassDelegate <NSObject>   //define delegate protocol
    - (void) myClassDelegateMethod: (MyClass *) sender;  //define delegate method to be implemented within another class
@end //end protocol

@interface MyClass : NSObject {
}
@property (nonatomic, weak) id <MyClassDelegate> delegate; //define MyClassDelegate as delegate

@end

MyClass.m file should look like this

#import "MyClass.h"
@implementation MyClass 
@synthesize delegate; //synthesise  MyClassDelegate delegate

- (void) myMethodToDoStuff {
    [self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class    
}

@end

To use your delegate in another class (UIViewController called MyVC in this case) MyVC.h:

#import "MyClass.h"
@interface MyVC:UIViewController <MyClassDelegate> { //make it a delegate for MyClassDelegate
}

MyVC.m:

myClass.delegate = self;          //set its delegate to self somewhere

Implement delegate method

- (void) myClassDelegateMethod: (MyClass *) sender {
    NSLog(@"Delegates are great!");
}

How do I format axis number format to thousands with a comma in matplotlib?

Short answer without importing matplotlib as mpl

plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))

Modified from @AlexG's answer

What are intent-filters in Android?

If possible try this one instant solution:

Intent intent =new Intent(getApplicationBaseContext,second_Act.class);
StartActivity(intent);

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

How to scan multiple paths using the @ComponentScan annotation?

You can also use @ComponentScans annotation:

@ComponentScans(value = { @ComponentScan("com.my.package.first"),
                          @ComponentScan("com.my.package.second") })

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to check whether a Button is clicked by using JavaScript

Just hook up the onclick event:

<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>

What is Unicode, UTF-8, UTF-16?

  • Unicode
    • is a set of characters used around the world
  • UTF-8
    • a character encoding capable of encoding all possible characters (called code points) in Unicode.
    • code unit is 8-bits
    • use one to four code units to encode Unicode
    • 00100100 for "$" (one 8-bits);11000010 10100010 for "¢" (two 8-bits);11100010 10000010 10101100 for "" (three 8-bits)
  • UTF-16
    • another character encoding
    • code unit is 16-bits
    • use one to two code units to encode Unicode
    • 00000000 00100100 for "$" (one 16-bits);11011000 01010010 11011111 01100010 for "" (two 16-bits)

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

How do I check form validity with angularjs?

You can also use myform.$invalid

E.g.

if($scope.myform.$invalid){return;}

Add all files to a commit except a single file?

I use git add --patch quite a bit and wanted something like this to avoid having to hit d all the time through the same files. I whipped up a very hacky couple of git aliases to get the job done:

[alias]
    HELPER-CHANGED-FILTERED = "!f() { git status --porcelain | cut -c4- | ( [[ \"$1\" ]] && egrep -v \"$1\" || cat ); }; f"
    ap                      = "!git add --patch -- $(git HELPER-CHANGED-FILTERED 'min.(js|css)$' || echo 'THIS_FILE_PROBABLY_DOESNT_EXIST' )"

In my case I just wanted to ignore certain minified files all the time, but you could make it use an environment variable like $GIT_EXCLUDE_PATTERN for a more general use case.

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

How do I express "if value is not empty" in the VBA language?

Alexphi's suggestion is good. You can also hard code this by first creating a variable as a Variant and then assigning it to Empty. Then do an if/then with to possibly fill it. If it gets filled, it's not empty, if it doesn't, it remains empty. You check this then with IsEmpty.

Sub TestforEmpty()

    Dim dt As Variant
    dt = Empty

    Dim today As Date
    today = Date
    If today = Date Then
        dt = today
    End If

    If IsEmpty(dt) Then
        MsgBox "It not is today"
    Else
        MsgBox "It is today"
    End If

End Sub

Loop in Jade (currently known as "Pug") template engine

Just adding another possibility as it might help someone that's trying to both iterate over an array AND maintain a count. For example, the code below goes through an array named items and only displays the first 3 items. Notice that the each and the if are native jade and don't need a hyphen.

ul
  - var count = 0;
  each item in items
    if count < 3
      li= item.name
    - count++;

Python __call__ special method practical example

The function call operator.

class Foo:
    def __call__(self, a, b, c):
        # do something

x = Foo()
x(1, 2, 3)

The __call__ method can be used to redefined/re-initialize the same object. It also facilitates the use of instances/objects of a class as functions by passing arguments to the objects.

Check if an array is empty or exists

in ts

 isArray(obj: any) 
{
    return Array.isArray(obj)
  }

in html

(photos == undefined || !(isArray(photos) && photos.length > 0) )

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.

Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater.

The code is the following, where this is an Activity:

final LayoutInflater factory = getLayoutInflater();

final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);

landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);

You need to get the inflater for this context, access the root view through the inflate method and finally call findViewById on the root view of the layout.

Hope this is useful for someone! Bye

Enabling HTTPS on express.js

This is my working code for express 4.0.

express 4.0 is very different from 3.0 and others.

4.0 you have /bin/www file, which you are going to add https here.

"npm start" is standard way you start express 4.0 server.

readFileSync() function should use __dirname get current directory

while require() use ./ refer to current directory.

First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.

How to get the last characters in a String in Java, regardless of String size

String inputstr = "abcd: efg: 1006746"
int startindex = inputstr.length() - 10;
String outputtendigitstr = inputstr.substring(startindex);

Make sure you check string length is more than 10.

Detecting when a div's height changes using jQuery

You can make a simple setInterval.

_x000D_
_x000D_
function someJsClass()_x000D_
{_x000D_
  var _resizeInterval = null;_x000D_
  var _lastHeight = 0;_x000D_
  var _lastWidth = 0;_x000D_
  _x000D_
  this.Initialize = function(){_x000D_
    var _resizeInterval = setInterval(_resizeIntervalTick, 200);_x000D_
  };_x000D_
  _x000D_
  this.Stop = function(){_x000D_
    if(_resizeInterval != null)_x000D_
      clearInterval(_resizeInterval);_x000D_
  };_x000D_
  _x000D_
  var _resizeIntervalTick = function () {_x000D_
    if ($(yourDiv).width() != _lastWidth || $(yourDiv).height() != _lastHeight) {_x000D_
      _lastWidth = $(contentBox).width();_x000D_
      _lastHeight = $(contentBox).height();_x000D_
      DoWhatYouWantWhenTheSizeChange();_x000D_
    }_x000D_
  };_x000D_
}_x000D_
_x000D_
var class = new someJsClass();_x000D_
class.Initialize();
_x000D_
_x000D_
_x000D_

EDIT:

This is a example with a class. But you can do something easiest.

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How can you encode a string to Base64 in JavaScript?

Contributing with a minified polyfill for window.atob + window.btoa that I'm currently using.

(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I am assuming Basic authentication here.

$cred = Get-Credential
Invoke-WebRequest -Uri 'https://whatever' -Credential $cred

You can get your credential through other means (Import-Clixml, etc.), but it does have to be a [PSCredential] object.

Edit based on comments:

GitHub is breaking RFC as they explain in the link you provided:

The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header.

Powershell's Invoke-WebRequest does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent.

Manually build the headers

Instead you'll have to create the basic auth headers yourself.

Basic authentication takes a string that consists of the username and password separated by a colon user:pass and then sends the Base64 encoded result of that.

Code like this should work:

$user = 'user'
$pass = 'pass'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}

Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

You could combine some of the string concatenation but I wanted to break it out to make it clearer.

show/hide a div on hover and hover out

Why not just use .show()/.hide() instead?

$("#menu").hover(function(){
    $('.flyout').show();
},function(){
    $('.flyout').hide();
});

Finding modified date of a file/folder

PowerShell code to find all document library files modified from last 2 days.

$web = Get-SPWeb -Identity http://siteName:9090/ 
        $list = $web.GetList("http://siteName:9090/Style Library/")
        $folderquery =  New-Object Microsoft.SharePoint.SPQuery  
        $foldercamlQuery =  
        '<Where>   <Eq> 
                <FieldRef Name="ContentType" />  <Value Type="text">Folder</Value> 
            </Eq> </Where>' 
        $folderquery.Query = $foldercamlQuery 
        $folders = $list.GetItems($folderquery) 
        foreach($folderItem in $folders) 
        { 
            $folder = $folderItem.Folder
            if($folder.ItemCount -gt 0){ 
            Write-Host " find Item count " $folder.ItemCount
                $oldest = $null
                $files = $folder.Files

                $date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
                foreach ($file in $files){ 
                    if($file.Item["Modified"]-Ge $date)
                    {
                        Write-Host "Last 2 days modified folder name:"   $folder   " File Name: "  $file.Item["Name"]   " Date of midified: "  $file.Item["Modified"] 
                    } 
                } 
            } 
            else
             { 
                Write-Warning "$folder['Name'] is empty" 
            } 
        }

Unit Tests not discovered in Visual Studio 2017

In my case, it was UWP project present in the solution causing the issue.

When I unloaded the UWP project, tests were discovered. When I loaded it back, test disappeard again.

Try to unload all projects and keep test project only. Ten rebuild solution and test shound appear in Test Runner. Load projects one by one and rebuild solution each time to find out what project are causing the problem

sample repo

VS bug report

How to get the <html> tag HTML with JavaScript / jQuery?

if you want to get an attribute of an HTML element with jQuery you can use .attr();

so $('html').attr('someAttribute'); will give you the value of someAttribute of the element html

http://api.jquery.com/attr/

Additionally:

there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes

that allows you to get all attributes from an HTML element

Find duplicate records in MongoDB

You can find the list of duplicate names using the following aggregate pipeline:

  • Group all the records having similar name.
  • Match those groups having records greater than 1.
  • Then group again to project all the duplicate names as an array.

The Code:

db.collection.aggregate([
{$group:{"_id":"$name","name":{$first:"$name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"name":1,"_id":0}},
{$group:{"_id":null,"duplicateNames":{$push:"$name"}}},
{$project:{"_id":0,"duplicateNames":1}}
])

o/p:

{ "duplicateNames" : [ "ksqn291", "ksqn29123213Test" ] }

Multiple Python versions on the same machine?

I did this with anaconda navigator. I installed anaconda navigator and created two different development environments with different python versions

and switch between different python versions by switching or activating and deactivating environments.

first install anaconda navigator and then create environments.

see help here on how to manage environments

https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/

Here is the video to do it with conda

https://youtu.be/EGaw6VXV3GI

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

log4net vs. Nlog

For anyone getting to this thread late, you may want to take a look back at the .Net Base Class Library (BCL). Many people missed the changes between .Net 1.1 and .Net 2.0 when the TraceSource class was introduced (circa 2005).

Using the TraceSource is analagous to other logging frameworks, with granular control of logging, configuration in app.config/web.config, and programmatic access - without the overhead of the enterprise application block.

There are also a number of comparisons floating around: "log4net vs TraceSource"

How to determine the last Row used in VBA including blank spaces in between

here is my code to find the next empty row for example in first row 'A'. To use it for any other row just change cells(i,2 or 3 or 4 so on)

Sheets("Sheeet1").Select
   for i=1 to 5000
        if cells(i,1)="" then nextEmpty=i goto 20
   next i
20 'continue your code here 

enter code here

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

a) object Class "Long" versus primitive type "long". (At least in Java)

b) There are different (even unclear) memory-sizes of the primitive types:

Java - all clear: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

  • byte, char .. 1B .. 8b
  • short int .. 2B .. 16b
  • int .. .. .. .. 4B .. 32b
  • long int .. 8B .. 64b

C .. just mess: https://en.wikipedia.org/wiki/C_data_types

  • short .. .. 16b
  • int .. .. .. 16b ... wtf?!?!
  • long .. .. 32b
  • long long .. 64b .. mess! :-/

Uncaught TypeError: undefined is not a function while using jQuery UI

Usually when you get this problem, it happens because a script is trying to reference an element that doesn't exist yet while the page is loading.

As richie mentioned: "The HTML parser will parse the HTML content from top to bottom..."

So you can add your JavaScript references to the bottom of the HTML file. This will not only improve performance; it will also ensure that all elements referenced in your script files have already been loaded by the HTML parser.

So you could have something like this:

<html>
    <head>
        <!--  Style sheet references and CSS definitions -->
    </head>
    <body>
        <!-- HTML markup and other page content -->

        <!-- JavaScript references. You could include jQuery here as well and do all your scripting here. -->
    </body>
</html>

How to drop all tables from the database with manage.py CLI in Django?

If you want to completely wipe the database and resync it in the same go you need something like the following. I also combine adding test data in this command:

#!/usr/bin/env python

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") # Replace with your app name.

from django.db import connection
from django.core.management import call_command
from django.conf import settings
# If you're using postgres you can't use django's sql stuff for some reason that I
# can't remember. It has to do with that autocommit thing I think.
# import psychodb2 as db

def recreateDb():
    print("Wiping database")
    dbinfo = settings.DATABASES['default']

    # Postgres version
    #conn = db.connect(host=dbinfo['HOST'], user=dbinfo['USER'],
    #                 password=dbinfo['PASSWORD'], port=int(dbinfo['PORT'] or 5432))
    #conn.autocommit = True
    #cursor = conn.cursor()
    #cursor.execute("DROP DATABASE " + dbinfo['NAME'])
    #cursor.execute("CREATE DATABASE " + dbinfo['NAME'] + " WITH ENCODING 'UTF8'") # Default is UTF8, but can be changed so lets be sure.

    # Mysql version:
    print("Dropping and creating database " + dbinfo['NAME'])
    cursor = connection.cursor()
    cursor.execute("DROP DATABASE " + dbinfo["NAME"] + "; CREATE DATABASE " + dbinfo["NAME"] + "; USE " + dbinfo["NAME"] + ";")
    print("Done")


if __name__ == "__main__":
    recreateDb();
    print("Syncing DB")
    call_command('syncdb', interactive=False)
    print("Adding test data")
    addTestData() # ...

It would be nice to be able to do cursor.execute(call_command('sqlclear', 'main')) but call_command prints the SQL to stdout rather than returning it as a string, and I can't work out the sql_delete code...

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

i know this is old, i actually just had the same issue. i was able to solve it by running npm install -g node-gyp and fixed! npm

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

How to get cumulative sum

Try this:

CREATE TABLE #t(
 [name] varchar NULL,
 [val] [int] NULL,
 [ID] [int] NULL
) ON [PRIMARY]

insert into #t (id,name,val) values
 (1,'A',10), (2,'B',20), (3,'C',30)

select t1.id, t1.val, SUM(t2.val) as cumSum
 from #t t1 inner join #t t2 on t1.id >= t2.id
 group by t1.id, t1.val order by t1.id

SOAP request to WebService with java

I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

Change callSoapWebService method first line to following.

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

I hope it will be helpful to others.

jQuery serialize does not register checkboxes

You can call handleInputs() add in your submit function before ajax

function handleInputs(){
    $('input[type=checkbox]').each(function() {     
        if (!this.checked) {
            $(this).attr("value","0");
        }else{
            $(this).attr("value","1");
        }
    });
}

It is perfectly working

Pass element ID to Javascript function

Check this: http://jsfiddle.net/h7kRt/1/,

you should change in jsfiddle on top-left to No-wrap in <head>

Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.

find: missing argument to -exec

Both {} and && will cause problems due to being expanded by the command line. I would suggest trying:

find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i \{} -sameq \{}.mp3 \; -exec rm \{} \;

Main differences between SOAP and RESTful web services in Java

REST is an architecture.
REST will give human-readable results.
REST is stateless.
REST services are easily cacheable.

SOAP is a protocol. It can run on top of JMS, FTP, and HTTP.

How to change 1 char in the string?

Strings are immutable. You can use the string builder class to help!:

string str = "valta is the best place in the World";

StringBuilder strB = new StringBuilder(str);

strB[0] = 'M';

How to set width and height dynamically using jQuery

Try this:

<div id="mainTable" style="width:100px; height:200px;"></div> 

$(document).ready(function() {
  $("#mainTable").width(100).height(200);
}) ;

How do I return a proper success/error message for JQuery .ajax() using PHP?

Server side:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

Client side:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

Javascript validation: Block special characters

For special characters:

var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

for (var i = 0; i < document.formname.fieldname.value.length; i++) {
    if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
        alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
        return false;
    }
}

Is there a way I can capture my iPhone screen as a video?

I've continued to research this item myself, and it does appear to remain beyond us at this point.

I even tried buying a Apple Composite AV Cable, but it doesn't capture screen, just video playing like YouTube, etc.

So I decided to go with the iShowU path and that has worked out well so far.

Thanks Guys!

Use CSS to automatically add 'required field' asterisk to form inputs

This example puts an asterisk symbol in front of a label to denote that particular input as a required field. I set the CSS properties using % and em to makesure my webpage is responsive. You could use px or other absolute units if you want to.

_x000D_
_x000D_
#name {_x000D_
   display: inline-block;_x000D_
   margin-left: 40%;_x000D_
   font-size:25px;_x000D_
    _x000D_
}_x000D_
.nameinput{_x000D_
   margin-left: 10px;_x000D_
   font-size:90%;_x000D_
   width: 17em;_x000D_
   _x000D_
}_x000D_
_x000D_
.nameinput::placeholder {_x000D_
  font-size: 0.7em;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
#name p{_x000D_
   margin:0;_x000D_
   border:0;_x000D_
   padding:0;_x000D_
   display:inline-block;_x000D_
   font-size: 40%;_x000D_
   vertical-align: super;_x000D_
}
_x000D_
<label id="name" value="name">_x000D_
<p>*</p> _x000D_
Name:  <input class="nameinput" type="text" placeholder="Enter your name" required>_x000D_
</label>
_x000D_
_x000D_
_x000D_

How do I select an element with its name attribute in jQuery?

You could always do $('input[name="somename"]')

Calling C++ class methods via a function pointer

I did this with std::function and std::bind..

I wrote this EventManager class that stores a vector of handlers in an unordered_map that maps event types (which are just const unsigned int, I have a big namespace-scoped enum of them) to a vector of handlers for that event type.

In my EventManagerTests class, I set up an event handler, like this:

auto delegate = std::bind(&EventManagerTests::OnKeyDown, this, std::placeholders::_1);
event_manager.AddEventListener(kEventKeyDown, delegate);

Here's the AddEventListener function:

std::vector<EventHandler>::iterator EventManager::AddEventListener(EventType _event_type, EventHandler _handler)
{
    if (listeners_.count(_event_type) == 0) 
    {
        listeners_.emplace(_event_type, new std::vector<EventHandler>());
    }
    std::vector<EventHandler>::iterator it = listeners_[_event_type]->end();
    listeners_[_event_type]->push_back(_handler);       
    return it;
}

Here's the EventHandler type definition:

typedef std::function<void(Event *)> EventHandler;

Then back in EventManagerTests::RaiseEvent, I do this:

Engine::KeyDownEvent event(39);
event_manager.RaiseEvent(1, (Engine::Event*) & event);

Here's the code for EventManager::RaiseEvent:

void EventManager::RaiseEvent(EventType _event_type, Event * _event)
{
    if (listeners_.count(_event_type) > 0)
    {
        std::vector<EventHandler> * vec = listeners_[_event_type];
        std::for_each(
            begin(*vec), 
            end(*vec), 
            [_event](EventHandler handler) mutable 
            {
                (handler)(_event);
            }
        );
    }
}

This works. I get the call in EventManagerTests::OnKeyDown. I have to delete the vectors come clean up time, but once I do that there are no leaks. Raising an event takes about 5 microseconds on my computer, which is circa 2008. Not exactly super fast, but. Fair enough as long as I know that and I don't use it in ultra hot code.

I'd like to speed it up by rolling my own std::function and std::bind, and maybe using an array of arrays rather than an unordered_map of vectors, but I haven't quite figured out how to store a member function pointer and call it from code that knows nothing about the class being called. Eyelash's answer looks Very Interesting..

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

How to specify the download location with wget?

man wget: -O file --output-document=file

wget "url" -O /tmp/cron_test/<file>

How to get html to print return value of javascript function?

It depends what you're going for. I believe the closest thing JS has to print is:

document.write( produceMessage() );

However, it may be more prudent to place the value inside a span or a div of your choosing like:

document.getElementById("mySpanId").innerHTML = produceMessage();

Split string into array of character strings

"cat".split("(?!^)")

This will produce

array ["c", "a", "t"]

String date to xmlgregoriancalendar conversion

Found the solution as below.... posting it as it could help somebody else too :)

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);

XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

System.out.println(xmlGregCal);

Output:

2014-04-24T11:15:00.000+02:00

Best practice to call ConfigureAwait for all server-side code

The biggest draw back I've found with using ConfigureAwait(false) is that the thread culture is reverted to the system default. If you've configured a culture e.g ...

<system.web>
    <globalization culture="en-AU" uiCulture="en-AU" />    
    ...

and you're hosting on a server whose culture is set to en-US, then you will find before ConfigureAwait(false) is called CultureInfo.CurrentCulture will return en-AU and after you will get en-US. i.e.

// CultureInfo.CurrentCulture ~ {en-AU}
await xxxx.ConfigureAwait(false);
// CultureInfo.CurrentCulture ~ {en-US}

If your application is doing anything which requires culture specific formatting of data, then you'll need to be mindful of this when using ConfigureAwait(false).

setting request headers in selenium

Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.

Here are a couple of possibilities that I can propose:

  1. Use another driver/library instead of selenium
  2. Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
  3. Use browsermob-proxy or some other proxy.

I'd go with option 3 in most of cases. It's not hard.

Note that Ghostdriver has an API for it but it's not supported by other drivers.

git - Server host key not cached

I suspect that your GIT_SSH environment variable is set to %ProgramFiles(x86)%\putty\plink.exe. For some reason, PLink does not use the .ssh/known_hosts file in your user directory to store the remote hosts keys.

If this is actually your case, and it might be so on purpose if you want to use pageant, you need to use PLink to connect to the host first.

"$GIT_SSH" user@hostname

You should get a similar message

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 86:7b:1b:12:85:35:8a:b7:98:b6:d2:97:5e:96:58:1d
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Once you have answered y to the question and successfully connected to the remote host, you should be all set. Go ahead and try your push again.

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

How to start a background process in Python?

You probably want the answer to "How to call an external command in Python".

The simplest approach is to use the os.system function, e.g.:

import os
os.system("some_command &")

Basically, whatever you pass to the system function will be executed the same as if you'd passed it to the shell in a script.

How to get JSON object from Razor Model object in javascript

In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

It should be as simple as:

<script>
  var json = @Json.Serialize(Model.CollegeInformationlist);
</script>

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

Add JsonArray to JsonObject

here is simple code

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
    obj.put("result", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());

Timeout a command in bash without unnecessary delay

OS X doesn't use bash 4 yet, nor does it have /usr/bin/timeout, so here's a function that works on OS X without home-brew or macports that is similar to /usr/bin/timeout (based on Tino's answer). Parameter validation, help, usage, and support for other signals are an exercise for reader.

# implement /usr/bin/timeout only if it doesn't exist
[ -n "$(type -p timeout 2>&1)" ] || function timeout { (
    set -m +b
    sleep "$1" &
    SPID=${!}
    ("${@:2}"; RETVAL=$?; kill ${SPID}; exit $RETVAL) &
    CPID=${!}
    wait %1
    SLEEPRETVAL=$?
    if [ $SLEEPRETVAL -eq 0 ] && kill ${CPID} >/dev/null 2>&1 ; then
      RETVAL=124
      # When you need to make sure it dies
      #(sleep 1; kill -9 ${CPID} >/dev/null 2>&1)&
      wait %2
    else
      wait %2
      RETVAL=$?
    fi
    return $RETVAL
) }

How do you properly return multiple values from a Promise?

Here is how I reckon you should be doing.

splitting the chain

Because both functions will be using amazingData, it makes sense to have them in a dedicated function. I usually do that everytime I want to reuse some data, so it is always present as a function arg.

As your example is running some code, I will suppose it is all declared inside a function. I will call it toto(). Then we will have another function which will run both afterSomething() and afterSomethingElse().

function toto() {
    return somethingAsync()
        .then( tata );
}

You will also notice I added a return statement as it is usually the way to go with Promises - you always return a promise so we can keep chaining if required. Here, somethingAsync() will produce amazingData and it will be available everywhere inside the new function.

Now what this new function will look like typically depends on is processAsync() also asynchronous?

processAsync not asynchronous

No reason to overcomplicate things if processAsync() is not asynchronous. Some old good sequential code would make it.

function tata( amazingData ) {
    var processed = afterSomething( amazingData );
    return afterSomethingElse( amazingData, processed );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}

Note that it does not matter if afterSomethingElse() is doing something async or not. If it does, a promise will be returned and the chain can continue. If it is not, then the result value will be returned. But because the function is called from a then(), the value will be wrapped into a promise anyway (at least in raw Javascript).

processAsync asynchronous

If processAsync() is asynchronous, the code will look slightly different. Here we consider afterSomething() and afterSomethingElse() are not going to be reused anywhere else.

function tata( amazingData ) {
    return afterSomething()
        .then( afterSomethingElse );

    function afterSomething( /* no args */ ) {
        return processAsync( amazingData );
    }
    function afterSomethingElse( processedData ) {
        /* amazingData can be accessed here */
    }
}

Same as before for afterSomethingElse(). It can be asynchronous or not. A promise will be returned, or a value wrapped into a resolved promise.


Your coding style is quite close to what I use to do, that is why I answered even after 2 years. I am not a big fan of having anonymous functions everywhere. I find it hard to read. Even if it is quite common in the community. It is as we replaced the callback-hell by a promise-purgatory.

I also like to keep the name of the functions in the then short. They will only be defined locally anyway. And most of the time they will call another function defined elsewhere - so reusable - to do the job. I even do that for functions with only 1 parameter, so I do not need to get the function in and out when I add/remove a parameter to the function signature.

Eating example

Here is an example:

function goingThroughTheEatingProcess(plenty, of, args, to, match, real, life) {
    return iAmAsync()
        .then(chew)
        .then(swallow);

        function chew(result) {
            return carefullyChewThis(plenty, of, args, "water", "piece of tooth", result);
        }

        function swallow(wine) {
            return nowIsTimeToSwallow(match, real, life, wine);
        }
}

function iAmAsync() {
    return Promise.resolve("mooooore");
}

function carefullyChewThis(plenty, of, args, and, some, more) {
    return true;
}

function nowIsTimeToSwallow(match, real, life, bobool) {
}

Do not focus too much on the Promise.resolve(). It is just a quick way to create a resolved promise. What I try to achieve by this is to have all the code I am running in a single location - just underneath the thens. All the others functions with a more descriptive name are reusable.

The drawback with this technique is that it is defining a lot of functions. But it is a necessary pain I am afraid in order to avoid having anonymous functions all over the place. And what is the risk anyway: a stack overflow? (joke!)


Using arrays or objects as defined in other answers would work too. This one in a way is the answer proposed by Kevin Reid.

You can also use bind() or Promise.all(). Note that they will still require you to split your code.

using bind

If you want to keep your functions reusable but do not really need to keep what is inside the then very short, you can use bind().

function tata( amazingData ) {
    return afterSomething( amazingData )
        .then( afterSomethingElse.bind(null, amazingData) );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}

To keep it simple, bind() will prepend the list of args (except the first one) to the function when it is called.

using Promise.all

In your post you mentionned the use of spread(). I never used the framework you are using, but here is how you should be able to use it.

Some believe Promise.all() is the solution to all problems, so it deserves to be mentioned I guess.

function tata( amazingData ) {
    return Promise.all( [ amazingData, afterSomething( amazingData ) ] )
        .then( afterSomethingElse );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( args ) {
    var amazingData = args[0];
    var processedData = args[1];
}

You can pass data to Promise.all() - note the presence of the array - as long as promises, but make sure none of the promises fail otherwise it will stop processing.

And instead of defining new variables from the args argument, you should be able to use spread() instead of then() for all sort of awesome work.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

Editor issue. When you create new files that not using Angular CLI, make sure you go to File > Save All (VS Code) to let the Editor aware of your new changes. Then run "ng serve --open" again. It solved mine. Hope it helps

How to reset AUTO_INCREMENT in MySQL?

ALTER TABLE tablename AUTO_INCREMENT = 1

How can I stop a running MySQL query?

Connect to mysql

mysql -uusername -p  -hhostname

show full processlist:

mysql> show full processlist;
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| Id      | User   | Host              | db      | Command | Time | State | Info             |
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| 9255451 | logreg | dmin001.ops:37651 | logdata | Query   |    0 | NULL  | show processlist |
+---------+--------+-------------------+---------+---------+------+-------+------------------+

Kill the specific query. Here id=9255451

mysql> kill 9255451;

If you get permission denied, try this SQL:

CALL mysql.rds_kill(9255451)

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

How do I load an url in iframe with Jquery

$("#button").click(function () { 
    $("#frame").attr("src", "http://www.example.com/");
});

HTML:

 <div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

How do you use global variables or constant values in Ruby?

I think it's local to the file you declared offset. Consider every file to be a method itself.

Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);?

How to globally replace a forward slash in a JavaScript string?

Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.

var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);

Mac zip compress without __MACOSX folder?

zip -r "$destFileName.zip" "$srcFileName" -x "*/\__MACOSX" -x "*/\.*"
  • -x "*/\__MACOSX": ignore __MACOSX as you mention.
  • -x "*/\.*": ignore any hidden file, such as .DS_Store .
  • Quote the variable to avoid file if it's named with SPACE.

Also, you can build Automator Service to make it easily to use in Finder. Check link below to see detail if you need.

Github

How to embed fonts in HTML?

Things have changed since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.

Paul Irish put together Bulletproof @font-face syntax combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.

Snipped from his article:

@font-face {
  font-family: 'Graublau Web';
  src: url('GraublauWeb.eot');
  src: local('Graublau Web Regular'), local('Graublau Web'),
    url("GraublauWeb.woff") format("woff"),
    url("GraublauWeb.otf") format("opentype"),
    url("GraublauWeb.svg#grablau") format("svg");
}

Working from that base, Font Squirrel put together a variety of useful tools including the @font-face Generator which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has Hundreds of @font-face kits.

Soma Design also put together the FontFriend Bookmarklet, which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.

More recently, Google has started to provide the Google Web Fonts, an assortment of fonts available under an Open Source license and served from Google's servers.

License Restrictions

Finally, WebFonts.info has put together a nice wiki'd list of Fonts available for @font-face embedding based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. It's important to read the licenses, because there are some limitations that aren't pushed forward obviously on the font downloads.

How to open local file on Jupyter?

simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.

What are .iml files in Android Studio?

Add .idea and *.iml to .gitignore, you don't need those files to successfully import and compile the project.

Setting top and left CSS attributes

You can also use the setProperty method like below

document.getElementById('divName').style.setProperty("top", "100px");

How do I kill background processes / jobs when my shell script exits?

To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

trap "echo hello" SIGINT

but can also be used to execute something if the shell exits:

trap "killall background" EXIT

It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

trap 'kill $(jobs -p)' EXIT

Watch out to use single ', to prevent the shell from substituting the $() immediately.

TCP vs UDP on video stream

Drawbacks of using TCP for live video:

  1. Typically live video-streaming appliances are not designed with TCP streaming in mind. If you use TCP, the OS must buffer the unacknowledged segments for every client. This is undesirable, particularly in the case of live events; presumably your list of simultaneous clients is long due to the singularity of the event. Pre-recorded video-casts typically don't have as much of a problem with this because viewers stagger their replay activity; therefore TCP is more appropriate for replaying a video-on-demand.
  2. IP multicast significantly reduces video bandwidth requirements for large audiences; TCP prevents the use of IP multicast, but UDP is well-suited for IP multicast.
  3. Live video is normally a constant-bandwidth stream recorded off a camera; pre-recorded video streams come off a disk. The loss-backoff dynamics of TCP make it harder to serve live video when the source streams are at a constant bandwidth (as would happen for a live-event). If you buffer to disk off a camera, be sure you have enough buffer for unpredictable network events and variable TCP send/backoff rates. UDP gives you much more control for this application since UDP doesn't care about network transport layer drops.

FYI, please don't use the word "packages" when describing networks. Networks send "packets".

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

Just to add to this, because I was getting this error as well. Going through all these answers most seem to apply to working with the UI and storyboard stuff. I know the original poster did seem to be working with the UI but when searching for possible reasons for this error mostly all questions lead back to this question with those others being closed as duplicates or simply having issues with connecting things in a storyboard so I will add my solution.

I was working on coding a web service in Swift 2. I had built all the needed proxy objects and stubs. As I looped through the returned XML I was dynamically instantiating my objects, which all came from NSObject and using setValue:forKey on them. Every time setValue:forKey tried to set a property it blew up with this error.

I had a switch statement for each type I was dealing with (e.g. Bool?, CShort?, String?) and for each XML node I went through and checked what the type was on the object and then converted the value to that type and attempted to set it with setValue:forKey.

Eventually I started commenting out all these setValue:forKey lines and found that my default switch statement case did work for String?.

I finally figured out that you can't use optional swift types with setValue:forKey unless they have a direct mapping to an Objective-C type like String? or NSNumber?. I ended up changing all CShort? types to NSNumber? since that has a direct mapping. For Bool? in my case it was fine for me to just use Bool and initialize it to false. Others may not have that luxury.

Anyway what a headache that was so hopefully this helps someone else who has a similar problem and keeps getting redirected to this question and saying to themselves, "I am not doing anything in UI!!".

So lastly to reiterate one more time Key-Value Coding does not work with optionals. Below I ended up finding somewhere but I forget where so to whoever posted this I apologize and would give credit if I remembered where I found this but it saved my life:

You cannot use KVC on an Optional Int property, because KVC is Cocoa / Objective-C, and Objective-C cannot see an Optional Int - it is not bridged to Objective-C. Objective-C can only see types that are bridged to Objective-C:

class types that are derived from NSObject

class types that are exposed with @objc

Swift structs that are bridged

Best way to check for nullable bool in a condition expression (if ...)

Given enum

public enum PublishMode { Edit, View }

you can do it like here

 void MyMethod(PublishMode? mode)
    {
       var publishMode = mode ?? PublishMode.Edit;

//or
       if (mode?? PublishMode.Edit == someValue)
       ....
    }

RuntimeError: module compiled against API version a but this version of numpy is 9

To solve the problem do following:

First uninstall numpy

sudo pip uninstall numpy

Install numpy with --no-cache-dir option

sudo pip install --no-cache-dir numpy

And to specify any specific version e.g. 1.14.2

sudo pip install --no-cache-dir numpy==1.14.2

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

Install tkinter for Python

For python 3.7 on ubuntu I had to use sudo apt-get install python3.7-tk to make it work

The service cannot accept control messages at this time

Restarting the machine worked for me but not every time.

If you are really stuck on this then follow below steps

  1. Open Task Manager
  2. A window will open. Click on Details tab.
  3. Search for the process name you wanted to restart/stop.
  4. Select process, right click on it, select End task option.
  5. A confirmation dialog box will appear. Click on End process button.
  6. Now try to restart your service from Services.msc window.

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

How to pull remote branch from somebody else's repo

No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.

Grabbing their commits:

git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch

This creates a local branch named ournameforbranch which is exactly the same as what theirbranch was for them. For the question example, the last argument would be foo:foo.

Note :ournameforbranch part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD is available. You can git log FETCH_HEAD to see their commits then do things like cherry-picked to cherry pick their commits.

Pushing it back to them:

Oftentimes, you want to fix something of theirs and push it right back. That's possible too:

git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD

# fix fix fix

git push [email protected]:theirusername/reponame.git HEAD:theirbranch

If working in detached state worries you, by all means create a branch using :ournameforbranch and replace FETCH_HEAD and HEAD above with ournameforbranch.

Truncate (not round) decimal places in SQL Server

I know this question is really old but nobody used sub-strings to round. This as advantage the ability to round really long numbers (limit of your string in SQL server which is usually 8000 characters):

SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)

Team Build Error: The Path ... is already mapped to workspace

I had this issue with this with Azure DevOps automated builds in an on-prem TFS build agent. Removing the workspace using TFS Sidekicks did not work. And tf.exe could not even find the workspace to delete it.

This solution should work for TFS 2017, TFS 2018, Azure DevOps, and possibly other versions:

  1. Take note of the workspace GUID in the error message.
  2. On the machine where the build is taking place, navigate to: %USERPROFILE%\AppData\Local\Microsoft\Team Foundation\ (where %USERPROFILE% belongs to the user that triggered the build).
  3. Search for and remove all instances of the workspace GUID under that directory. There will likely be a folder in a 'cache' directory, as well as entries in 'LocationServerMap.xml' and 'LocalItemExclusions.config'. Remove them all.

That worked in my circumstance.

Best cross-browser method to capture CTRL+S with JQuery?

I like this little plugin. It needs a bit more cross browser friendliness though.

How do you convert a byte array to a hexadecimal string in C?

What complex solutions!
Malloc and sprints and casts oh my. (OZ quote)
and not a single rem anywhere. Gosh

How about something like this?

main()
{
    // the value
    int value = 16;

    // create a string array with a '\0' ending ie. 0,0,0
    char hex[]= {0,0,'\0'}; 
    char *hex_p=hex;

    //a working variable
    int TEMP_int=0;

    // get me how many 16s are in this code
    TEMP_int=value/16;

    // load the first character up with 
    // 48+0 gives you ascii 0, 55+10 gives you ascii A
    if (TEMP_int<10) {*hex_p=48+TEMP_int;}
        else {*hex_p=55+TEMP_int;}

    // move that pointer to the next (less significant byte)<BR>
    hex_p++;

    // get me the remainder after I have divied by 16
    TEMP_int=value%16;

    // 48+0 gives you ascii 0, 55+10 gives you ascii A
    if (TEMP_int<10) {*hex_p=48+TEMP_int;}
        else {*hex_p=55+TEMP_int;}

    // print the result
    printf("%i , 0x%s",value,hex);

}

How to do a regular expression replace in MySQL?

I recently wrote a MySQL function to replace strings using regular expressions. You could find my post at the following location:

http://techras.wordpress.com/2011/06/02/regex-replace-for-mysql/

Here is the function code:

DELIMITER $$

CREATE FUNCTION  `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN 
 DECLARE temp VARCHAR(1000); 
 DECLARE ch VARCHAR(1); 
 DECLARE i INT;
 SET i = 1;
 SET temp = '';
 IF original REGEXP pattern THEN 
  loop_label: LOOP 
   IF i>CHAR_LENGTH(original) THEN
    LEAVE loop_label;  
   END IF;
   SET ch = SUBSTRING(original,i,1);
   IF NOT ch REGEXP pattern THEN
    SET temp = CONCAT(temp,ch);
   ELSE
    SET temp = CONCAT(temp,replacement);
   END IF;
   SET i=i+1;
  END LOOP;
 ELSE
  SET temp = original;
 END IF;
 RETURN temp;
END$$

DELIMITER ;

Example execution:

mysql> select regex_replace('[^a-zA-Z0-9\-]','','2my test3_text-to. check \\ my- sql (regular) ,expressions ._,');

Convert Java string to Time, NOT Date

Joda-Time & java.time

Both Joda-Time and java.time (new in Java 8) offer a LocalTime class to represent a time-of-day without any date or time zone.

Example code, identical code for both java.time and Joda-Time.

LocalTime localTime = new LocalTime( "14:40" );
LocalTime deadline = new LocalTime( "15:30" );
boolean meetsDeadline = localTime.isBefore( deadline );

enter image description here


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

C programming in Visual Studio

Yes, you very well can learn C using Visual Studio.

Visual Studio comes with its own C compiler, which is actually the C++ compiler. Just use the .c file extension to save your source code.

You don't have to be using the IDE to compile C. You can write the source in Notepad, and compile it in command line using Developer Command Prompt which comes with Visual Studio.

Open the Developer Command Prompt, enter the directory you are working in, use the cl command to compile your C code.

For example, cl helloworld.c compiles a file named helloworld.c.

Refer this for more information: Walkthrough: Compiling a C Program on the Command Line

Hope this helps

Undo scaffolding in Rails

First, if you have already run the migrations generated by the scaffold command, you have to perform a rollback first.

rake db:rollback

You can create scaffolding using:

rails generate scaffold MyFoo 

(or similar), and you can destroy/undo it using

rails destroy scaffold MyFoo

That will delete all the files created by generate, but not any additional changes you may have made manually.

How to close Android application?

public class CloseAppActivity extends AppCompatActivity
{
    public static final void closeApp(Activity activity)
    {
        Intent intent = new Intent(activity, CloseAppActivity.class);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
        activity.startActivity(intent);
    }

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

and in manifest:

<activity
     android:name=".presenter.activity.CloseAppActivity"
     android:noHistory="true"
     android:clearTaskOnLaunch="true"/>

Then you can call CloseAppActivity.closeApp(fromActivity) and application will be closed.

Load a HTML page within another HTML page

How about

<button onclick="window.open('http://www.google.com','name','width=200,height=200');">Open</button>

How to install easy_install in Python 2.7.1 on Windows 7

I know this isn't a direct answer to your question but it does offer one solution to your problem. Python 2.7.9 includes PIP and SetupTools, if you update to this version you will have one solution to your problem.

Unknown Column In Where Clause

See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html

"A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses."

(...)

It is not permissible to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section B.5.4.4, “Problems with Column Aliases”.

Transparent background in JPEG image

How can I set a transparent background on JPEG image?

If you intend to keep the image as a JPEG then you can't. As others have suggested, convert it to PNG and add an alpha channel.

How do I turn off Unicode in a VC++ project?

Burgos has the right answer. Just to clarify, the Character Set should be changed to "Not Set".

pySerial write() won't take my string

You have found the root cause. Alternately do like this:

ser.write(bytes(b'your_commands'))

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Find a pair of elements from an array whose sum equals a given number

There are 3 approaches to this solution:

Let the sum be T and n be the size of array

Approach 1:
The naive way to do this would be to check all combinations (n choose 2). This exhaustive search is O(n2).

Approach 2: 
 A better way would be to sort the array. This takes O(n log n)
Then for each x in array A, use binary search to look for T-x. This will take O(nlogn).
So, overall search is  O(n log n)

Approach 3 :
The best way would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion.
Then for every x, we can just look up its complement, T-x, which is O(1).
Overall the run time of this approach is O(n).


You can refer more here.Thanks.


Wait for a void async method

do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.

You can also wait on a Task that returns from your void async

How to get memory available or used in C#

Look here for details.

private PerformanceCounter cpuCounter;
private PerformanceCounter ramCounter;
public Form1()
{
    InitializeComponent();
    InitialiseCPUCounter();
    InitializeRAMCounter();
    updateTimer.Start();
}

private void updateTimer_Tick(object sender, EventArgs e)
{
    this.textBox1.Text = "CPU Usage: " +
    Convert.ToInt32(cpuCounter.NextValue()).ToString() +
    "%";

    this.textBox2.Text = Convert.ToInt32(ramCounter.NextValue()).ToString()+"Mb";
}

private void Form1_Load(object sender, EventArgs e)
{
}

private void InitialiseCPUCounter()
{
    cpuCounter = new PerformanceCounter(
    "Processor",
    "% Processor Time",
    "_Total",
    true
    );
}

private void InitializeRAMCounter()
{
    ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);

}

If you get value as 0 it need to call NextValue() twice. Then it gives the actual value of CPU usage. See more details here.

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

Django: Get list of model fields?

Just to add, I am using self object, this worked for me:

[f.name for f in self.model._meta.get_fields()]

Concatenate text files with Windows command line, dropping leading lines

I would put this in a comment to ghostdog74, except my rep is too low, so here goes.

more +2 file2.txt > temp
This code will actually ignore rows 1 and 2 of the file. OP wants to keep all rows from the first file (to maintain the header row), and then exclude the first row (presumably the same header row) on the second file, so to exclude only the header row OP should use more +1.

type temp file1.txt > out.txt

It is unclear what order results from this code. Is temp appended to file1.txt (as desired), or is file1.txt appended to temp (undesired as the header row would be buried in the middle of the resulting file).

In addition, these operations take a REALLY LONG TIME with large files (e.g. 300MB)

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I used file_get_contents using stream_create_context and it works fine:

$postdataStr = http_build_query($postdataArr);

$context_options = array (
        'http' => array (    <blink> // this will allways be http!!!</blink>
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($postdataArr) . "\r\n"
                . "Cookie: " . $cookies."\r\n"
            'content' => $postdataStr
            )
        );

$context = stream_context_create($context_options);
$HTTPSReq = file_get_contents('https://www.example.com/', false, $context);

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

How to connect android emulator to the internet

What worked for me on android 4.4 was to do the following: Settings -> Wireless & Networks -> Mobile networks -> Make sure both Data enabled and Data roaming is enabled.

How do I use Maven through a proxy?

Some times you need to add other <proxy></proxy> tags, and specify the https in the protocol tags: <protocol>https</protocol>

Vue 2 - Mutating props vue-warn

Vue just warns you: you change the prop in the component, but when parent component re-renders, "list" will be overwritten and you lose all your changes. So it is dangerous to do so.

Use computed property instead like this:

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    computed: {
        listJson: function(){
            return JSON.parse(this.list);
        }
    }
});

Javascript: Call a function after specific time period

You can use JavaScript Timing Events to call function after certain interval of time:

This shows the alert box after 3 seconds:

setInterval(function(){alert("Hello")},3000);

You can use two method of time event in javascript.i.e.

  1. setInterval(): executes a function, over and over again, at specified time intervals
  2. setTimeout() : executes a function, once, after waiting a specified number of milliseconds

How to remove the last element added into the List?

I would rather use Last() from LINQ to do it.

rows = rows.Remove(rows.Last());

or

rows = rows.Remove(rows.LastOrDefault());

Border Radius of Table is not working

Just add overflow:hidden to the table with border-radius.

.tablewithradius {
  overflow:hidden ;
  border-radius: 15px;
}

How to set up subdomains on IIS 7

If your computer can't find the IP address associated with SUBDOMAIN1.example.COM, it will not find the site.

You need to either change your hosts file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).

Split text with '\r\n'

This worked for me.

using System.IO;

//  

    string readStr = File.ReadAllText(file.FullName);          
    string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

I know this answer is not directly related to this questions' issue but in some cases the "Uncaught ReferenceError: google is not defined" issue will occur if your js file is being called prior to the google maps api you're using...so DON'T DO this:

<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

Adding placeholder text to textbox

txtUsuario.Attributes.Add("placeholder", "Texto");

How to check if a socket is connected/disconnected in C#?

Use Socket.Connected Property.

--UPDATE--

As Paul Turner answered Socket.Connected cannot be used in this situation. You need to poll connection every time to see if connection is still active. See 2

Return rows in random order

SELECT * FROM table
ORDER BY NEWID()

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

font size in html code

just write the css attributes in a proper manner i.e:

font-size:35px;

Ansible - Save registered variable to file

I am using Ansible 1.9.4 and this is what worked for me -

- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"

static constructors in C++? I need to initialize private static objects

When trying to compile and use class Elsewhere (from Earwicker's answer) I get:

error LNK2001: unresolved external symbol "private: static class StaticStuff Elsewhere::staticStuff" (?staticStuff@Elsewhere@@0VStaticStuff@@A)

It seems is not possible to initialize static attributes of non-integer types without putting some code outside the class definition (CPP).

To make that compile you can use "a static method with a static local variable inside" instead. Something like this:

class Elsewhere
{
public:
    static StaticStuff& GetStaticStuff()
    {
        static StaticStuff staticStuff; // constructor runs once, single instance
        return staticStuff;
    }
};

And you may also pass arguments to the constructor or initialize it with specific values, it is very flexible, powerfull and easy to implement... the only thing is you have a static method containing a static variable, not a static attribute... syntaxis changes a bit, but still useful. Hope this is useful for someone,

Hugo González Castro.

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

Using multiprocessing.Process with a maximum number of simultaneous processes

I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # simulate a time-consuming task by sleeping
    time.sleep(5)
    # `release` will add 1 to `sema`, allowing other 
    # processes blocked on it to continue
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        # once 20 processes are running, the following `acquire` call
        # will block the main process since `sema` has been reduced
        # to 0. This loop will continue only after one or more 
        # previously created processes complete.
        sema.acquire()
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The following code is more structured since it acquires and releases sema in the same function. However, it will consume too much resources if total_task_num is very large:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # `sema` is acquired and released in the same
    # block of code here, making code more readable,
    # but may lead to problem.
    sema.acquire()
    time.sleep(5)
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        # the following line won't block after 20 processes
        # have been created and running, instead it will carry 
        # on until all 1000 processes are created.
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The above code will create total_task_num processes but only concurrency processes will be running while other processes are blocked, consuming precious system resources.

No 'Access-Control-Allow-Origin' header in Angular 2 app

I also encountered the same problem and passed the following way to solve this problem.

step 1:

$ npm install --save-dev http-proxy-middleware

step 2:

add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .

//file: bs-config.js
var proxyMiddleware = require('http-proxy-middleware');

module.exports = {
    server: {
        middleware: {
            1: proxyMiddleware('/example-api', {
                target: 'http://api.example.com',
                changeOrigin: true,
                pathRewrite: {
                '^/news-at-api': '/api'
                }
            })
        }
    }
};

hope this helps.

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

Python foreach equivalent

Sure. A for loop.

for f in pets:
    print f

Switch tabs using Selenium WebDriver with Java

Please see below:

WebDriver driver = new FirefoxDriver();

driver.manage().window().maximize();
driver.get("https://www.irctc.co.in/");
String oldTab = driver.getWindowHandle();

//For opening window in New Tab
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("Hotels & Lounge")).sendKeys(selectLinkOpeninNewTab);

// Perform Ctrl + Tab to focus on new Tab window
new Actions(driver).sendKeys(Keys.chord(Keys.CONTROL, Keys.TAB)).perform();

// Switch driver control to focused tab window
driver.switchTo().window(oldTab);

driver.findElement(By.id("textfield")).sendKeys("bangalore");

Hope this is helpful!

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

JavaScript backslash (\) in variables is causing an error

The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx

How to check if element in groovy array/hash/collection/list?

If you really want your includes method on an ArrayList, just add it:

ArrayList.metaClass.includes = { i -> i in delegate }

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  http://www.springframework.org/schema/cache 
        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

        <mvc:annotation-driven/>
        <context:component-scan base-package="com.testpoc.controller"/>

        <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property>
            <property name="prefix">
                <value>/WEB-INF/pages/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>

</beans>

Sorting A ListView By Column

i would recommend you to you datagridview, for heavy stuff.. it's include a lot of auto feature listviwe does not

Detect changed input text box

onkeyup, onpaste, onchange, oninput seems to be failing when the browser performs autofill on the textboxes. To handle such a case include "autocomplete='off'" in your textfield to prevent browser from autofilling the textbox,

Eg,

<input id="inputDatabaseName" autocomplete='off' onchange="check();"
 onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />

<script>
     function check(){
          alert("Input box changed");
          // Things to do when the textbox changes
     }
</script>

How can I get a list of all classes within current module in Python?

Go to Python Interpreter. type help ('module_name') , then press Enter. e.g. help('os') . Here, I've pasted one part of the output below:

class statvfs_result(__builtin__.object)
     |  statvfs_result: Result from statvfs or fstatvfs.
     |
     |  This object may be accessed either as a tuple of
     |    (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),
     |  or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.
     |
     |  See os.statvfs for more information.
     |
     |  Methods defined here:
     |
     |  __add__(...)
     |      x.__add__(y) <==> x+y
     |
     |  __contains__(...)
     |      x.__contains__(y) <==> y in x

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

The current answer is incomplete. Installing libv4l-dev creates a /usr/include/linux/videodev2.h but doesn't solve the stated problem of not being able to find linux/videodev.h. The library does ship header files for compatibility, but fails to put them where applications will look for them.

sudo apt-get install libv4l-dev
cd /usr/include/linux
sudo ln -s ../libv4l1-videodev.h videodev.h

This provides a linux/videodev.h, and of the right version (1).

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

Python "expected an indented block"

There are several issues:

  1. elif option == 2: and the subsequent elif-else should be aligned with the second if option == 1, not with the for.

  2. The for x in range(x, 1, 1): is missing a body.

  3. Since "option 1 (count)" requires a second input, you need to call input() for the second time. However, for sanity's sake I urge you to store the result in a second variable rather than repurposing option.

  4. The comparison in the first line of your code is probably meant to be an assignment.

You'll discover more issues once you're able to run your code (you'll need a couple more input() calls, one of the range() calls will need attention etc).

Lastly, please don't use the same variable as the loop variable and as part of the initial/terminal condition, as in:

            for x in range(1, x, 1):
                print x

It may work, but it is very confusing to read. Give the loop variable a different name:

            for i in range(1, x, 1):
                print i

How can I order a List<string>?

List<string> myCollection = new List<string>()
{
    "Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};

myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
    Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}

output: Abdi 3 Alex 2 Bob 4

Docker: How to use bash with an Alpine based docker image?

Try using RUN /bin/sh instead of bash.

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Spring Boot: Cannot access REST Controller on localhost (404)

It also works if we use as follows:

@SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })

How to make IPython notebook matplotlib plot inline

If your matplotlib version is above 1.4, it is also possible to use

IPython 3.x and above

%matplotlib notebook

import matplotlib.pyplot as plt

older versions

%matplotlib nbagg

import matplotlib.pyplot as plt

Both will activate the nbagg backend, which enables interactivity.

Example plot with the nbagg backend

How to update one file in a zip archive

I know this is old question, but I wanted to do the same. Update a file in zip archive. And none of the above answers really helped me.

Here is what I did. Created temp directory abc. Copied file.zip to abc and extracted the file in that directory. I edited the file I wanted to edit. Then while being in abc, ran the following command

user@host ~/temp/abc $ zip -u file.zip
updating: content/js/ (stored 0%)
updating: content/js/moduleConfig.js (deflated 69%)

-u switch will look for changed/new files and will add to the zip archive.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Which is the correct C# infinite loop, for (;;) or while (true)?

To rehash a couple of old jokes:

  1. Don't use "for (;;) {}" — it makes the statement cry.
  2. Unless, of course, you "#define EVER ;;".

Is there a better way to compare dictionary values

If your dictionaries are deeply nested and if they contain different types of collections, you could convert them to json string and compare.

import json
match = (json.dumps(dict1) == json.dumps(dict2))

caveat- this solution may not work if your dictionaries have binary strings in the values as this is not json serializable

How to get files in a relative path in C#

string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");

The first parameter is the path. The second is the search pattern you want to use.

Getting content/message from HttpResponseMessage

If you want to cast it to specific type (e.g. within tests) you can use ReadAsAsync extension method:

object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));

or following for synchronous code:

object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;

Update: there is also generic option of ReadAsAsync<> which returns specific type instance instead of object-declared one:

YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();

How to take column-slices of dataframe in pandas

And if you came here looking for slicing two ranges of columns and combining them together (like me) you can do something like

op = df[list(df.columns[0:899]) + list(df.columns[3593:])]
print op

This will create a new dataframe with first 900 columns and (all) columns > 3593 (assuming you have some 4000 columns in your data set).

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

Convert number of minutes into hours & minutes using PHP

$m = 250;

$extraIntH = intval($m/60);

$extraIntHs = ($m/60);             // float value   

$whole = floor($extraIntHs);      //  return int value 1

$fraction = $extraIntHs - $whole; // Total - int = . decimal value

$extraIntHss =  ($fraction*60); 

$TotalHoursAndMinutesString  =  $extraIntH."h ".$extraIntHss."m";

How can I access an internal class from an external assembly?

I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

 Install-Package Mono.Cecil

And the code like:

static readonly string[] s_toInject = {
  // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
  "MyAssembly"
};

static void Main(string[] args) {
  const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";

   var parameters = new ReaderParameters();
   var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
   foreach (var toInject in s_toInject) {
     var ca = new CustomAttribute(
       asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                      typeof(string)})));
     ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
     asm.Assembly.CustomAttributes.Add(ca);
   }
   asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
   // note if the assembly is strongly-signed you need to resign it like
   // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
   //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
   // });
}

Determine version of Entity Framework I am using?

can check it in packages.config file.

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.0.2" targetFramework="net40-Client" />
</packages> 

Child element click event trigger the parent click event

You need to use event.stopPropagation()

Live Demo

$('#childDiv').click(function(event){
    event.stopPropagation();
    alert(event.target.id);
});?

event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

How can I create a temp file with a specific extension with .NET?

Based on answers I found from the internet, I come to my code as following:

public static string GetTemporaryFileName()
{       
    string tempFilePath = Path.Combine(Path.GetTempPath(), "SnapshotTemp");
    Directory.Delete(tempFilePath, true);
    Directory.CreateDirectory(tempFilePath);
    return Path.Combine(tempFilePath, DateTime.Now.ToString("MMddHHmm") + "-" + Guid.NewGuid().ToString() + ".png");
}

And as C# Cookbook by Jay Hilyard, Stephen Teilhet pointed in Using a Temporary File in Your Application:

  • you should use a temporary file whenever you need to store information temporarily for later retrieval.

  • The one thing you must remember is to delete this temporary file before the application that created it is terminated.

  • If it is not deleted, it will remain in the user’s temporary directory until the user manually deletes it.

Find if a textbox is disabled or not using jquery

 if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
 {

    // code when element is disabled

  }

how to use ng-option to set default value of select element

So assuming that object is in your scope:

<div ng-controller="MyCtrl">
  <select ng-model="prop.value" ng-options="v for v in prop.values">
  </select>
</div>

 

function MyCtrl($scope) {
  $scope.prop = {
    "type": "select", 
    "name": "Service",
    "value": "Service 3", 
    "values": [ "Service 1", "Service 2", "Service 3", "Service 4"] 
  };
}

Working Plunkr: http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g

Fit Image in ImageButton in Android

I want them to cover 75% of the button area.

Use android:padding="20dp" (adjust the padding as needed) to control how much the image takes up on the button.

but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?

Use a android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling.

All of these attributes can be set in code on each ImageButton at runtime. However, it is much easier to set and preview in xml in my opinion.

Also, do not use sp for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp dimensions will be larger than your intended if the user has a "large" text setting. Use dp instead, as it is not scaled by the user's text size preference.

Here's a snippet of what each button should look like:

    <ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:scaleType="fitCenter" />

Sample Button

What's the difference between Git Revert, Checkout and Reset?

Reset - On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.

Revert - Reverting undoes a commit by creating a new commit. This is a safe way to undo changes, as it has no chance of re-writing the commit history. Contrast this with git reset, which does alter the existing commit history. For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch.

You can have a look on this link- Reset, Checkout and Revert

Determining the version of Java SDK on the Mac

In /System/Library/Frameworks/JavaVM.framework/Versions you'll see all the installed JDKs. There is a symbolic link named CurrentJDK pointing the active JDK.

How to call Stored Procedures with EntityFramework?

This is what I recently did for my Data Visualization Application which has a 2008 SQL Database. In this example I am recieving a list returned from a stored procedure:

public List<CumulativeInstrumentsDataRow> GetCumulativeInstrumentLogs(RunLogFilter filter)
    {
        EFDbContext db = new EFDbContext();
        if (filter.SystemFullName == string.Empty)
        {
            filter.SystemFullName = null;
        }
        if (filter.Reconciled == null)
        {
            filter.Reconciled = 1;
        }
        string sql = GetRunLogFilterSQLString("[dbo].[rm_sp_GetCumulativeInstrumentLogs]", filter);
        return db.Database.SqlQuery<CumulativeInstrumentsDataRow>(sql).ToList();
    }

And then this extension method for some formatting in my case:

public string GetRunLogFilterSQLString(string procedureName, RunLogFilter filter)
        {
            return string.Format("EXEC {0} {1},{2}, {3}, {4}", procedureName, filter.SystemFullName == null ? "null" : "\'" + filter.SystemFullName + "\'", filter.MinimumDate == null ? "null" : "\'" + filter.MinimumDate.Value + "\'", filter.MaximumDate == null ? "null" : "\'" + filter.MaximumDate.Value + "\'", +filter.Reconciled == null ? "null" : "\'" + filter.Reconciled + "\'");

        }

How copy data from Excel to a table using Oracle SQL Developer

None of these options show up for me. The way to paste data from Excel is as follows:

  • Add an extra column to the left of your spreadsheet data (if you don't have row numbers showing in PL/SQL Developer you may not have to have an extra empty column to the left).

  • Copy the rows of data from your spreadsheet including the empty column.

  • In PL/SQL Developer, open your table in edit mode. You can right-click the table name in the object browser and select Edit Data or write your own select statement that includes the rowid and click the lock icon. Be sure your columns are ordered the same as in your spreadsheet.

  • Here's the part that took me forever to figure out: click on the left side of the first empty row to highlight it. It will not work if you don't have the first empty row highlighted.

  • Paste as usual using Ctrl+V or right-click Paste.

I couldn't find this info anywhere when I needed it, so I wanted to be sure to post it.

numbers not allowed (0-9) - Regex Expression in javascript

Simply:

/^([^0-9]*)$/

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/. It will let you easily test out a regex.

Node.js throws "btoa is not defined" error

The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.

If you need to convert to Base64 you could do so using Buffer:

console.log(Buffer.from('Hello World!').toString('base64'));

Reverse (assuming the content you're decoding is a utf8 string):

console.log(Buffer.from(b64Encoded, 'base64').toString());

Note: prior to Node v4, use new Buffer rather than Buffer.from.

Why would we call cin.clear() and cin.ignore() after reading input?

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

From my answer here, thought this might be useful:

I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:

Step 1: Identify the Database Version

$ mysql --version

You'll see some output like this with MySQL:

$ mysql  Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using  EditLine wrapper

Or output like this for MariaDB:

mysql  Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1

Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.

Step 2: Stopping the Database Server

To change the root password, you have to shut down the database server beforehand.

You can do that for MySQL with:

$ sudo systemctl stop mysql

And for MariaDB with:

$ sudo systemctl stop mariadb

Step 3: Restarting the Database Server Without Permission Checking

If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.

To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.

Start the database without loading the grant tables or enabling networking:

$ sudo mysqld_safe --skip-grant-tables --skip-networking &

The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.

Now you can connect to the database as the root user, which should not ask for a password.

$ mysql -u root

You'll immediately see a database shell prompt instead.

MySQL Prompt

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

MariaDB Prompt

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Now that you have root access, you can change the root password.

Step 4: Changing the Root Password

mysql> FLUSH PRIVILEGES;

Now we can actually change the root password.

For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:

mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

Make sure to replace new_password with your new password of choice.

Note: If the ALTER USER command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET to reset the root password instead.

[IMPORTANT] This is the specific line that fixed my particular issue:

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';

Remember to reload the grant tables after this.

In either case, you should see confirmation that the command has been successfully executed.

Query OK, 0 rows affected (0.00 sec)

The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.

Step 5: Restart the Database Server Normally

The tutorial goes into some further steps to restart the database, but the only piece I used was this:

For MySQL, use: $ sudo systemctl start mysql

For MariaDB, use:

$ sudo systemctl start mariadb

Now you can confirm that the new password has been applied correctly by running:

$ mysql -u root -p

The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.

Conclusion

You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.

Counting repeated elements in an integer array

with O(n log(n))

int[] arr1; // your given array
int[] arr2 = new int[arr1.length];
Arrays.sort(arr1);

for (int i = 0; i < arr1.length; i++) {
    arr2[i]++;
    if (i+1 < arr1.length) 
    {
        if (arr1[i] == arr1[i + 1]) {
            arr2[i]++;
            i++;
        }
    }
}

for (int i = 0; i < arr1.length; i++) {
    if(arr2[i]>0)
    System.out.println(arr1[i] + ":" + arr2[i]);
}

Swift - iOS - Dates and times in different format

let dateString = "1970-01-01T13:30:00.000Z"
let formatter = DateFormatter()

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.date(from: String(dateString.dropLast(5)))!
formatter.dateFormat = "hh.mma"
print(formatter.string(from: date))

if You notice I have set .dateFormat = "hh.mma"by this you will get time only. Result:01.30PM

How to get substring of NSString?

Here's a slightly less complicated answer:

NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];

See also substringWithRange and substringFromIndex

How to compile LEX/YACC files on Windows?

I was having the same problem, it has a very simple solution.
Steps for executing the 'Lex' program:

  1. Tools->'Lex File Compiler'
  2. Tools->'Lex Build'
  3. Tools->'Open CMD'
  4. Then in command prompt type 'name_of_file.exe' example->'1.exe'
  5. Then entering the whole input press Ctrl + Z and press Enter.

Example