Programs & Examples On #Kcachegrind

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

How to decrypt Hash Password in Laravel

Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).

The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.

Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).

For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.

IsNumeric function in c#

public bool IsNumeric(string value)
{
    return value.All(char.IsNumber);
}

Install MySQL on Ubuntu without a password prompt

Use:

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"

How to create an integer-for-loop in Ruby?

x.times do |i|
    something(i+1)
end

How to get distinct values from an array of objects in JavaScript?

Using Lodash

var array = [
    { "name": "Joe", "age": 17 },
    { "name": "Bob", "age": 17 },
    { "name": "Carl", "age": 35 }
];

_.chain(array).map('age').unique().value();

Returns [17,35]

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

NSCameraUsageDescription in iOS 10.0 runtime crash?

You have to add this below key in info.plist.

NSCameraUsageDescription Or Privacy - Camera usage description

And add description of usage.

Detailed screenshots are available in this link

Collections sort(List<T>,Comparator<? super T>) method example

This might be simplest way -

Collections.sort(listOfStudent,new Comparator<Student>(){
                     public int compare(Student s1,Student s2){
                           // Write your logic here.
                     }});

Using Java 8(lambda expression) -

listOfStudent.sort((s1, s2) -> s1.age - s2.age); 

How to convert an int value to string in Go?

You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (
    "fmt"
)

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)
    fmt.Println(s)
}

how to run vibrate continuously in iphone?

There are numerous examples that show how to do this with a private CoreTelephony call: _CTServerConnectionSetVibratorState, but it's really not a sensible course of action since your app will get rejected for abusing the vibrate feature like that. Just don't do it.

What regex will match every character except comma ',' or semi-colon ';'?

[^,;]+         

You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:

[,;]+

scrollable div inside container

I created an enhanced version, based on Trey Copland's fiddle, that I think is more like what you wanted. Added here for future reference to those who come here later. Fiddle example

    <body>
<style>
.modal {
  height: 390px;
  border: 5px solid green;
}
.heading {
  padding: 10px;
}
.content {
  height: 300px;
  overflow:auto;
  border: 5px solid red;
}
.scrollable {
  height: 1200px;
  border: 5px solid yellow;

}
.footer {
  height: 2em;
  padding: .5em;
}
</style>
      <div class="modal">
          <div class="heading">
            <h4>Heading</h4>
          </div>
          <div class="content">
              <div class="scrollable" >hello</div>
          </div>
          <div class="footer">
            Footer
          </div>
      </div>
    </body>

AES vs Blowfish for file encryption

Both algorithms (AES and twofish) are considered very secure. This has been widely covered in other answers.

However, since AES is much widely used now in 2016, it has been specifically hardware-accelerated in several platforms such as ARM and x86. While not significantly faster than twofish before hardware acceleration, AES is now much faster thanks to the dedicated CPU instructions.

Scroll to a specific Element Using html

If you use Jquery you can add this to your javascript:

$('.smooth-goto').on('click', function() {  
    $('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
    return false;
});

Also, don't forget to add this class to your a tag too like this:

<a href="#id-of-element" class="smooth-goto">Text</a>

Google Maps API v3 adding an InfoWindow to each marker

The only way I could finally get this to work was by creating an array in JavaScript. The array elements reference the various info-windows (one info-window is created for each marker on the map). Each array element contains the unique text for its appropriate map marker. I defined the JavaScript event for each info-window based on the array element. And when the event fires, I use the "this" keyword to reference the array element to reference the appropriate value to display.

var map = new google.maps.Map(document.getElementById('map-div'), mapOptions);
zipcircle = [];
for (var zip in zipmap) {
    var circleoptions = {
        strokeOpacity: 0.8,
        strokeWeight: 1,
        fillOpacity: 0.35,
        map: map,
        center: zipmap[zip].center,
        radius: 100
    };
    zipcircle[zipmap[zip].zipkey] = new google.maps.Circle(circleoptions);
    zipcircle[zipmap[zip].zipkey].infowindowtext = zipmap[zip].popuptext;
    zipcircle[zipmap[zip].zipkey].infowindow = new google.maps.InfoWindow();
    google.maps.event.addListener(zipcircle[zipmap[zip].zipkey], 'click', function() {
        this.infowindow.setContent(this.infowindowtext);
        this.infowindow.open(map, this);
    });
}

How to export and import a .sql file from command line with options?

If you're already running the SQL shell, you can use the source command to import data:

use databasename;
source data.sql;

How to install mongoDB on windows?

Step by Step Solution for windows 32 bit

  1. Download msi file for windows 32 bit.
  2. Double click Install it, choose custom and browse the location where ever you have to install(personally i have create the mongodb folder in E drive and install it there).
  3. Ok,now you have to create the data\db two folder where ever create it, i've created it in installed location root e.g on E:\
  4. Now link the mongod to these folder for storing data use this command or modify according to your requirement go to using cmd E:\mongodb\bin and after that write in console mongod --dbpath E:\data it will link.
  5. Now navigate to E:\mongodb\bin and write mongod using cmd.
  6. Open another cmd by right click and run as admin point to your monogodb installed directory and then to bin just like E:\mongodb\bin and write this mongo.exe
  7. Next - write db.test.save({Field:'Hello mongodb'}) this command will insert the a field having name Field and its value Hello mongodb.
  8. Next, check the record db.test.find() and press enter you will find the record that you have recently entered.

How to increase buffer size in Oracle SQL Developer to view all records?

Select Tools > Preferences > Database / Advanced

There is an input field for Sql Array Fetch Size but it only allows setting a max of 500 rows.

How to install the Six module in Python2.7

You need to install this

https://pypi.python.org/pypi/six

If you still don't know what pip is , then please also google for pip install

Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/

TypeError: coercing to Unicode: need string or buffer

For the less specific case (not just the code in the question - since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.

For example:

os.path.exists(arg)  
os.stat(arg)

Will raise this exception when arg is None.

jQuery remove special characters from string and more

this will remove all the special character

 str.replace(/[_\W]+/g, "");

this is really helpful and solve my issue. Please run the below code and ensure it works

_x000D_
_x000D_
var str="hello world !#to&you%*()";_x000D_
console.log(str.replace(/[_\W]+/g, ""));
_x000D_
_x000D_
_x000D_

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);
    }
}

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
            _input.nativeElement.focus();
        }, 0);
    }
}

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

How to hide the bar at the top of "youtube" even when mouse hovers over it?

Open youtube video. Click on share option. In share option click on embed tag. You can see in embed tag there is some check box. Unchecked on show video title and player actions. After this just copy frame tag.

<iframe width="100%" height="350" src="https://www.youtube.com/embed/uqhnxAjK7qY?autoplay=1&showinfo=0" frameborder="0" allowfullscreen></iframe>

Sleep function in ORACLE

It would be better to implement a synchronization mechanism. The easiest is to write a file after the first file is complete. So you have a sentinel file.

So the external programs looks for the sentinel file to exist. When it does it knows that it can safely use the data in the real file.

Another way to do this, which is similar to how some browsers do it when downloading files, is to have the file named base-name_part until the file is completely downloaded and then at the end rename the file to base-name. This way the external program can't "see" the file until it is complete. This way wouldn't require rewrite of the external program. Which might make it best for this situation.

How to select multiple rows filled with constants?

Here is how I populate static data in Oracle 10+ using a neat XML trick.

create table prop
(ID NUMBER,
 NAME varchar2(10),
 VAL varchar2(10),
 CREATED timestamp,
 CONSTRAINT PK_PROP PRIMARY KEY(ID)
);

merge into Prop p
using (
select 
  extractValue(value(r), '/R/ID') ID,
  extractValue(value(r), '/R/NAME') NAME,
  extractValue(value(r), '/R/VAL') VAL
from
(select xmltype('
<ROWSET>
   <R><ID>1</ID><NAME>key1</NAME><VAL>value1</VAL></R>
   <R><ID>2</ID><NAME>key2</NAME><VAL>value2</VAL></R>
   <R><ID>3</ID><NAME>key3</NAME><VAL>value3</VAL></R>
</ROWSET>
') xml from dual) input,
 table(xmlsequence(input.xml.extract('/ROWSET/R'))) r
) p_new
on (p.ID = p_new.ID)
when not matched then
insert
(ID, NAME, VAL, CREATED)
values
( p_new.ID, p_new.NAME, p_new.VAL, SYSTIMESTAMP );

The merge only inserts the rows that are missing in the original table, which is convenient if you want to rerun your insert script.

position fixed is not working

Another cause could be a parent container that contains the CSS animation property. That's what it was for me.

Function or sub to add new row and data to table

Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
        table.ListRows.Add Position:=1
        Set lastRow = table.ListRows(1).Range
    Else
        Set lastRow = table.ListRows(table.ListRows.Count).Range
    End If
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

Strip HTML from Text JavaScript

Using Jquery:

function stripTags() {
    return $('<p></p>').html(textToEscape).text()
}

Move an array element from one array position to another

This is based on @Reid's solution. Except:

  • I'm not changing the Array prototype.
  • Moving an item out of bounds to the right does not create undefined items, it just moves the item to the right-most position.

Function:

function move(array, oldIndex, newIndex) {
    if (newIndex >= array.length) {
        newIndex = array.length - 1;
    }
    array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
    return array;
}

Unit tests:

describe('ArrayHelper', function () {
    it('Move right', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 0, 1);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    })
    it('Move left', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, 0);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    });
    it('Move out of bounds to the left', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, -2);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    });
    it('Move out of bounds to the right', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, 4);
        assert.equal(array[0], 1);
        assert.equal(array[1], 3);
        assert.equal(array[2], 2);
    });
});

Comparing Arrays of Objects in JavaScript

Please try this one:

function used_to_compare_two_arrays(a, b)
{
  // This block will make the array of indexed that array b contains a elements
  var c = a.filter(function(value, index, obj) {
    return b.indexOf(value) > -1;
  });

  // This is used for making comparison that both have same length if no condition go wrong 
  if (c.length !== a.length) {
    return 0;
  } else{
    return 1;
  }
}

CSS media queries: max-width OR max-height

There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:

@media only screen 
and (min-width : 415px){
    /* Styles */
}

@media only screen 
and (min-width : 769px){
    /* Styles */
}

@media only screen 
and (min-width : 992px){
    /* Styles */
}

But if you are writing media queries for smaller device first, then it would be something like:

@media only screen 
and (max-width : 991px){
    /* Styles */
}

@media only screen 
and (max-width : 768px){
    /* Styles */
}

@media only screen 
and (max-width : 414px){
    /* Styles */
}

Android Studio 3.0 Flavor Dimension Issue

in KotlinDSL you can use like this :

flavorDimensions ("PlaceApp")
productFlavors {
    create("tapsi") {
        setDimension("PlaceApp")
        buildConfigField("String", "API_BASE_URL", "https://xxx/x/x/")
    }

}

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

How do I view an older version of an SVN file?

To directly answer the question of how to "get a copy of that file":

svn cat -r 666 file > file_r666

then you can view the newly created file_r666 with any viewer or comparison program, e.g.

kompare file_r666 file

nicely shows the differences.

I posted the answer because the accepted answer's commands do actually not give a copy of the file and because svn cat -r 666 file | vim does not work with my system (Vim: Error reading input, exiting...)

Counting array elements in Perl

It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:

#!/usr/bin/perl

use strict;
use warnings;

my %sparse;

@sparse{0, 5, 23} = (1 .. 3);

print "there are ", scalar keys %sparse, " items in the sparse array\n",
    map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;

The keys function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.

You must also remember to use the delete function to remove items from the sparse array (just setting their value to undef is not enough).

xls to csv converter

First read your excel spreadsheet into pandas, below code will import your excel spreadsheet into pandas as a OrderedDict type which contain all of your worksheet as dataframes. Then simply use worksheet_name as a key to access specific worksheet as a dataframe and save only required worksheet as csv file by using df.to_csv(). Hope this will workout in your case.

import pandas as pd
df = pd.read_excel('YourExcel.xlsx', sheet_name=None)
df['worksheet_name'].to_csv('YourCsv.csv')  

If your Excel file contain only one worksheet then simply use below code:

import pandas as pd
df = pd.read_excel('YourExcel.xlsx')
df.to_csv('YourCsv.csv') 

If someone want to convert all the excel worksheets from single excel workbook to the different csv files, try below code:

import pandas as pd
def excelTOcsv(filename):
    df = pd.read_excel(filename, sheet_name=None)  
    for key, value in df.items(): 
        return df[key].to_csv('%s.csv' %key)

This function is working as a multiple Excel sheet of same excel workbook to multiple csv file converter. Where key is the sheet name and value is the content inside sheet.

How to initialize an array in Java?

Rather than learning un-Official websites learn from oracle website

link follows:Click here

*You can find Initialization as well as declaration with full description *

int n; // size of array here 10
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
    a[i] = Integer.parseInt(s.nextLine()); // using Scanner class
}

Input: 10//array size 10 20 30 40 50 60 71 80 90 91

Displaying data:

for (int i = 0; i < a.length; i++) 
{
    System.out.println(a[i] + " ");
}

Output: 10 20 30 40 50 60 71 80 90 91

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

How to change XAMPP apache server port?

If the XAMPP server is running for the moment, stop XAMPP server.

Follow these steps to change the port number.

Open the file in following location.

[XAMPP Installation Folder]/apache/conf/httpd.conf

Open the httpd.conf file and search for the String:

Listen 80

This is the port number used by XAMMP.

Then search for the string ServerName and update the Port Number which you entered earlier for Listen

Now save and re-start XAMPP server.

AngularJS- Login and Authentication in each route and controller

The simplest manner of defining custom behavior for individual routes would be fairly easy:

1) routes.js: create a new property (like requireAuth) for any desired route

angular.module('yourApp').config(function($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'templates/home.html',
            requireAuth: true // our custom property
        })
        .when('/login', {
            templateUrl: 'templates/login.html',
        })
        .otherwise({
            redirectTo: '/home'
        });
})

2) In a top-tier controller that isn't bound to an element inside the ng-view (to avoid conflict with angular $routeProvider), check if the newUrl has the requireAuth property and act accordingly

 angular.module('YourApp').controller('YourController', function ($scope, $location, session) {

     // intercept the route change event
     $scope.$on('$routeChangeStart', function (angularEvent, newUrl) {

         // check if the custom property exist
         if (newUrl.requireAuth && !session.user) {

             // user isn’t authenticated
             $location.path("/login");
         }
     });
 });

Simple regular expression for a decimal with a precision of 2

Main answer is WRONG because it valids 5. or 5, inputs

this code handle it (but in my example negative numbers are forbidden):

/^[0-9]+([.,][0-9]{1,2})?$/;

results are bellow:

true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2" true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true => "1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false => "0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" / true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true => "81,3" / true => "7" / true => "7.654"

Jquery : Refresh/Reload the page on clicking a button

Use this line simply inside your head with

       window.location.reload(true);

It will load your current page or view.

How to pass an event object to a function in Javascript?

  1. Modify the definition of the function check_me as::

     function check_me(ev) {
    
  2. Now you can access the methods and parameters of the event, in your case:

     ev.preventDefault();
    
  3. Then, you have to pass the parameter on the onclick in the inline call::

     <button type="button" onclick="check_me(event);">Click Me!</button>
    

A useful link to understand this.


Full example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <button type="button" onclick="check_me(event);">Click Me!</button>
  </body>
</html>









Alternatives (best practices):

Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation

A. Using addEventListener:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
      
      <!-- add the event to the button identified #my_button -->
      document.getElementById("my_button").addEventListener("click", check_me);
    </script>
  </body>
</html>

B. Isolating Javascript:

Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.

Just put this two files in the same folder:

  • example.html:
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript" src="example.js"></script>
  </body>
</html>
  • example.js:
function check_me(ev) {
    ev.preventDefault();
    alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);

Blue and Purple Default links, how to remove?

Hey define color #000 into as like you and modify your css as like this

.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }

or this

 li a { text-decoration: none; color:#000; }
 li a:visited { text-decoration: none; color:#000; }
 li a:hover { text-decoration: none; color:#000; }
 li a:focus { text-decoration: none; color:#000; }
 li a:hover, .navBtn:active { text-decoration: none; color:#000; }

Add SUM of values of two LISTS into new LIST

If you have an unknown number of lists of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each). The * is used again to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

Output:

[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:

[19, 19, 19, 19, 19]

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

If you have Google analytics or Facebook api in you app, you need to check all of them to make sure it works!

Edit: This is an old answer - see comments or other answers for an exact answer.

Printing out a number in assembly language?

;        good example of      unlimited num print

.model small

.stack 100h

.data

number word 6432

string db 10 dup('$')

.code


main proc

mov ax,@data 

mov ds,ax



mov ax,number

mov bx ,10

mov cx,0

l1:

mov dx,0

div bx

add dx,48

push dx

inc cx

cmp ax,0

jne l1


mov bx ,offset string 

l2:

pop dx           

mov [bx],dx

inc bx



loop l2



mov ah,09

mov dx,offset string

int 21h
mov ax,4c00h

int 21h


main endp

end main

MySQL - UPDATE multiple rows with different values in one query

To Extend on @Trevedhek answer,

In case the update has to be done with non-unique keys, 4 queries will be need

NOTE: This is not transaction-safe

This can be done using a temp table.

Step 1: Create a temp table keys and the columns you want to update

CREATE TEMPORARY TABLE  temp_table_users
(
    cod_user varchar(50)
    , date varchar(50)
    , user_rol varchar(50)
    ,  cod_office varchar(50)
) ENGINE=MEMORY

Step 2: Insert the values into the temp table

Step 3: Update the original table

UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET 
t1.cod_office = tt1.cod_office
t1.date = tt1.date

Step 4: Drop the temp table

Full Screen DialogFragment in Android

No more style that need more complex code.. with status bar..

public static void ShowFullScreenDialog(Context context, View contentView, string header)
        {

            using (Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(context, Android.Resource.Style.ThemeBlackNoTitleBarFullScreen))
            {
                var view = UIHelper.InflaterView(context, Resource.Layout.dialog_full_screen);
                builder.SetView(view);
                Dialog dialog = builder.Create();
                dialog.Window.SetBackgroundDrawableResource(ThemeHelper.GetMainActivityThemeDrawable());
                dialog.Window.SetLayout(context.Resources.DisplayMetrics.WidthPixels, context.Resources.DisplayMetrics.HeightPixels);
                dialog.Window.DecorView.SystemUiVisibility = StatusBarVisibility.Visible;
                
                //fullLinear
                var headtxt = view.FindViewById<TextView>(Resource.Id.headertxt);
                headtxt.SetTextColor(Color.White);
                headtxt.Text = header;
                var fullLinear = view.FindViewById<LinearLayout>(Resource.Id.fullLinear);
                var closeBttn = view.FindViewById<ImageButton>(Resource.Id.closeBttn);
                closeBttn.ImageTintList = ColorHelper.ConvertColorToStateList(Color.White);
                closeBttn.Click += delegate
                {
                    dialog.Hide();
                };
                if (contentView.Parent != null)
                    ((ViewGroup)contentView.Parent).RemoveView(contentView); // <- fix
                fullLinear.AddView(contentView);
                
                dialog.Show();
            }
            
        }

Important

dialog.Window.SetLayout(context.Resources.DisplayMetrics.WidthPixels, context.Resources.DisplayMetrics.HeightPixels);

How to read an entire file to a string using C#?

you can use :

 public static void ReadFileToEnd()
{
    try
    {
    //provide to reader your complete text file
        using (StreamReader sr = new StreamReader("TestFile.txt"))
        {
            String line = sr.ReadToEnd();
            Console.WriteLine(line);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}

Read connection string from web.config

First add this:

using System.Configuration;

How can I make an entire HTML form "readonly"?

There's no fully compliant, official HTML way to do it, but a little javascript can go a long way. Another problem you'll run into is that disabled fields don't show up in the POST data

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I have just faced with similar issue building LLVM 3.7 version. first check whether you have installed the required library on your system:

$locate libstdc++.so.6.*

Then add the found location to your $LD_LIBRARY_PATH environment variable.

What's the difference between “mod” and “remainder”?

Does '%' mean either "mod" or "rem" in C?

In C, % is the remainder1.

..., the result of the / operator is the algebraic quotient with any fractional part discarded ... (This is often called "truncation toward zero".) C11dr §6.5.5 6

The operands of the % operator shall have integer type. C11dr §6.5.5 2

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder ... C11dr §6.5.5 5


What's the difference between “mod” and “remainder”?

C does not define "mod", such as the integer modulus function used in Euclidean division or other modulo. "Euclidean mod" differs from C's a%b operation when a is negative.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1   

Modulo as Euclidean division

 7 modulo  3 -->  1  
 7 modulo -3 -->  1  
-7 modulo  3 -->  2  
-7 modulo -3 -->  2   

Candidate modulo code:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

Note about floating point: double fmod(double x, double y), even though called "fmod", it is not the same as Euclidean division "mod", but similar to C integer remainder:

The fmod functions compute the floating-point remainder of x/y. C11dr §7.12.10.1 2

fmod( 7,  3) -->  1.0  
fmod( 7, -3) -->  1.0  
fmod(-7,  3) --> -1.0  
fmod(-7, -3) --> -1.0   

Disambiguation: C also has a similar named function double modf(double value, double *iptr) which breaks the argument value into integral and fractional parts, each of which has the same type and sign as the argument. This has little to do with the "mod" discussion here except name similarity.


[Edit Dec 2020]

For those who want proper functionality in all cases, an improved modulo_Euclidean() that 1) detects mod(x,0) and 2) a good and no UB result with modulo_Euclidean2(INT_MIN, -1). Inspired by 4 different implementations of modulo with fully defined behavior.

int modulo_Euclidean2(int a, int b) {
  if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
  if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

1 Prior to C99, C's definition of % was still the remainder from division, yet then / allowed negative quotients to round down rather than "truncation toward zero". See Why do you get different values for integer division in C89?. Thus with some pre-C99 compilation, % code can act just like the Euclidean division "mod". The above modulo_Euclidean() will work with this alternate old-school remainder too.

How do you make an array of structs in C?

So to put it all together by using malloc():

int main(int argc, char** argv) {
    typedef struct{
        char* firstName;
        char* lastName;
        int day;
        int month;
        int year;

    }STUDENT;

    int numStudents=3;
    int x;
    STUDENT* students = malloc(numStudents * sizeof *students);
    for (x = 0; x < numStudents; x++){
        students[x].firstName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].firstName);
        students[x].lastName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].lastName);
        scanf("%d",&students[x].day);
        scanf("%d",&students[x].month);
        scanf("%d",&students[x].year);
    }

    for (x = 0; x < numStudents; x++)
        printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

    return (EXIT_SUCCESS);
}

JavaScript/jQuery - How to check if a string contain specific words

You're looking for the indexOf function:

if (str.indexOf("are") >= 0){//Do stuff}

byte array to pdf

You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.

If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.

With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do

System.IO.File.WriteAllBytes("hello.pdf", fileContent);

Paste a multi-line Java String in Eclipse

Okay, I just found the answer (on Stackoverflow, no less).

Eclipse has an option so that copy-paste of multi-line text into String literals will result in quoted newlines:

Preferences/Java/Editor/Typing/ "Escape text when pasting into a string literal"

How to add a new row to an empty numpy array

Here is my solution:

arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)

Can we cast a generic object to a custom object type in javascript?

The answer of @PeterOlson may be worked back in the day but it looks like Object.create is changed. I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.

Nowadays we can use Object.assign (credits to @SayanPal solution) & ES6 syntax:

class Person {
  constructor(obj) {
    obj && Object.assign(this, obj);
  }

  getFullName() {
    return `${this.lastName} ${this.firstName}`;
  }
}

Usage:

const newPerson = new Person(person1)
newPerson.getFullName() // -> Freeman Gordon

ES5 answer below

function Person(obj) {
    for(var prop in obj){
        // for safety you can use the hasOwnProperty function
        this[prop] = obj[prop];
    }
}

Usage:

var newPerson = new Person(person1);
console.log(newPerson.getFullName()); // -> Freeman Gordon

Using a shorter version, 1.5 liner:

function Person(){
    if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
}

jsfiddle

127 Return code from $?

If you're trying to run a program using a scripting language, you may need to include the full path of the scripting language and the file to execute. For example:

exec('/usr/local/bin/node /usr/local/lib/node_modules/uglifycss/uglifycss in.css > out.css');

JavaScript: How do I print a message to the error console?

The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).

How do I disable right click on my web page?

If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag

<body oncontextmenu="return false;">

This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

However, as mentioned in the other answers, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.

How to find out the username and password for mysql database

Go to this file in: WampFolder\apps\phpmyadmin[phpmyadmin version]\config.inc.php

Usually wamp is in your main hard drive folder C:\wamp\

You will see something like:

$cfg['Servers'][$i]['user'] = 'YOUR USER NAME IS HERE';
$cfg['Servers'][$i]['password'] = 'AND YOU PASSWORD IS HERE';

Try using the password and username that you have on that file.

Allow multiple roles to access controller action

Using AspNetCore 2.x, you have to go a little different way:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
    public AuthorizeRoleAttribute(params YourEnum[] roles)
    {
        Policy = string.Join(",", roles.Select(r => r.GetDescription()));
    }
}

just use it like this:

[Authorize(YourEnum.Role1, YourEnum.Role2)]

Select a date from date picker using Selenium webdriver

This code should work properly to get the current date from the calendar.

String today=getCurrentDay(); //function 
driver.findElement(By.xpath("here xpath of textbox")).click();
Thread.sleep(5000);
WebElement dateWidgetForm= driver.findElement(By.xpath("here xpath of calender"));
List<WebElement> columns = dateWidgetForm.findElements(By.tagName("td"));

    for (WebElement cell: columns) {
      String z=cell.getAttribute("class").toString();
      if(z.equalsIgnoreCase("day")){
      if (cell.getText().equals(today)) {
        cell.click();
        break;
      }
    }

private String getCurrentDay() {
 Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
 //Get Current Day as a number
 int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
 System.out.println("Today Int: " + todayInt +"\n");

 //Integer to String Conversion
 String todayStr = Integer.toString(todayInt);
 return todayStr;
}

Convert String to java.util.Date

It sounds like you may want to use something like SimpleDateFormat. http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

You declare your date format and then call the parse method with your string.

private static final DateFormat DF = new SimpleDateFormat(...);
Date myDate = DF.parse("1234");

And as Guillaume says, set the timezone!

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

How do I detect unsigned integer multiply overflow?

I see you're using unsigned integers. By definition, in C (I don't know about C++), unsigned arithmetic does not overflow ... so, at least for C, your point is moot :)

With signed integers, once there has been overflow, undefined behaviour (UB) has occurred and your program can do anything (for example: render tests inconclusive). 

#include <limits.h>

int a = <something>;
int x = <something>;
a += x;              /* UB */
if (a < 0) {         /* Unreliable test */
  /* ... */
}

To create a conforming program, you need to test for overflow before generating said overflow. The method can be used with unsigned integers too:

// For addition
#include <limits.h>

int a = <something>;
int x = <something>;
if ((x > 0) && (a > INT_MAX - x)) /* `a + x` would overflow */;
if ((x < 0) && (a < INT_MIN - x)) /* `a + x` would underflow */;

// For subtraction
#include <limits.h>
int a = <something>;
int x = <something>;
if ((x < 0) && (a > INT_MAX + x)) /* `a - x` would overflow */;
if ((x > 0) && (a < INT_MIN + x)) /* `a - x` would underflow */;

// For multiplication
#include <limits.h>

int a = <something>;
int x = <something>;
// There may be a need to check for -1 for two's complement machines.
// If one number is -1 and another is INT_MIN, multiplying them we get abs(INT_MIN) which is 1 higher than INT_MAX
if ((a == -1) && (x == INT_MIN)) /* `a * x` can overflow */
if ((x == -1) && (a == INT_MIN)) /* `a * x` (or `a / x`) can overflow */
// general case
if (a > INT_MAX / x) /* `a * x` would overflow */;
if ((a < INT_MIN / x)) /* `a * x` would underflow */;

For division (except for the INT_MIN and -1 special case), there isn't any possibility of going over INT_MIN or INT_MAX.

How to get row count in sqlite using Android?

In order to query a table for the number of rows in that table, you want your query to be as efficient as possible. Reference.

Use something like this:

/**
 * Query the Number of Entries in a Sqlite Table
 * */
public long QueryNumEntries()
{
    SQLiteDatabase db = this.getReadableDatabase();
    return DatabaseUtils.queryNumEntries(db, "table_name");
}

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

Found the solution after some searching.

You need to add a <meta> tag in your <head> containing name="theme-color", with your HEX code as the content value. For example:

<meta name="theme-color" content="#999999" />

Update:

If the android device has native dark-mode enabled, then this meta tag is ignored.

Chrome for Android does not use the color on devices with native dark-mode enabled.

source: https://caniuse.com/#search=theme-color

jQuery delete all table rows except first

This worked in the following way in my case and working fine

$("#compositeTable").find("tr:gt(1)").remove();

Calculate cosine similarity given 2 sentence strings

The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:

Meaning of words

The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".

This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:

theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles

These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.

The problem with phrases

You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.

Composition

To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.

The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.

Further reading

I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).


Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

An old thread, but since I didn't find it elsewhere, here is one more possibility:

If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true" attribute

enter image description here

This tells tomcat to map the servlets using data given in web.xml instead of using the @WebServlet annotation.

Simple way to encode a string according to a password?

If you want to be safe, you can use Fernet, which is cryptographically sound. You can use a static "salt" if you don't want to store it separately - you will only lose dictionary and rainbow attack prevention. I chose it because I can pick long or short passwords´, which is not so easy with AES.

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64

#set password
password = "mysecretpassword"
#set message
message = "secretmessage"

kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt="staticsalt", iterations=100000, backend=default_backend())
key = base64.urlsafe_b64encode(kdf.derive(password))
f = Fernet(key)

#encrypt
encrypted = f.encrypt(message)
print encrypted

#decrypt
decrypted = f.decrypt(encrypted)
print decrypted

If that's too complicated, someone suggested simplecrypt

from simplecrypt import encrypt, decrypt
ciphertext = encrypt('password', plaintext)
plaintext = decrypt('password', ciphertext)

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

Select columns in PySpark dataframe

First two columns and 5 rows

 df.select(df.columns[:2]).take(5)

How to force NSLocalizedString to use a specific language

Here is a decent solution for this problem, and it does not require application restart.

https://github.com/cmaftuleac/BundleLocalization

This implementation works by tweaking inside NSBundle. The idea is that you override the method localizedStringForKey on the instance of NSBundle object, and then call this method on a different bundle with a different language. Simple and elegant fully compatible with all types of resources.

Check that a input to UITextField is numeric only

To be more international (and not only US colored ;-) ) just replace in the code above by

-(NSNumber *) getNumber
{
  NSString* localeIdentifier = [[NSLocale autoupdatingCurrentLocale] localeIdentifier];
  NSLocale *l_en = [[NSLocale alloc] initWithLocaleIdentifier: localeIdentifier] ;
  return [self getNumberWithLocale: [l_en autorelease] ];
}

Real mouse position in canvas

The easiest way to compute the correct mouse click or mouse move position on a canvas event is to use this little equation:

canvas.addEventListener('click', event =>
{
    let bound = canvas.getBoundingClientRect();

    let x = event.clientX - bound.left - canvas.clientLeft;
    let y = event.clientY - bound.top - canvas.clientTop;

    context.fillRect(x, y, 16, 16);
});

If the canvas has padding-left or padding-top, subtract x and y via:

x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));

Laravel Rule Validation for Numbers

If I correctly got what you want:

$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];

or

$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];

For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules

digits_between :min,max

The field under validation must have a length between the given min and max.

numeric

The field under validation must have a numeric value.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

SOAP vs REST (differences)

SOAP (Simple Object Access Protocol) and REST (Representation State Transfer) both are beautiful in their way. So I am not comparing them. Instead, I am trying to depict the picture, when I preferred to use REST and when SOAP.

What is payload?

When data is sent over the Internet, each unit transmitted includes both header information and the actual data being sent. The header identifies the source and destination of the packet, while the actual data is referred to as the payload. In general, the payload is the data that is carried on behalf of an application and the data received by the destination system.

Now, for example, I have to send a Telegram and we all know that the cost of the telegram will depend on some words.

So tell me among below mentioned these two messages, which one is cheaper to send?

<name>Arin</name>

or

"name": "Arin"

I know your answer will be the second one although both representing the same message second one is cheaper regarding cost.

So I am trying to say that, sending data over the network in JSON format is cheaper than sending it in XML format regarding payload.

Here is the first benefit or advantages of REST over SOAP. SOAP only support XML, but REST supports different format like text, JSON, XML, etc. And we already know, if we use Json then definitely we will be in better place regarding payload.

Now, SOAP supports the only XML, but it also has its advantages.

Really! How?

SOAP relies on XML in three ways Envelope – that defines what is in the message and how to process it.

A set of encoding rules for data types, and finally the layout of the procedure calls and responses gathered.

This envelope is sent via a transport (HTTP/HTTPS), and an RPC (Remote Procedure Call) is executed, and the envelope is returned with information in an XML formatted document.

The important point is that one of the advantages of SOAP is the use of the “generic” transport but REST uses HTTP/HTTPS. SOAP can use almost any transport to send the request but REST cannot. So here we got an advantage of using SOAP.

As I already mentioned in above paragraph “REST uses HTTP/HTTPS”, so go a bit deeper on these words.

When we are talking about REST over HTTP, all security measures applied HTTP are inherited, and this is known as transport level security and it secures messages only while it is inside the wire but once you delivered it on the other side you don’t know how many stages it will have to go through before reaching the real point where the data will be processed. And of course, all those stages could use something different than HTTP.So Rest is not safer completely, right?

But SOAP supports SSL just like REST additionally it also supports WS-Security which adds some enterprise security features. WS-Security offers protection from the creation of the message to it’s consumption. So for transport level security whatever loophole we found that can be prevented using WS-Security.

Apart from that, as REST is limited by it's HTTP protocol so it’s transaction support is neither ACID compliant nor can provide two-phase commit across distributed transnational resources.

But SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.

I am not drawing any conclusion, but I will prefer SOAP-based web service while security, transaction, etc. are the main concerns.

Here is the "The Java EE 6 Tutorial" where they have said A RESTful design may be appropriate when the following conditions are met. Have a look.

Hope you enjoyed reading my answer.

Android ACTION_IMAGE_CAPTURE Intent

I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.

I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:

String storageState = Environment.getExternalStorageState();
        if(storageState.equals(Environment.MEDIA_MOUNTED)) {

            String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
            _photoFile = new File(path);
            try {
                if(_photoFile.exists() == false) {
                    _photoFile.getParentFile().mkdirs();
                    _photoFile.createNewFile();
                }

            } catch (IOException e) {
                Log.e(TAG, "Could not create file.", e);
            }
            Log.i(TAG, path);

            _fileUri = Uri.fromFile(_photoFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
            intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
            startActivityForResult(intent, TAKE_PICTURE);
        }   else {
            new AlertDialog.Builder(MainActivity.this)
            .setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
            .setCancelable(true).create().show();
        }

I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.

Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg

There is no need to copy the file in the "onActivityResult" as posted above.

Getting all types in a namespace via reflection

For a specific Assembly, NameSpace and ClassName:

var assemblyName = "Some.Assembly.Name"
var nameSpace = "Some.Namespace.Name";
var className = "ClassNameFilter";

var asm = Assembly.Load(assemblyName);
var classes = asm.GetTypes().Where(p =>
     p.Namespace == nameSpace &&
     p.Name.Contains(className) 
).ToList();

Note: The project must reference the assembly

How to clear Facebook Sharer cache?

This answer is intended for developers.

Clearing the cache means that new shares of this webpage will show the new content which is provided in the OG tags. But only if the URL that you are working on has less than 50 interactions (likes + shares). It will also not affect old links to this webpage which have already been posted on Facebook. Only when sharing the URL on Facebook again will the way that Facebook shows the link be updated.

catandmouse's answer is correct but you can also make Facebook clear the OG (OpenGraph) cache by sending a post request to graph.facebook.com (works for both http and https as of the writing of this answer). You do not need an access token.

A post request to graph.facebook.com may look as follows:

POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: graph.facebook.com
Content-Length: 63
Accept-Encoding: gzip
User-Agent: Mojolicious (Perl)

id=<url_encoded_url>&scrape=true

In Perl, you can use the following code where the library Mojo::UserAgent is used to send and receive HTTP requests:

sub _clear_og_cache_on_facebook {
    my $fburl     = "http://graph.facebook.com";
    my $ua        = Mojo::UserAgent->new;
    my $clearurl  = <the url you want Facebook to forget>;
    my $post_body = {id => $clearurl, scrape => 'true'};
    my $res       = $ua->post($fburl => form => $post_body)->res;
    my $code      = $res->code;
    unless ($code eq '200') {
        Log->warn("Clearing cached OG data for $clearurl failed with code $code.");
        }
    }
}

Sending this post request through the terminal can be done with the following command:

curl -F id="<URL>" -F scrape=true graph.facebook.com

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

Querying a linked sql server

SELECT * FROM [server].[database].[schema].[table]

This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

Create two-dimensional arrays and access sub-arrays in Ruby

You didn't state your actual goal, but maybe this can help:

require 'matrix'  # bundled with Ruby
m = Matrix[
 [1, 2, 3],
 [4, 5, 6]
]

m.column(0) # ==> Vector[1, 4]

(and Vectors acts like arrays)

or, using a similar notation as you desire:

m.minor(0..1, 2..2) # => Matrix[[3], [6]]

Async await in linq select

I have the same problem as @KTCheek in that I need it to execute sequentially. However I figured I would try using IAsyncEnumerable (introduced in .NET Core 3) and await foreach (introduced in C# 8). Here's what I have come up with:

public static class IEnumerableExtensions {
    public static async IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) {
        foreach (var item in source) {
            yield return await selector(item);
        }
    }
}

public static class IAsyncEnumerableExtensions {
    public static async Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source) {
        var list = new List<TSource>();

        await foreach (var item in source) {
            list.Add(item);
        }

        return list;
    }
}

This can be consumed by saying:

var inputs = await events.SelectAsync(ev => ProcessEventAsync(ev)).ToListAsync();

Update: Alternatively you can add a reference to "System.Linq.Async" and then you can say:

var inputs = await events
    .ToAsyncEnumerable()
    .SelectAwait(async ev => await ProcessEventAsync(ev))
    .ToListAsync();

How can I change the text inside my <span> with jQuery?

$('#abc span').text('baa baa black sheep');
$('#abc span').html('baa baa <strong>black sheep</strong>');

text() if just text content. html() if it contains, well, html content.

Command not found when using sudo

It seems that linux will say "command not found" even if you explicitly give the path to the file.

[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
sudo: /tmp/uid.sh: command not found
1
[veeam@jsandbox ~]$ chmod +x /tmp/uid.sh
[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
0

It's a somewhat misleading error, however it's probably technically correct. A file is not a command until its executable, and so cannot be found.

Keeping ASP.NET Session Open / Alive

Here JQuery plugin version of Maryan solution with handle optimization. Only with JQuery 1.7+!

(function ($) {
    $.fn.heartbeat = function (options) {
        var settings = $.extend({
            // These are the defaults.
            events: 'mousemove keydown'
            , url: '/Home/KeepSessionAlive'
            , every: 5*60*1000
        }, options);

        var keepSessionAlive = false
         , $container = $(this)
         , handler = function () {
             keepSessionAlive = true;
             $container.off(settings.events, handler)
         }, reset = function () {
             keepSessionAlive = false;
             $container.on(settings.events, handler);
             setTimeout(sessionAlive, settings.every);
         }, sessionAlive = function () {
             keepSessionAlive && $.ajax({
                 type: "POST"
                 , url: settings.url
                 ,success: reset
                });
         };
        reset();

        return this;
    }
})(jQuery)

and how it does import in your *.cshtml

$('body').heartbeat(); // Simple
$('body').heartbeat({url:'@Url.Action("Home", "heartbeat")'}); // different url
$('body').heartbeat({every:6*60*1000}); // different timeout

ASP.NET MVC Razor render without encoding

You can also use the WriteLiteral method

Simplest way to throw an error/exception with a custom message in Swift 2?

I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:

struct RuntimeError: LocalizedError
{
    let message: String

    init(_ message: String)
    {
        self.message = message
    }

    public var errorDescription: String?
    {
        return message
    }
}

See this answer for more details.

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

How to escape comma and double quote at same time for CSV file?

There are several libraries. Here are two examples:


❐ Apache Commons Lang

Apache Commons Lang includes a special class to escape or unescape strings (CSV, EcmaScript, HTML, Java, Json, XML): org.apache.commons.lang3.StringEscapeUtils.

  • Escape to CSV

    String escaped = StringEscapeUtils
        .escapeCsv("I said \"Hey, I am 5'10\".\""); // I said "Hey, I am 5'10"."
    
    System.out.println(escaped); // "I said ""Hey, I am 5'10""."""
    
  • Unescape from CSV

    String unescaped = StringEscapeUtils
        .unescapeCsv("\"I said \"\"Hey, I am 5'10\"\".\"\"\""); // "I said ""Hey, I am 5'10""."""
    
    System.out.println(unescaped); // I said "Hey, I am 5'10"."
    

* You can download it from here.


❐ OpenCSV

If you use OpenCSV, you will not need to worry about escape or unescape, only for write or read the content.

  • Writing file:

    FileOutputStream fos = new FileOutputStream("awesomefile.csv"); 
    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
    CSVWriter writer = new CSVWriter(osw);
    ...
    String[] row = {
        "123", 
        "John", 
        "Smith", 
        "39", 
        "I said \"Hey, I am 5'10\".\""
    };
    writer.writeNext(row);
    ...
    writer.close();
    osw.close();
    os.close();
    
  • Reading file:

    FileInputStream fis = new FileInputStream("awesomefile.csv"); 
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    CSVReader reader = new CSVReader(isr);
    
    for (String[] row; (row = reader.readNext()) != null;) {
        System.out.println(Arrays.toString(row));
    }
    
    reader.close();
    isr.close();
    fis.close();
    

* You can download it from here.

Download text/csv content as files from server in Angular

var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document

anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
    target: '_blank',
    download: 'filename.csv'
})[0].click();

anchor.remove(); // Clean it up afterwards

This code works both Mozilla and chrome

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

If you can make all characters lowercase on the server than you can apply:

text-transform: capitalize

I don't think text-transform will work with uppercase letters as the input.

Angular 2 - innerHTML styling

The simple solution you need to follow is

import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer){}

transformYourHtml(htmlTextWithStyle) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}

python dataframe pandas drop column using int

You can delete column on i index like this:

df.drop(df.columns[i], axis=1)

It could work strange, if you have duplicate names in columns, so to do this you can rename column you want to delete column by new name. Or you can reassign DataFrame like this:

df = df.iloc[:, [j for j, c in enumerate(df.columns) if j != i]]

How do I delete rows in a data frame?

You can also work with a so called boolean vector, aka logical:

row_to_keep = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)
myData = myData[row_to_keep,]

Note that the ! operator acts as a NOT, i.e. !TRUE == FALSE:

myData = myData[!row_to_keep,]

This seems a bit cumbersome in comparison to @mrwab's answer (+1 btw :)), but a logical vector can be generated on the fly, e.g. where a column value exceeds a certain value:

myData = myData[myData$A > 4,]
myData = myData[!myData$A > 4,] # equal to myData[myData$A <= 4,]

You can transform a boolean vector to a vector of indices:

row_to_keep = which(myData$A > 4)

Finally, a very neat trick is that you can use this kind of subsetting not only for extraction, but also for assignment:

myData$A[myData$A > 4,] <- NA

where column A is assigned NA (not a number) where A exceeds 4.

Chrome disable SSL checking for sites?

To disable the errors windows related with certificates you can start Chrome from console and use this option: --ignore-certificate-errors.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ignore-certificate-errors

You should use it for testing purposes. A more complete list of options is here: http://peter.sh/experiments/chromium-command-line-switches/

WAMP/XAMPP is responding very slow over localhost

have a look here :

http://forum.wampserver.com/read.php?2,91602,page=3

Basically use 127.0.0.1 instead of localhost when connecting to mysql through php on windows 8

if your finding phpmyadmin slow

in the config.inc.php you can change localhost to 127.0.0.1 also

How to get the function name from within that function?

You can use name property to get the function name, unless you're using an anonymous function

For example:

var Person = function Person () {
  this.someMethod = function () {};
};

Person.prototype.getSomeMethodName = function () {
  return this.someMethod.name;
};

var p = new Person();
// will return "", because someMethod is assigned with anonymous function
console.log(p.getSomeMethodName());

now let's try with named function

var Person = function Person () {
  this.someMethod = function someMethod() {};
};

now you can use

// will return "someMethod"
p.getSomeMethodName()

How can VBA connect to MySQL database in Excel?

Enable Microsoft ActiveX Data Objects 2.8 Library

Dim oConn As ADODB.Connection 
Private Sub ConnectDB()     
Set oConn = New ADODB.Connection    
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _        
"SERVER=localhost;" & _         
"DATABASE=yourdatabase;" & _        
"USER=yourdbusername;" & _      
"PASSWORD=yourdbpassword;" & _      
"Option=3" 
End Sub

There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/

How to use color picker (eye dropper)?

It is just called the eyedropper tool. There is no shortcut key for it that I'm aware of. The only way you can use it now is by clicking on the color picker box in styles sidebar and then clicking on the page as you have already been doing.

document.getElementById().value and document.getElementById().checked not working for IE

The code you pasted should work... There must be something else we are not seeing here.

Check this out. Working for me fine on IE7. When you submit you will see the variable passed in the URL.

What is a practical, real world example of the Linked List?

He did ask for a practical example; so I'll give it a shot:

Lets say you are writing a firewall; in this firewall you have an IP whitelist and an IP blacklist.

You know that your IP, your jobs IP, and some testing IP's need to be whitelisted. So, you add all of the IP's to the whitelist.

Now, you also have a list of known IP's that should be blocked. So, you add those IPs to the blacklist.

Why might use LinkedList for this?

  1. The operation is fast for adding/removing an item from the list.
  2. You do not know how many IP's are going to blocked/whitelisted. Thus, revealing one of the main advantages to a LinkedList (it's resizable).

How to view hierarchical package structure in Eclipse package explorer

Here is representation of screen eclipse to make hierarachical.

enter image description here

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

ssh script returns 255 error

It can very much be an ssh-agent issue. Check whether there is an ssh-agent PID currently running with eval "$(ssh-agent -s)"

Check whether your identity is added with ssh-add -l and if not, add it with ssh-add <pathToYourRSAKey>.

Then try again your ssh command (or any other command that spawns ssh daemons, like autossh for example) that returned 255.

Send Email Intent

Finally come up with best way to do

String to = "[email protected]";
String subject= "Hi I am subject";
String body="Hi I am test body";
String mailTo = "mailto:" + to +
        "?&subject=" + Uri.encode(subject) +
        "&body=" + Uri.encode(body);
Intent emailIntent = new Intent(Intent.ACTION_VIEW);
emailIntent.setData(Uri.parse(mailTo));
startActivity(emailIntent);

How to block users from closing a window in Javascript?

What will you do when a user hits ALT + F4 or closes it from Task Manager

Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."

Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)

diff current working copy of a file with another branch's committed copy

Also: git diff master..feature foo

Since git diff foo master:foo doesn't work on directories for me.

When to use pthread_exit() and when to use pthread_join() in Linux?

Using pthread_exit in the main thread(in place of pthread_join), will leave the main thread in defunct(zombie) state. Since not using pthread_join, other joinable threads which are terminated will also remain in the zombie state and cause resource leakage.

Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).

Another point is keeping the main thread in the defunct state, while other threads are running may cause implementation dependent issues in various conditions like if resources are allocated in main thread or variables which are local to the main thread are used in other threads.

Also, all the shared resources are released only when the process exits, it's not saving any resources. So, I think using pthread_exit in place of pthread_join should be avoided.

making a paragraph in html contain a text from a file

I would use javascript for this.

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
  if (txtFile.readyState === 4 && txtFile.status == 200) {
     allText = txtFile.responseText;
  }
document.getElementById('your div id').innerHTML = allText;

This is just a code sample, would need tweaking for all browsers, etc.

Proxy Basic Authentication in C#: HTTP 407 error

try this

        var YourURL = "http://yourUrl/";

         HttpClientHandler handler = new HttpClientHandler() 
         { 
             Proxy = new WebProxy("http://127.0.0.1:8888"), 
             UseProxy = true, 
         }; 

         Console.WriteLine(YourURL); 

         HttpClient client = new HttpClient(handler); 

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The correct solution seems to be:

<Window.Resources>
    <CollectionViewSource x:Key="ItemsCVS" Source="{Binding MyItems}" />
</Window.Resources>
<!-- ... -->
<DataGrid ItemsSource="{Binding MyRecords}">
    <DataGridComboBoxColumn Header="Column With Predefined Values"
                            ItemsSource="{Binding Source={StaticResource ItemsCVS}}"
                            SelectedValueBinding="{Binding MyItemId}"
                            SelectedValuePath="Id"
                            DisplayMemberPath="StatusCode" />
</DataGrid>

The layout above works perfectly fine for me, and should work for others. This design choice also makes sense, though it isn't very well explained anywhere. But if you have a data column with predefined values, those values typically don't change during run-time. So creating a CollectionViewSource and initializing the data once makes sense. It also gets rid of the longer bindings to find an ancestor and bind on it's data context (which always felt wrong to me).

I am leaving this here for anyone else who struggled with this binding, and wondered if there was a better way (As this page is obviously still coming up in search results, that's how I got here).

Convert string to a variable name

assign is what you are looking for.

assign("x", 5)

x
[1] 5

but buyer beware.

See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

My Routes are Returning a 404, How can I Fix Them?

The Main problem of route not working is there is mod_rewrite.so module in macos, linux not enabled in httpd.conf file of apache configuration, so can .htaccess to work. i have solved this by uncomment the line :

# LoadModule rewrite_module libexec/apache2/mod_rewrite.so

Remove the # from above line of httpdf.conf. Then it will works.
enjoy!

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

That particular package does not include assemblies for dotnet core, at least not at present. You may be able to build it for core yourself with a few tweaks to the project file, but I can't say for sure without diving into the source myself.

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE but you can use UPDATE.

The syntax is as follows:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

Why maven? What are the benefits?

Maven can be considered as complete project development tool not just build tool like Ant. You should use Eclipse IDE with maven plugin to fix all your problems.

Here are few advantages of Maven, quoted from the Benefits of using Maven page:

Henning

  • quick project setup, no complicated build.xml files, just a POM and go
  • all developers in a project use the same jar dependencies due to centralized POM.
  • getting a number of reports and metrics for a project "for free"
  • reduce the size of source distributions, because jars can be pulled from a central location

Emmanuel Venisse

  • a lot of goals are available so it isn't necessary to develop some specific build process part contrary to ANT we can reuse existing ANT tasks in build process with antrun plugin

Jesse Mcconnell

  • Promotes modular design of code. by making it simple to manage mulitple projects it allows the design to be laid out into muliple logical parts, weaving these parts together through the use of dependency tracking in pom files.
  • Enforces modular design of code. it is easy to pay lipservice to modular code, but when the code is in seperate compiling projects it is impossible to cross pollinate references between modules of code unless you specifically allow for it in your dependency management... there is no 'I'll just do this now and fix it later' implementations.
  • Dependency Management is clearly declared. with the dependency management mechanism you have to try to screw up your jar versioning...there is none of the classic problem of 'which version of this vendor jar is this?' And setting it up on an existing project rips the top off of the existing mess if it exists when you are forced to make 'unknown' versions in your repository to get things up and running...that or lie to yourself that you know the actual version of ABC.jar.
  • strong typed life cycle there is a strong defined lifecycle that a software system goes thru from the initiation of a build to the end... and the users are allowed to mix and match their system to the lifecycle instead of cobble together their own lifecycle.. this has the additional benefit of allowing people to move from one project to another and speak using the same vocabulary in terms of software building

Vincent Massol

  • Greater momentum: Ant is now legacy and not moving fast ahead. Maven is forging ahead fast and there's a potential of having lots of high-value tools around Maven (CI, Dashboard project, IDE integration, etc).

Firefox "ssl_error_no_cypher_overlap" error

I had the same problem with a really old local router and was not able to open its WebGUI because of self-signed certificates. The solution was to install an old Firefox Portable version. I tested the following versions:

  • Firefox 33.1.1 (worked)
  • Firefox 45.0.2 (worked)
  • Firefox 56.0.2 (failed)

This is strange because it should be only a problem since version 59, but as long it works, it's ok for me.

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.

import numpy as np
import random
import cv2

def sp_noise(image,prob):
    '''
    Add salt and pepper noise to image
    prob: Probability of the noise
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)

How do I render a shadow?

    viewStyle : {
    backgroundColor: '#F8F8F8',
    justifyContent: 'center',
    alignItems: 'center',
    height: 60,
    paddingTop: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    marginBottom: 10,
    elevation: 2,
    position: 'relative'
},

Use marginBottom: 10

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.

Run a shell script with an html button

This is how it look like in pure bash

cat /usr/lib/cgi-bin/index.cgi

#!/bin/bash
echo Content-type: text/html
echo ""
## make POST and GET stings
## as bash variables available
if [ ! -z $CONTENT_LENGTH ] && [ "$CONTENT_LENGTH" -gt 0 ] && [ $CONTENT_TYPE != "multipart/form-data" ]; then
read -n $CONTENT_LENGTH POST_STRING <&0
eval `echo "${POST_STRING//;}"|tr '&' ';'`
fi
eval `echo "${QUERY_STRING//;}"|tr '&' ';'`

echo  "<!DOCTYPE html>"
echo  "<html>"
echo  "<head>"
echo  "</head>"

if [[ "$vote" = "a" ]];then
echo "you pressed A"
  sudo /usr/local/bin/run_a.sh
elif [[ "$vote" = "b" ]];then
echo "you pressed B"
  sudo /usr/local/bin/run_b.sh
fi

echo  "<body>"
echo  "<div id=\"content-container\">"
echo  "<div id=\"content-container-center\">"
echo  "<form id=\"choice\" name='form' method=\"POST\" action=\"/\">"
echo  "<button id=\"a\" type=\"submit\" name=\"vote\" class=\"a\" value=\"a\">A</button>"
echo  "<button id=\"b\" type=\"submit\" name=\"vote\" class=\"b\" value=\"b\">B</button>"
echo  "</form>"
echo  "<div id=\"tip\">"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</body>"
echo  "</html>"

Build with https://github.com/tinoschroeter/bash_on_steroids

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

Add this in your values/styles.xml

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

<style name="AppBaseTheme" parent="YourCustomTheme">

</style>

<style name="AppTheme" parent="AppBaseTheme">

</style>

And add the following code in your values-v11/styles.xml and values-v14/styles.xml

<style name="AppBaseTheme" parent="YourCustomTheme">

</style>

Thats it. It will work.

Range of values in C Int and Long 32 - 64 bits

Have a look at the limits.h file in your system it will tell the system specific limits. Or check man limits.h and go to the "Numerical Limits" section.

Redirect to external URI from ASP.NET MVC controller

If you're talking about ASP.NET MVC then you should have a controller method that returns the following:

return Redirect("http://www.google.com");

Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.

How to append new data onto a new line

You need to change parameter "a" => "a+". Follow this code bellows:

def storescores():
hs = open("hst.txt","a+")

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

How can I correctly format currency using jquery?

I used to use the jquery format currency plugin, but it has been very buggy recently. I only need formatting for USD/CAD, so I wrote my own automatic formatting.

$(".currencyMask").change(function () {
            if (!$.isNumeric($(this).val()))
                $(this).val('0').trigger('change');

            $(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
        });

Simply set the class of whatever input should be formatted as currency <input type="text" class="currencyMask" /> and it will format it perfectly in any browser.

How to get child process from parent process

I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.

function getcpid() {
    cpids=`pgrep -P $1|xargs`
#    echo "cpids=$cpids"
    for cpid in $cpids;
    do
        echo "$cpid"
        getcpid $cpid
    done
}

getcpid $1

How to split a string literal across multiple lines in C / Objective-C?

There are two ways to split strings over multiple lines:

Using \

All lines in C can be split into multiple lines using \.

Plain C:

char *my_string = "Line 1 \
                   Line 2";

Objective-C:

NSString *my_string = @"Line1 \
                        Line2";

Better approach

There's a better approach that works just for strings.

Plain C:

char *my_string = "Line 1 "
                  "Line 2";

Objective-C:

NSString *my_string = @"Line1 "
                       "Line2";    // the second @ is optional

The second approach is better, because there isn't a lot of whitespace included. For a SQL query however, both are possible.

NOTE: With a #define, you have to add an extra '\' to concatenate the two strings:

Plain C:

#define kMyString "Line 1"\
                  "Line 2"

LINQ - Full Outer Join

Yet another full outer join

As was not that happy with the simplicity and the readability of the other propositions, I ended up with this :

It does not have the pretension to be fast ( about 800 ms to join 1000 * 1000 on a 2020m CPU : 2.4ghz / 2cores). To me, it is just a compact and casual full outer join.

It works the same as a SQL FULL OUTER JOIN (duplicates conservation)

Cheers ;-)

using System;
using System.Collections.Generic;
using System.Linq;
namespace NS
{
public static class DataReunion
{
    public static List<Tuple<T1, T2>> FullJoin<T1, T2, TKey>(List<T1> List1, Func<T1, TKey> KeyFunc1, List<T2> List2, Func<T2, TKey> KeyFunc2)
    {
        List<Tuple<T1, T2>> result = new List<Tuple<T1, T2>>();

        Tuple<TKey, T1>[] identifiedList1 = List1.Select(_ => Tuple.Create(KeyFunc1(_), _)).OrderBy(_ => _.Item1).ToArray();
        Tuple<TKey, T2>[] identifiedList2 = List2.Select(_ => Tuple.Create(KeyFunc2(_), _)).OrderBy(_ => _.Item1).ToArray();

        identifiedList1.Where(_ => !identifiedList2.Select(__ => __.Item1).Contains(_.Item1)).ToList().ForEach(_ => {
            result.Add(Tuple.Create<T1, T2>(_.Item2, default(T2)));
        });

        result.AddRange(
            identifiedList1.Join(identifiedList2, left => left.Item1, right => right.Item1, (left, right) => Tuple.Create<T1, T2>(left.Item2, right.Item2)).ToList()
        );

        identifiedList2.Where(_ => !identifiedList1.Select(__ => __.Item1).Contains(_.Item1)).ToList().ForEach(_ => {
            result.Add(Tuple.Create<T1, T2>(default(T1), _.Item2));
        });

        return result;
    }
}
}

The idea is to

  1. Build Ids based on provided key function builders
  2. Process left only items
  3. Process inner join
  4. Process right only items

Here is a succinct test that goes with it :

Place a break point at the end to manually verify that it behaves as expected

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NS;

namespace Tests
{
[TestClass]
public class DataReunionTest
{
    [TestMethod]
    public void Test()
    {
        List<Tuple<Int32, Int32, String>> A = new List<Tuple<Int32, Int32, String>>();
        List<Tuple<Int32, Int32, String>> B = new List<Tuple<Int32, Int32, String>>();

        Random rnd = new Random();

        /* Comment the testing block you do not want to run
        /* Solution to test a wide range of keys*/

        for (int i = 0; i < 500; i += 1)
        {
            A.Add(Tuple.Create(rnd.Next(1, 101), rnd.Next(1, 101), "A"));
            B.Add(Tuple.Create(rnd.Next(1, 101), rnd.Next(1, 101), "B"));
        }

        /* Solution for essential testing*/

        A.Add(Tuple.Create(1, 2, "B11"));
        A.Add(Tuple.Create(1, 2, "B12"));
        A.Add(Tuple.Create(1, 3, "C11"));
        A.Add(Tuple.Create(1, 3, "C12"));
        A.Add(Tuple.Create(1, 3, "C13"));
        A.Add(Tuple.Create(1, 4, "D1"));

        B.Add(Tuple.Create(1, 1, "A21"));
        B.Add(Tuple.Create(1, 1, "A22"));
        B.Add(Tuple.Create(1, 1, "A23"));
        B.Add(Tuple.Create(1, 2, "B21"));
        B.Add(Tuple.Create(1, 2, "B22"));
        B.Add(Tuple.Create(1, 2, "B23"));
        B.Add(Tuple.Create(1, 3, "C2"));
        B.Add(Tuple.Create(1, 5, "E2"));

        Func<Tuple<Int32, Int32, String>, Tuple<Int32, Int32>> key = (_) => Tuple.Create(_.Item1, _.Item2);

        var watch = System.Diagnostics.Stopwatch.StartNew();
        var res = DataReunion.FullJoin(A, key, B, key);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        String aser = JToken.FromObject(res).ToString(Formatting.Indented);
        Console.Write(elapsedMs);
    }
}

}

Extract substring in Bash

There's also the bash builtin 'expr' command:

INPUT="someletters_12345_moreleters.ext"  
SUBSTRING=`expr match "$INPUT" '.*_\([[:digit:]]*\)_.*' `  
echo $SUBSTRING

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

How to access nested elements of json object using getJSONArray method

I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:

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

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class GsonProgram {

    public static void main(String... args) {
        String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";

        Gson gson = new GsonBuilder().serializeNulls().create();
        Response res = gson.fromJson(response, Response.class);

        System.out.println("Entries: " + res.getResult().getMap().getEntry());
    }
}

class Response {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return result.toString();
    }
}

class Result {

    private MapNode map;

    public MapNode getMap() {
        return map;
    }

    public void setMap(MapNode map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return map.toString();
    }
}

class MapNode {

    List<Entry> entry = new ArrayList<Entry>();

    public List<Entry> getEntry() {
        return entry;
    }

    public void setEntry(List<Entry> entry) {
        this.entry = entry;
    }

    @Override
    public String toString() {
        return Arrays.toString(entry.toArray());
    }
}

class Entry {

    private Key key;
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Key getKey() {
        return key;
    }

    public void setKey(Key key) {
        this.key = key;
    }

    @Override
    public String toString() {
        return "[key=" + key + ", value=" + value + "]";
    }
}

class Key {

    @SerializedName("$")
    private String value;

    @SerializedName("@xsi.type")
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "[value=" + value + ", type=" + type + "]";
    }
}

Program output:

Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]

If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".

Limit the length of a string with AngularJS

In html its used along with limitTo filter provided by angular itself as below,

    <p> {{limitTo:30 | keepDots }} </p>

filter keepDots :

     App.filter('keepDots' , keepDots)

       function keepDots() {

        return function(input,scope) {
            if(!input) return;

             if(input.length > 20)
                return input+'...';
            else
                return input;

        }


    }

How to skip over an element in .map()?

To extrapolate on Felix Kling's comment, you can use .filter() like this:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() === "json") { // if extension is .json
    return null; // skip
  } else {
    return img.src;
  }
}).filter(Boolean);

That will remove falsey values from the array that is returned by .map()

You could simplify it further like this:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() !== "json") { // if extension is .json
    return img.src;
  }
}).filter(Boolean);

Or even as a one-liner using an arrow function, object destructuring and the && operator:

var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);

Python equivalent to 'hold on' in Matlab

The hold on feature is switched on by default in matplotlib.pyplot. So each time you evoke plt.plot() before plt.show() a drawing is added to the plot. Launching plt.plot() after the function plt.show() leads to redrawing the whole picture.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

What is difference between functional and imperative programming languages?

Definition: An imperative language uses a sequence of statements to determine how to reach a certain goal. These statements are said to change the state of the program as each one is executed in turn.

Examples: Java is an imperative language. For example, a program can be created to add a series of numbers:

 int total = 0;
 int number1 = 5;
 int number2 = 10;
 int number3 = 15;
 total = number1 + number2 + number3; 

Each statement changes the state of the program, from assigning values to each variable to the final addition of those values. Using a sequence of five statements the program is explicitly told how to add the numbers 5, 10 and 15 together.

Functional languages: The functional programming paradigm was explicitly created to support a pure functional approach to problem solving. Functional programming is a form of declarative programming.

Advantages of Pure Functions: The primary reason to implement functional transformations as pure functions is that pure functions are composable: that is, self-contained and stateless. These characteristics bring a number of benefits, including the following: Increased readability and maintainability. This is because each function is designed to accomplish a specific task given its arguments. The function does not rely on any external state.

Easier reiterative development. Because the code is easier to refactor, changes to design are often easier to implement. For example, suppose you write a complicated transformation, and then realize that some code is repeated several times in the transformation. If you refactor through a pure method, you can call your pure method at will without worrying about side effects.

Easier testing and debugging. Because pure functions can more easily be tested in isolation, you can write test code that calls the pure function with typical values, valid edge cases, and invalid edge cases.

For OOP People or Imperative languages:

Object-oriented languages are good when you have a fixed set of operations on things and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods and the existing classes are left alone.

Functional languages are good when you have a fixed set of things and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types and the existing functions are left alone.

Cons:

It depends on the user requirements to choose the way of programming, so there is harm only when users don’t choose the proper way.

When evolution goes the wrong way, you have problems:

  • Adding a new operation to an object-oriented program may require editing many class definitions to add a new method
  • Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

Make a link use POST instead of GET

HTML + JQuery: A link that submits a hidden form with POST.

Since I spent a lot of time to understand all these answers, and since all of them have some interesting details, here is the combined version that finally worked for me and which I prefer for its simplicity.

My approach is again to create a hidden form and to submit it by clicking a link somewhere else in the page. It doesn't matter where in the body of the page the form will be placed.

The code for the form:

<form id="myHiddenFormId" action="myAction.php" method="post" style="display: none">
  <input type="hidden" name="myParameterName" value="myParameterValue">
</form>

Description:

The display: none hides the form. You can alternatively put it in a div or another element and set the display: none on the element.

The type="hidden" will create an fild that will not be shown but its data will be transmitted to the action eitherways (see W3C). I understand that this is the simplest input type.

The code for the link:

<a href="" onclick="$('#myHiddenFormId').submit(); return false;" title="My link title">My link text</a>

Description:

The empty href just targets the same page. But it doesn't really matter in this case since the return false will stop the browser from following the link. You may want to change this behavior of course. In my specific case, the action contained a redirection at the end.

The onclick was used to avoid using href="javascript:..." as noted by mplungjan. The $('#myHiddenFormId').submit(); was used to submit the form (instead of defining a function, since the code is very small).

This link will look exactly like any other <a> element. You can actually use any other element instead of the <a> (for example a <span> or an image).

Bootstrap 3 navbar active li not changing background-color

in my case just removing background-image from nav-bar item solved the problem

.navbar-default .navbar-nav > .active > a:focus {
    .
    .
    .


    background-image: none;
}

Using jQuery to center a DIV on the screen

Why you don't use CSS for centering a div?

#timer_wrap{  
  position: fixed;
  left: 50%;
  top: 50%;
} 

Spring Test & Security: How to mock authentication?

Create a class TestUserDetailsImpl on your test package:

@Service
@Primary
@Profile("test")
public class TestUserDetailsImpl implements UserDetailsService {
    public static final String API_USER = "[email protected]";

    private User getAdminUser() {
        User user = new User();
        user.setUsername(API_USER);

        SimpleGrantedAuthority role = new SimpleGrantedAuthority("ROLE_API_USER");
        user.setAuthorities(Collections.singletonList(role));

        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) 
                                         throws UsernameNotFoundException {
        if (Objects.equals(username, ADMIN_USERNAME))
            return getAdminUser();
        throw new UsernameNotFoundException(username);
    }
}

Rest endpoint:

@GetMapping("/invoice")
@Secured("ROLE_API_USER")
public Page<InvoiceDTO> getInvoices(){
   ...
}

Test endpoint:

@Test
@WithUserDetails("[email protected]")
public void testApi() throws Exception {
     ...
}

delete word after or around cursor in VIM

It doesn't look like there's any built-in way to do it in insert mode, which was the question. Some of the other answers are correct for normal mode, as well as pointing out that a custom mapping could be created to add the functionality in insert mode.

Honestly, you should probably do most of your deleting in normal mode. ^W is neat to know about but I'm not sure I can think of a situation where I'd rather do it than esc to go into normal mode and have the more powerful deletion commands at my disposal.

Vim is very different from a number of other editors (including TextMate) in this way. If you're using it productively, you'll probably find that you don't spend very much time in insert mode.

Returning a boolean value in a JavaScript function

You could wrap your return value in the Boolean function

Boolean([return value])

That'll ensure all falsey values are false and truthy statements are true.

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

sklearn plot confusion matrix with labels

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

import numpy as np


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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

It will look like this enter image description here

Map enum in JPA with fixed values?

The problem is, I think, that JPA was never incepted with the idea in mind that we could have a complex preexisting Schema already in place.

I think there are two main shortcomings resulting from this, specific to Enum:

  1. The limitation of using name() and ordinal(). Why not just mark a getter with @Id, the way we do with @Entity?
  2. Enum's have usually representation in the database to allow association with all sorts of metadata, including a proper name, a descriptive name, maybe something with localization etc. We need the easy of use of an Enum combined with the flexibility of an Entity.

Help my cause and vote on JPA_SPEC-47

Would this not be more elegant than using a @Converter to solve the problem?

// Note: this code won't work!!
// it is just a sample of how I *would* want it to work!
@Enumerated
public enum Language {
  ENGLISH_US("en-US"),
  ENGLISH_BRITISH("en-BR"),
  FRENCH("fr"),
  FRENCH_CANADIAN("fr-CA");
  @ID
  private String code;
  @Column(name="DESCRIPTION")
  private String description;

  Language(String code) {
    this.code = code;
  }

  public String getCode() {
    return code;
  }

  public String getDescription() {
    return description;
  }
}

ConnectivityManager getNetworkInfo(int) deprecated

Something like this:

public boolean hasConnection(final Context context){
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNW = cm.getActiveNetworkInfo();
    if (activeNW != null && activeNW.isConnected())
    {
        return true;
    }
    return false;
}

And in the main program body:

if(hasConnection(this)) {
    Toast.makeText(this, "Active networks OK ", Toast.LENGTH_LONG).show();
    getAccountData(token, tel);
}
else  Toast.makeText(this, "No active networks... ", Toast.LENGTH_LONG).show();

"A referral was returned from the server" exception when accessing AD from C#

Had the same issue and managed to resolve it.

In my case, I had an AD group in the current logon domain with members (users) from a sub domain. The server that I was running the code on could not access the domain controller of the sub domain (the server had never needed to access the sub domain before).

I struggled for a while as my desktop PC could access the domain so everything looked OK in the MMC plugin (Active Directory Users & Computers).

Hope that helps someone else.

maven "cannot find symbol" message unhelpful

SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again

WHY SO :
I get this error many times. Most of the times I will try to build my component alone (As I have not made changes elsewhere).

Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times

How to get the client IP address in PHP

Here is a cleaner code sample of a good way to get the IP address of the user.

$ip = $_SERVER['HTTP_CLIENT_IP'] ? $_SERVER['HTTP_CLIENT_IP'] : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);

Here is a shorter version that uses the elvis operator:

$_SERVER['HTTP_CLIENT_IP'] ? : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? : $_SERVER['REMOTE_ADDR']);

Here is a version that uses isset to remove notices (thank you, @shasi kanth):

$ip = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];

How to change Hash values?

my_hash.each { |k, v| my_hash[k] = v.upcase } 

or, if you'd prefer to do it non-destructively, and return a new hash instead of modifying my_hash:

a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k] = v.upcase; h } 

This last version has the added benefit that you could transform the keys too.

Two models in one view in ASP MVC 3

Another option which doesn't have the need to create a custom Model is to use a Tuple<>.

@model Tuple<Person,Order>

It's not as clean as creating a new class which contains both, as per Andi's answer, but it is viable.

jQuery UI DatePicker to show month year only

Here's what I came up with. It hides the calendar without needing an extra style block and adds a clear button to deal with the problem of not being able to clear the value once you click on the input. Also works nicely with multiple monthpickers on the same page.

HTML:

<input type='text' class='monthpicker'>

JavaScript:

$(".monthpicker").datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "yy-mm",
    showButtonPanel: true,
    currentText: "This Month",
    onChangeMonthYear: function (year, month, inst) {
        $(this).val($.datepicker.formatDate('yy-mm', new Date(year, month - 1, 1)));
    },
    onClose: function(dateText, inst) {
        var month = $(".ui-datepicker-month :selected").val();
        var year = $(".ui-datepicker-year :selected").val();
        $(this).val($.datepicker.formatDate('yy-mm', new Date(year, month, 1)));
    }
}).focus(function () {
    $(".ui-datepicker-calendar").hide();
}).after(
    $("<a href='javascript: void(0);'>clear</a>").click(function() {
        $(this).prev().val('');
    })
);

Detecting input change in jQuery?

If you've got HTML5:

  • oninput (fires only when a change actually happens, but does so immediately)

Otherwise you need to check for all these events which might indicate a change to the input element's value:

  • onchange
  • onkeyup (not keydown or keypress as the input's value won't have the new keystroke in it yet)
  • onpaste (when supported)

and maybe:

  • onmouseup (I'm not sure about this one)

What Does This Mean in PHP -> or =>

=> is used in associative array key value assignment. Take a look at:

http://php.net/manual/en/language.types.array.php.

-> is used to access an object method or property. Example: $obj->method().

Move_uploaded_file() function is not working

If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.

But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.

First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.

Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data user, or group.

So in order to make this www-data get access first type in;

sudo chgrp "www-data" your_project_folder

once its done, if there is no write access to the following as well;

sudo chown g+w your_project_folder

That will do the trick in Linux.

Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.

Property 'value' does not exist on type 'EventTarget'

Best way is to use templating => add id to your input and then use it value

<input type="text" #notaryLockup (keyup) = "searchNotary(notaryLockup.value)"placeholder="Entrez des information" >

searchNotary(value: string) {
 // your logic
}

this way you will never have Typescript error when strict verification is activated => See angular Docs

Retrieve a Fragment from a ViewPager

You don't need to call getItem() or some other method at later stage to get the reference of a Fragment hosted inside ViewPager. If you want to update some data inside Fragment then use this approach: Update ViewPager dynamically?

Key is to set new data inside Adaper and call notifyDataSetChanged() which in turn will call getItemPosition(), passing you a reference of your Fragment and giving you a chance to update it. All other ways require you to keep reference to yourself or some other hack which is not a good solution.

@Override
public int getItemPosition(Object object) {
    if (object instanceof UpdateableFragment) {
        ((UpdateableFragment) object).update(xyzData);
    }
    //don't return POSITION_NONE, avoid fragment recreation. 
    return super.getItemPosition(object);
}

What is the Linux equivalent to DOS pause?

read does this:

user@host:~$ read -n1 -r -p "Press any key to continue..." key
[...]
user@host:~$ 

The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key.

If you are using Bash, you can also specify a timeout with -t, which causes read to return a failure when a key isn't pressed. So for example:

read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
if [ "$?" -eq "0" ]; then
    echo 'A key was pressed.'
else
    echo 'No key was pressed.'
fi

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

This solved my problem when I had to deal with HTML page with embedded JavaScript

WebElement empSalary =  driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);

count (non-blank) lines-of-code in bash

It's kinda going to depend on the number of files you have in the project. In theory you could use

grep -c '.' <list of files>

Where you can fill the list of files by using the find utility.

grep -c '.' `find -type f`

Would give you a line count per file.

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

how to cancel/abort ajax request in axios

Typically you want to cancel the previous ajax request and ignore it's coming response, only when a new ajax request of that instance is started, for this purpose, do the following:

Example: getting some comments from API:

// declare an ajax request's cancelToken (globally)
let ajaxRequest = null; 

function getComments() {

    // cancel  previous ajax if exists
    if (ajaxRequest ) {
        ajaxRequest.cancel(); 
    }

    // creates a new token for upcomming ajax (overwrite the previous one)
    ajaxRequest = axios.CancelToken.source();  

    return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
        console.log(response.data)
    }).catch(function(err) {
        if (axios.isCancel(err)) {
           console.log('Previous request canceled, new request is send', err.message);
        } else {
               // handle error
        }
    });
}

Hive cast string to date dd-MM-yyyy

AFAIK you must reformat your String in ISO format to be able to cast it as a Date:

cast(concat(substr(STR_DMY,7,4), '-',
            substr(STR_DMY,1,2), '-',
            substr(STR_DMY,4,2)
           )
     as date
     ) as DT

To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()

=> did you check the documentation by the way?

Alter user defined type in SQL Server

As devio says there is no way to simply edit a UDT if it's in use.

A work-round through SMS that worked for me was to generate a create script and make the appropriate changes; rename the existing UDT; run the create script; recompile the related sprocs and drop the renamed version.

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

Finding smallest value in an array most efficiently

You need too loop through the array, remembering the smallest value you've seen so far. Like this:

int smallest = INT_MAX;
for (int i = 0; i < array_length; i++) {
    if (array[i] < smallest) {
        smallest = array[i];
    }
}

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

const char* concatenation

The C way:

char buf[100];
strcpy(buf, one);
strcat(buf, two);

The C++ way:

std::string buf(one);
buf.append(two);

The compile-time way:

#define one "hello "
#define two "world"
#define concat(first, second) first second

const char* buf = concat(one, two);

How can I convert spaces to tabs in Vim or Linux?

In my case, I had multiple spaces(fields were separated by one or more space) that I wanted to replace with a tab. The following did it:

:% s/\s\+/\t/g

Duplicating a MySQL table, indices, and data

I found the same situation and the approach which I took was as follows:

  1. Execute SHOW CREATE TABLE <table name to clone> : This will give you the Create Table syntax for the table which you want to clone
  2. Run the CREATE TABLE query by changing the table name to clone the table.

This will create exact replica of the table which you want to clone along with indexes. The only thing which you then need is to rename the indexes (if required).

Does Django scale?

We're doing load testing now. We think we can support 240 concurrent requests (a sustained rate of 120 hits per second 24x7) without any significant degradation in the server performance. That would be 432,000 hits per hour. Response times aren't small (our transactions are large) but there's no degradation from our baseline performance as the load increases.

We're using Apache front-ending Django and MySQL. The OS is Red Hat Enterprise Linux (RHEL). 64-bit. We use mod_wsgi in daemon mode for Django. We've done no cache or database optimization other than to accept the defaults.

We're all in one VM on a 64-bit Dell with (I think) 32Gb RAM.

Since performance is almost the same for 20 or 200 concurrent users, we don't need to spend huge amounts of time "tweaking". Instead we simply need to keep our base performance up through ordinary SSL performance improvements, ordinary database design and implementation (indexing, etc.), ordinary firewall performance improvements, etc.

What we do measure is our load test laptops struggling under the insane workload of 15 processes running 16 concurrent threads of requests.

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

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

How to hide a navigation bar from first ViewController in Swift?

Call the set hide method in view Will appear and Disappear. if you will not call the method in view will disappear with status false.It will hide the navigation bar in complete navigation hierarchy

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.setNavigationBarHidden(true, animated: true)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationController?.setNavigationBarHidden(false, animated:true)
}

How to specify the JDK version in android studio?

In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:

Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase

What is the $? (dollar question mark) variable in shell scripting?

It is well suited for debugging in case your script exit if set -e is used. For example, put echo $? after the command that cause it to exit and see the returned error value.

How to declare or mark a Java method as deprecated?

Use both @Deprecated annotation and the @deprecated JavaDoc tag.

The @deprecated JavaDoc tag is used for documentation purposes.

The @Deprecated annotation instructs the compiler that the method is deprecated. Here is what it says in Sun/Oracles document on the subject:

Using the @Deprecated annotation to deprecate a class, method, or field ensures that all compilers will issue warnings when code uses that program element. In contrast, there is no guarantee that all compilers will always issue warnings based on the @deprecated Javadoc tag, though the Sun compilers currently do so. Other compilers may not issue such warnings. Thus, using the @Deprecated annotation to generate warnings is more portable that relying on the @deprecated Javadoc tag.

You can find the full document at How and When to Deprecate APIs

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Anybody knows any knowledge base open source?

How about one of the many wikis?

Kenny: I've used FlexWiki & ScrewTurn (abandoned).

someone else with RepPower to edit my post added this.
Wikipedia is powered by MediaWiki.

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

Configure hibernate to connect to database via JNDI Datasource

I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.

The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.

How can I download a file from a URL and save it in Rails?

I think this is the clearest way:

require 'open-uri'

File.write 'image.png', open('http://example.com/image.png').read

Why is January month 0 in Java Calendar?

In addition to DannySmurf's answer of laziness, I'll add that it's to encourage you to use the constants, such as Calendar.JANUARY.